MediaWiki REL1_35
MessageCache.php
Go to the documentation of this file.
1<?php
33use Psr\Log\LoggerAwareInterface;
34use Psr\Log\LoggerInterface;
36use Wikimedia\ScopedCallback;
37
42define( 'MSG_CACHE_VERSION', 2 );
43
50class MessageCache implements LoggerAwareInterface {
51 private const FOR_UPDATE = 1; // force message reload
52
54 private const WAIT_SEC = 15;
56 private const LOCK_TTL = 30;
57
62 private const WAN_TTL = IExpiringStore::TTL_DAY;
63
65 private $logger;
66
72 protected $cache;
73
80
84 protected $cacheVolatile = [];
85
90 protected $mDisable;
91
96 protected $mParserOptions;
98 protected $mParser;
99
103 protected $mInParser = false;
104
106 protected $wanCache;
108 protected $clusterCache;
110 protected $srvCache;
112 protected $contLang;
116 protected $langFactory;
124 private $hookRunner;
125
133 public static function singleton() {
134 return MediaWikiServices::getInstance()->getMessageCache();
135 }
136
143 public static function normalizeKey( $key ) {
144 $lckey = strtr( $key, ' ', '_' );
145 if ( ord( $lckey ) < 128 ) {
146 $lckey[0] = strtolower( $lckey[0] );
147 } else {
148 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
149 }
150
151 return $lckey;
152 }
153
171 public function __construct(
172 WANObjectCache $wanCache,
173 BagOStuff $clusterCache,
174 BagOStuff $serverCache,
175 Language $contLang,
176 ILanguageConverter $contLangConverter,
177 LoggerInterface $logger,
178 array $options,
179 LanguageFactory $langFactory,
180 LocalisationCache $localisationCache,
181 LanguageNameUtils $languageNameUtils,
182 LanguageFallback $languageFallback,
183 HookContainer $hookContainer
184 ) {
185 $this->wanCache = $wanCache;
186 $this->clusterCache = $clusterCache;
187 $this->srvCache = $serverCache;
188 $this->contLang = $contLang;
189 $this->contLangConverter = $contLangConverter;
190 $this->logger = $logger;
191 $this->langFactory = $langFactory;
192 $this->localisationCache = $localisationCache;
193 $this->languageNameUtils = $languageNameUtils;
194 $this->languageFallback = $languageFallback;
195 $this->hookRunner = new HookRunner( $hookContainer );
196
197 $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
198
199 $this->mDisable = !( $options['useDB'] ?? true );
200 }
201
202 public function setLogger( LoggerInterface $logger ) {
203 $this->logger = $logger;
204 }
205
211 private function getParserOptions() {
212 global $wgUser;
213
214 if ( !$this->mParserOptions ) {
215 if ( !$wgUser || !$wgUser->isSafeToLoad() ) {
216 // $wgUser isn't available yet, so don't try to get a
217 // ParserOptions for it. And don't cache this ParserOptions
218 // either.
219 $po = ParserOptions::newFromAnon();
220 $po->setAllowUnsafeRawHtml( false );
221 return $po;
222 }
223
224 $this->mParserOptions = new ParserOptions( $wgUser );
225 // Messages may take parameters that could come
226 // from malicious sources. As a precaution, disable
227 // the <html> parser tag when parsing messages.
228 $this->mParserOptions->setAllowUnsafeRawHtml( false );
229 }
230
231 return $this->mParserOptions;
232 }
233
240 protected function getLocalCache( $code ) {
241 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
242
243 return $this->srvCache->get( $cacheKey );
244 }
245
252 protected function saveToLocalCache( $code, $cache ) {
253 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
254 $this->srvCache->set( $cacheKey, $cache );
255 }
256
278 protected function load( $code, $mode = null ) {
279 if ( !is_string( $code ) ) {
280 throw new InvalidArgumentException( "Missing language code" );
281 }
282
283 # Don't do double loading...
284 if ( $this->isLanguageLoaded( $code ) && $mode != self::FOR_UPDATE ) {
285 return true;
286 }
287
288 # 8 lines of code just to say (once) that message cache is disabled
289 if ( $this->mDisable ) {
290 static $shownDisabled = false;
291 if ( !$shownDisabled ) {
292 $this->logger->debug( __METHOD__ . ': disabled' );
293 $shownDisabled = true;
294 }
295
296 return true;
297 }
298
299 # Loading code starts
300 $success = false; # Keep track of success
301 $staleCache = false; # a cache array with expired data, or false if none has been loaded
302 $where = []; # Debug info, delayed to avoid spamming debug log too much
303
304 # Hash of the contents is stored in memcache, to detect if data-center cache
305 # or local cache goes out of date (e.g. due to replace() on some other server)
306 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
307 $this->cacheVolatile[$code] = $hashVolatile;
308
309 # Try the local cache and check against the cluster hash key...
310 $cache = $this->getLocalCache( $code );
311 if ( !$cache ) {
312 $where[] = 'local cache is empty';
313 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
314 $where[] = 'local cache has the wrong hash';
315 $staleCache = $cache;
316 } elseif ( $this->isCacheExpired( $cache ) ) {
317 $where[] = 'local cache is expired';
318 $staleCache = $cache;
319 } elseif ( $hashVolatile ) {
320 $where[] = 'local cache validation key is expired/volatile';
321 $staleCache = $cache;
322 } else {
323 $where[] = 'got from local cache';
324 $this->cache->set( $code, $cache );
325 $success = true;
326 }
327
328 if ( !$success ) {
329 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
330 # Try the global cache. If it is empty, try to acquire a lock. If
331 # the lock can't be acquired, wait for the other thread to finish
332 # and then try the global cache a second time.
333 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
334 if ( $hashVolatile && $staleCache ) {
335 # Do not bother fetching the whole cache blob to avoid I/O.
336 # Instead, just try to get the non-blocking $statusKey lock
337 # below, and use the local stale value if it was not acquired.
338 $where[] = 'global cache is presumed expired';
339 } else {
340 $cache = $this->clusterCache->get( $cacheKey );
341 if ( !$cache ) {
342 $where[] = 'global cache is empty';
343 } elseif ( $this->isCacheExpired( $cache ) ) {
344 $where[] = 'global cache is expired';
345 $staleCache = $cache;
346 } elseif ( $hashVolatile ) {
347 # DB results are replica DB lag prone until the holdoff TTL passes.
348 # By then, updates should be reflected in loadFromDBWithLock().
349 # One thread regenerates the cache while others use old values.
350 $where[] = 'global cache is expired/volatile';
351 $staleCache = $cache;
352 } else {
353 $where[] = 'got from global cache';
354 $this->cache->set( $code, $cache );
355 $this->saveToCaches( $cache, 'local-only', $code );
356 $success = true;
357 }
358 }
359
360 if ( $success ) {
361 # Done, no need to retry
362 break;
363 }
364
365 # We need to call loadFromDB. Limit the concurrency to one process.
366 # This prevents the site from going down when the cache expires.
367 # Note that the DB slam protection lock here is non-blocking.
368 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
369 if ( $loadStatus === true ) {
370 $success = true;
371 break;
372 } elseif ( $staleCache ) {
373 # Use the stale cache while some other thread constructs the new one
374 $where[] = 'using stale cache';
375 $this->cache->set( $code, $staleCache );
376 $success = true;
377 break;
378 } elseif ( $failedAttempts > 0 ) {
379 # Already blocked once, so avoid another lock/unlock cycle.
380 # This case will typically be hit if memcached is down, or if
381 # loadFromDB() takes longer than LOCK_WAIT.
382 $where[] = "could not acquire status key.";
383 break;
384 } elseif ( $loadStatus === 'cantacquire' ) {
385 # Wait for the other thread to finish, then retry. Normally,
386 # the memcached get() will then yield the other thread's result.
387 $where[] = 'waited for other thread to complete';
388 $this->getReentrantScopedLock( $cacheKey );
389 } else {
390 # Disable cache; $loadStatus is 'disabled'
391 break;
392 }
393 }
394 }
395
396 if ( !$success ) {
397 $where[] = 'loading FAILED - cache is disabled';
398 $this->mDisable = true;
399 $this->cache->set( $code, [] );
400 $this->logger->error( __METHOD__ . ": Failed to load $code" );
401 # This used to throw an exception, but that led to nasty side effects like
402 # the whole wiki being instantly down if the memcached server died
403 }
404
405 if ( !$this->isLanguageLoaded( $code ) ) { // sanity
406 throw new LogicException( "Process cache for '$code' should be set by now." );
407 }
408
409 $info = implode( ', ', $where );
410 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
411
412 return $success;
413 }
414
421 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
422 # If cache updates on all levels fail, give up on message overrides.
423 # This is to avoid easy site outages; see $saveSuccess comments below.
424 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
425 $status = $this->clusterCache->get( $statusKey );
426 if ( $status === 'error' ) {
427 $where[] = "could not load; method is still globally disabled";
428 return 'disabled';
429 }
430
431 # Now let's regenerate
432 $where[] = 'loading from database';
433
434 # Lock the cache to prevent conflicting writes.
435 # This lock is non-blocking so stale cache can quickly be used.
436 # Note that load() will call a blocking getReentrantScopedLock()
437 # after this if it really need to wait for any current thread.
438 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
439 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
440 if ( !$scopedLock ) {
441 $where[] = 'could not acquire main lock';
442 return 'cantacquire';
443 }
444
445 $cache = $this->loadFromDB( $code, $mode );
446 $this->cache->set( $code, $cache );
447 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
448
449 if ( !$saveSuccess ) {
463 if ( $this->srvCache instanceof EmptyBagOStuff ) {
464 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
465 $where[] = 'could not save cache, disabled globally for 5 minutes';
466 } else {
467 $where[] = "could not save global cache";
468 }
469 }
470
471 return true;
472 }
473
483 protected function loadFromDB( $code, $mode = null ) {
485
486 // (T164666) The query here performs really poorly on WMF's
487 // contributions replicas. We don't have a way to say "any group except
488 // contributions", so for the moment let's specify 'api'.
489 // @todo: Get rid of this hack.
490 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
491
492 $cache = [];
493
494 $mostused = []; // list of "<cased message key>/<code>"
495 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
496 if ( !$this->cache->has( $wgLanguageCode ) ) {
497 $this->load( $wgLanguageCode );
498 }
499 $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
500 foreach ( $mostused as $key => $value ) {
501 $mostused[$key] = "$value/$code";
502 }
503 }
504
505 // Common conditions
506 $conds = [
507 'page_is_redirect' => 0,
508 'page_namespace' => NS_MEDIAWIKI,
509 ];
510 if ( count( $mostused ) ) {
511 $conds['page_title'] = $mostused;
512 } elseif ( $code !== $wgLanguageCode ) {
513 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
514 } else {
515 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
516 # other than language code.
517 $conds[] = 'page_title NOT' .
518 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
519 }
520
521 // Set the stubs for oversized software-defined messages in the main cache map
522 $res = $dbr->select(
523 'page',
524 [ 'page_title', 'page_latest' ],
525 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
526 __METHOD__ . "($code)-big"
527 );
528 foreach ( $res as $row ) {
529 // Include entries/stubs for all keys in $mostused in adaptive mode
530 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title )
531 ) {
532 $cache[$row->page_title] = '!TOO BIG';
533 }
534 // At least include revision ID so page changes are reflected in the hash
535 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
536 }
537
538 // Can not inject the RevisionStore as it would break the installer since
539 // it instantiates MessageCache before the DB.
540 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
541 // Set the text for small software-defined messages in the main cache map
542 $revQuery = $revisionStore->getQueryInfo( [ 'page', 'user' ] );
543
544 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
545 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
546 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
547 // `revision` first rather than `page`).
548 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
549 unset( $revQuery['joins']['page'] );
550 // It isn't actually necesssary to reorder $revQuery['tables'] as Database does the right thing
551 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
552 // `page` to the start.
553 $revQuery['tables'] = array_merge(
554 [ 'page' ],
555 array_diff( $revQuery['tables'], [ 'page' ] )
556 );
557
558 $res = $dbr->select(
559 $revQuery['tables'],
560 $revQuery['fields'],
561 array_merge( $conds, [
562 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
563 'page_latest = rev_id' // get the latest revision only
564 ] ),
565 __METHOD__ . "($code)-small",
566 [ 'STRAIGHT_JOIN' ],
567 $revQuery['joins']
568 );
569 foreach ( $res as $row ) {
570 // Include entries/stubs for all keys in $mostused in adaptive mode
571 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title )
572 ) {
573 try {
574 $rev = $revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
575 $content = $rev->getContent( MediaWiki\Revision\SlotRecord::MAIN );
576 $text = $this->getMessageTextFromContent( $content );
577 } catch ( Exception $ex ) {
578 $text = false;
579 }
580
581 if ( !is_string( $text ) ) {
582 $entry = '!ERROR';
583 $this->logger->error(
584 __METHOD__
585 . ": failed to load message page text for {$row->page_title} ($code)"
586 );
587 } else {
588 $entry = ' ' . $text;
589 }
590 $cache[$row->page_title] = $entry;
591 } else {
592 // T193271: cache object gets too big and slow to generate.
593 // At least include revision ID so page changes are reflected in the hash.
594 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
595 }
596 }
597
598 $cache['VERSION'] = MSG_CACHE_VERSION;
599 ksort( $cache );
600
601 # Hash for validating local cache (APC). No need to take into account
602 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
603 # stored and fetched from memcache.
604 $cache['HASH'] = md5( serialize( $cache ) );
605 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
606 unset( $cache['EXCESSIVE'] ); // only needed for hash
607
608 return $cache;
609 }
610
617 private function isLanguageLoaded( $lang ) {
618 // It is important that this only returns true if the cache was fully
619 // populated by load(), so that callers can assume all cache keys exist.
620 // It is possible for $this->cache to be only patially populated through
621 // methods like MessageCache::replace(), which must not make this method
622 // return true (T208897). And this method must cease to return true
623 // if the language was evicted by MapCacheLRU (T230690).
624 return $this->cache->hasField( $lang, 'VERSION' );
625 }
626
638 private function isMainCacheable( $name, $code = null ) {
639 global $wgLanguageCode;
640
641 // Convert first letter to lowercase, and strip /code suffix
642 $name = $this->contLang->lcfirst( $name );
643 // Include common conversion table pages. This also avoids problems with
644 // Installer::parse() bailing out due to disallowed DB queries (T207979).
645 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
646 return true;
647 }
648 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
649
650 if ( $code === null ) {
651 // Bulk load
652 if ( $this->systemMessageNames === null ) {
653 $this->systemMessageNames = array_flip(
654 $this->localisationCache->getSubitemList( $wgLanguageCode, 'messages' ) );
655 }
656 return isset( $this->systemMessageNames[$msg] );
657 } else {
658 // Use individual subitem
659 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
660 }
661 }
662
669 public function replace( $title, $text ) {
670 global $wgLanguageCode;
671
672 if ( $this->mDisable ) {
673 return;
674 }
675
676 list( $msg, $code ) = $this->figureMessage( $title );
677 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
678 // Content language overrides do not use the /<code> suffix
679 return;
680 }
681
682 // (a) Update the process cache with the new message text
683 if ( $text === false ) {
684 // Page deleted
685 $this->cache->setField( $code, $title, '!NONEXISTENT' );
686 } else {
687 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
688 $this->cache->setField( $code, $title, ' ' . $text );
689 }
690
691 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
692 DeferredUpdates::addUpdate(
693 new MessageCacheUpdate( $code, $title, $msg ),
694 DeferredUpdates::PRESEND
695 );
696 }
697
703 public function refreshAndReplaceInternal( $code, array $replacements ) {
705
706 // Allow one caller at a time to avoid race conditions
707 $scopedLock = $this->getReentrantScopedLock(
708 $this->clusterCache->makeKey( 'messages', $code )
709 );
710 if ( !$scopedLock ) {
711 foreach ( $replacements as list( $title ) ) {
712 $this->logger->error(
713 __METHOD__ . ': could not acquire lock to update {title} ({code})',
714 [ 'title' => $title, 'code' => $code ] );
715 }
716
717 return;
718 }
719
720 // Load the existing cache to update it in the local DC cache.
721 // The other DCs will see a hash mismatch.
722 if ( $this->load( $code, self::FOR_UPDATE ) ) {
723 $cache = $this->cache->get( $code );
724 } else {
725 // Err? Fall back to loading from the database.
726 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
727 }
728 // Check if individual cache keys should exist and update cache accordingly
729 $newTextByTitle = []; // map of (title => content)
730 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
731 foreach ( $replacements as list( $title ) ) {
732 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
733 $page->loadPageData( $page::READ_LATEST );
734 $text = $this->getMessageTextFromContent( $page->getContent() );
735 // Remember the text for the blob store update later on
736 $newTextByTitle[$title] = $text;
737 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
738 if ( !is_string( $text ) ) {
739 $cache[$title] = '!NONEXISTENT';
740 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
741 $cache[$title] = '!TOO BIG';
742 $newBigTitles[$title] = $page->getLatest();
743 } else {
744 $cache[$title] = ' ' . $text;
745 }
746 }
747 // Update HASH for the new key. Incorporates various administrative keys,
748 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
749 // and previous replace() calls), but that doesn't really matter since we
750 // only ever compare it for equality with a copy saved by saveToCaches().
751 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
752 // Update the too-big WAN cache entries now that we have the new HASH
753 foreach ( $newBigTitles as $title => $id ) {
754 // Match logic of loadCachedMessagePageEntry()
755 $this->wanCache->set(
756 $this->bigMessageCacheKey( $cache['HASH'], $title ),
757 ' ' . $newTextByTitle[$title],
758 self::WAN_TTL
759 );
760 }
761 // Mark this cache as definitely being "latest" (non-volatile) so
762 // load() calls do not try to refresh the cache with replica DB data
763 $cache['LATEST'] = time();
764 // Update the process cache
765 $this->cache->set( $code, $cache );
766 // Pre-emptively update the local datacenter cache so things like edit filter and
767 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
768 // The datacenter handling replace() calls should be the same one handling edits
769 // as they require HTTP POST.
770 $this->saveToCaches( $cache, 'all', $code );
771 // Release the lock now that the cache is saved
772 ScopedCallback::consume( $scopedLock );
773
774 // Relay the purge. Touching this check key expires cache contents
775 // and local cache (APC) validation hash across all datacenters.
776 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
777
778 // Purge the messages in the message blob store and fire any hook handlers
779 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
780 foreach ( $replacements as list( $title, $msg ) ) {
781 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
782 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
783 }
784 }
785
792 protected function isCacheExpired( $cache ) {
793 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
794 return true;
795 }
796 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
797 return true;
798 }
799 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
800 return true;
801 }
802
803 return false;
804 }
805
815 protected function saveToCaches( array $cache, $dest, $code = false ) {
816 if ( $dest === 'all' ) {
817 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
818 $success = $this->clusterCache->set( $cacheKey, $cache );
819 $this->setValidationHash( $code, $cache );
820 } else {
821 $success = true;
822 }
823
824 $this->saveToLocalCache( $code, $cache );
825
826 return $success;
827 }
828
835 protected function getValidationHash( $code ) {
836 $curTTL = null;
837 $value = $this->wanCache->get(
838 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
839 $curTTL,
840 [ $this->getCheckKey( $code ) ]
841 );
842
843 if ( $value ) {
844 $hash = $value['hash'];
845 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
846 // Cache was recently updated via replace() and should be up-to-date.
847 // That method is only called in the primary datacenter and uses FOR_UPDATE.
848 // Also, it is unlikely that the current datacenter is *now* secondary one.
849 $expired = false;
850 } else {
851 // See if the "check" key was bumped after the hash was generated
852 $expired = ( $curTTL < 0 );
853 }
854 } else {
855 // No hash found at all; cache must regenerate to be safe
856 $hash = false;
857 $expired = true;
858 }
859
860 return [ $hash, $expired ];
861 }
862
873 protected function setValidationHash( $code, array $cache ) {
874 $this->wanCache->set(
875 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
876 [
877 'hash' => $cache['HASH'],
878 'latest' => $cache['LATEST'] ?? 0
879 ],
880 WANObjectCache::TTL_INDEFINITE
881 );
882 }
883
889 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
890 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
891 }
892
926 public function get( $key, $useDB = true, $langcode = true ) {
927 if ( is_int( $key ) ) {
928 // Fix numerical strings that somehow become ints
929 // on their way here
930 $key = (string)$key;
931 } elseif ( !is_string( $key ) ) {
932 throw new MWException( 'Non-string key given' );
933 } elseif ( $key === '' ) {
934 // Shortcut: the empty key is always missing
935 return false;
936 }
937
938 // Normalise title-case input (with some inlining)
939 $lckey = self::normalizeKey( $key );
940
941 $this->hookRunner->onMessageCache__get( $lckey );
942
943 // Loop through each language in the fallback list until we find something useful
944 $message = $this->getMessageFromFallbackChain(
945 wfGetLangObj( $langcode ),
946 $lckey,
947 !$this->mDisable && $useDB
948 );
949
950 // If we still have no message, maybe the key was in fact a full key so try that
951 if ( $message === false ) {
952 $parts = explode( '/', $lckey );
953 // We may get calls for things that are http-urls from sidebar
954 // Let's not load nonexistent languages for those
955 // They usually have more than one slash.
956 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
957 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] );
958 if ( $message === null ) {
959 $message = false;
960 }
961 }
962 }
963
964 // Post-processing if the message exists
965 if ( $message !== false ) {
966 // Fix whitespace
967 $message = str_replace(
968 [
969 # Fix for trailing whitespace, removed by textarea
970 '&#32;',
971 # Fix for NBSP, converted to space by firefox
972 '&nbsp;',
973 '&#160;',
974 '&shy;'
975 ],
976 [
977 ' ',
978 "\u{00A0}",
979 "\u{00A0}",
980 "\u{00AD}"
981 ],
982 $message
983 );
984 }
985
986 return $message;
987 }
988
1001 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1002 $alreadyTried = [];
1003
1004 // First try the requested language.
1005 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1006 if ( $message !== false ) {
1007 return $message;
1008 }
1009
1010 // Now try checking the site language.
1011 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1012 return $message;
1013 }
1014
1025 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1026 $langcode = $lang->getCode();
1027
1028 // Try checking the database for the requested language
1029 if ( $useDB ) {
1030 $uckey = $this->contLang->ucfirst( $lckey );
1031
1032 if ( !isset( $alreadyTried[$langcode] ) ) {
1033 $message = $this->getMsgFromNamespace(
1034 $this->getMessagePageName( $langcode, $uckey ),
1035 $langcode
1036 );
1037 if ( $message !== false ) {
1038 return $message;
1039 }
1040 $alreadyTried[$langcode] = true;
1041 }
1042 } else {
1043 $uckey = null;
1044 }
1045
1046 // Check the CDB cache
1047 $message = $lang->getMessage( $lckey );
1048 if ( $message !== null ) {
1049 return $message;
1050 }
1051
1052 // Try checking the database for all of the fallback languages
1053 if ( $useDB ) {
1054 $fallbackChain = $this->languageFallback->getAll( $langcode );
1055
1056 foreach ( $fallbackChain as $code ) {
1057 if ( isset( $alreadyTried[$code] ) ) {
1058 continue;
1059 }
1060
1061 $message = $this->getMsgFromNamespace(
1062 $this->getMessagePageName( $code, $uckey ), $code );
1063
1064 if ( $message !== false ) {
1065 return $message;
1066 }
1067 $alreadyTried[$code] = true;
1068 }
1069 }
1070
1071 return false;
1072 }
1073
1081 private function getMessagePageName( $langcode, $uckey ) {
1082 global $wgLanguageCode;
1083
1084 if ( $langcode === $wgLanguageCode ) {
1085 // Messages created in the content language will not have the /lang extension
1086 return $uckey;
1087 } else {
1088 return "$uckey/$langcode";
1089 }
1090 }
1091
1104 public function getMsgFromNamespace( $title, $code ) {
1105 // Load all MediaWiki page definitions into cache. Note that individual keys
1106 // already loaded into cache during this request remain in the cache, which
1107 // includes the value of hook-defined messages.
1108 $this->load( $code );
1109
1110 $entry = $this->cache->getField( $code, $title );
1111
1112 if ( $entry !== null ) {
1113 // Message page exists as an override of a software messages
1114 if ( substr( $entry, 0, 1 ) === ' ' ) {
1115 // The message exists and is not '!TOO BIG' or '!ERROR'
1116 return (string)substr( $entry, 1 );
1117 } elseif ( $entry === '!NONEXISTENT' ) {
1118 // The text might be '-' or missing due to some data loss
1119 return false;
1120 }
1121 // Load the message page, utilizing the individual message cache.
1122 // If the page does not exist, there will be no hook handler fallbacks.
1123 $entry = $this->loadCachedMessagePageEntry(
1124 $title,
1125 $code,
1126 $this->cache->getField( $code, 'HASH' )
1127 );
1128 } else {
1129 // Message page either does not exist or does not override a software message
1130 if ( !$this->isMainCacheable( $title, $code ) ) {
1131 // Message page does not override any software-defined message. A custom
1132 // message might be defined to have content or settings specific to the wiki.
1133 // Load the message page, utilizing the individual message cache as needed.
1134 $entry = $this->loadCachedMessagePageEntry(
1135 $title,
1136 $code,
1137 $this->cache->getField( $code, 'HASH' )
1138 );
1139 }
1140 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1141 // Message does not have a MediaWiki page definition; try hook handlers
1142 $message = false;
1143 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1144 if ( $message !== false ) {
1145 $this->cache->setField( $code, $title, ' ' . $message );
1146 } else {
1147 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1148 }
1149
1150 return $message;
1151 }
1152 }
1153
1154 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1155 if ( $this->cacheVolatile[$code] ) {
1156 // Make sure that individual keys respect the WAN cache holdoff period too
1157 $this->logger->debug(
1158 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1159 [ 'titleKey' => $title, 'code' => $code ] );
1160 } else {
1161 $this->cache->setField( $code, $title, $entry );
1162 }
1163 // The message exists, so make sure a string is returned
1164 return (string)substr( $entry, 1 );
1165 }
1166
1167 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1168
1169 return false;
1170 }
1171
1178 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1179 $fname = __METHOD__;
1180 return $this->srvCache->getWithSetCallback(
1181 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1182 BagOStuff::TTL_HOUR,
1183 function () use ( $code, $dbKey, $hash, $fname ) {
1184 return $this->wanCache->getWithSetCallback(
1185 $this->bigMessageCacheKey( $hash, $dbKey ),
1186 self::WAN_TTL,
1187 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1188 // Try loading the message from the database
1189 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1190 // Use newKnownCurrent() to avoid querying revision/user tables
1191 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1192 // Injecting RevisionStore breaks installer since it
1193 // instantiates MessageCache before DB.
1194 $revision = MediaWikiServices::getInstance()
1195 ->getRevisionLookup()
1196 ->getKnownCurrentRevision( $title );
1197 if ( !$revision ) {
1198 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1199 // When overrides are created, self::replace() takes care of the cache.
1200 return '!NONEXISTENT';
1201 }
1202 $content = $revision->getContent( SlotRecord::MAIN );
1203 if ( $content ) {
1204 $message = $this->getMessageTextFromContent( $content );
1205 } else {
1206 $this->logger->warning(
1207 $fname . ': failed to load page text for \'{titleKey}\'',
1208 [ 'titleKey' => $dbKey, 'code' => $code ]
1209 );
1210 $message = null;
1211 }
1212
1213 if ( !is_string( $message ) ) {
1214 // Revision failed to load Content, or Content is incompatible with wikitext.
1215 // Possibly a temporary loading failure.
1216 $ttl = 5;
1217
1218 return '!NONEXISTENT';
1219 }
1220
1221 return ' ' . $message;
1222 }
1223 );
1224 }
1225 );
1226 }
1227
1235 public function transform( $message, $interface = false, $language = null, $title = null ) {
1236 // Avoid creating parser if nothing to transform
1237 if ( strpos( $message, '{{' ) === false ) {
1238 return $message;
1239 }
1240
1241 if ( $this->mInParser ) {
1242 return $message;
1243 }
1244
1245 $parser = $this->getParser();
1246 if ( $parser ) {
1247 $popts = $this->getParserOptions();
1248 $popts->setInterfaceMessage( $interface );
1249 $popts->setTargetLanguage( $language );
1250
1251 $userlang = $popts->setUserLang( $language );
1252 $this->mInParser = true;
1253 $message = $parser->transformMsg( $message, $popts, $title );
1254 $this->mInParser = false;
1255 $popts->setUserLang( $userlang );
1256 }
1257
1258 return $message;
1259 }
1260
1264 public function getParser() {
1265 if ( !$this->mParser ) {
1266 $parser = MediaWikiServices::getInstance()->getParser();
1267 # Do some initialisation so that we don't have to do it twice
1268 $parser->firstCallInit();
1269 # Clone it and store it
1270 $this->mParser = clone $parser;
1271 }
1272
1273 return $this->mParser;
1274 }
1275
1284 public function parse( $text, $title = null, $linestart = true,
1285 $interface = false, $language = null
1286 ) {
1287 global $wgTitle;
1288
1289 if ( $this->mInParser ) {
1290 return htmlspecialchars( $text );
1291 }
1292
1293 $parser = $this->getParser();
1294 $popts = $this->getParserOptions();
1295 $popts->setInterfaceMessage( $interface );
1296
1297 if ( is_string( $language ) ) {
1298 $language = $this->langFactory->getLanguage( $language );
1299 }
1300 $popts->setTargetLanguage( $language );
1301
1302 if ( !$title || !$title instanceof Title ) {
1303 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1304 $logger->info(
1305 __METHOD__ . ' called with no title set.',
1306 [ 'exception' => new Exception ]
1307 );
1308 $title = $wgTitle;
1309 }
1310 // Sometimes $wgTitle isn't set either...
1311 if ( !$title ) {
1312 # It's not uncommon having a null $wgTitle in scripts. See r80898
1313 # Create a ghost title in such case
1314 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1315 }
1316
1317 $this->mInParser = true;
1318 $res = $parser->parse( $text, $title, $popts, $linestart );
1319 $this->mInParser = false;
1320
1321 return $res;
1322 }
1323
1324 public function disable() {
1325 $this->mDisable = true;
1326 }
1327
1328 public function enable() {
1329 $this->mDisable = false;
1330 }
1331
1344 public function isDisabled() {
1345 return $this->mDisable;
1346 }
1347
1353 public function clear() {
1354 $langs = $this->languageNameUtils->getLanguageNames( null, 'mw' );
1355 foreach ( array_keys( $langs ) as $code ) {
1356 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1357 }
1358 $this->cache->clear();
1359 }
1360
1365 public function figureMessage( $key ) {
1366 global $wgLanguageCode;
1367
1368 $pieces = explode( '/', $key );
1369 if ( count( $pieces ) < 2 ) {
1370 return [ $key, $wgLanguageCode ];
1371 }
1372
1373 $lang = array_pop( $pieces );
1374 if ( !$this->languageNameUtils->getLanguageName( $lang, null, 'mw' ) ) {
1375 return [ $key, $wgLanguageCode ];
1376 }
1377
1378 $message = implode( '/', $pieces );
1379
1380 return [ $message, $lang ];
1381 }
1382
1391 public function getAllMessageKeys( $code ) {
1392 $this->load( $code );
1393 if ( !$this->cache->has( $code ) ) {
1394 // Apparently load() failed
1395 return null;
1396 }
1397 // Remove administrative keys
1398 $cache = $this->cache->get( $code );
1399 unset( $cache['VERSION'] );
1400 unset( $cache['EXPIRY'] );
1401 unset( $cache['EXCESSIVE'] );
1402 // Remove any !NONEXISTENT keys
1403 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1404
1405 // Keys may appear with a capital first letter. lcfirst them.
1406 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1407 }
1408
1416 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1417 $msgText = $this->getMessageTextFromContent( $content );
1418 if ( $msgText === null ) {
1419 $msgText = false; // treat as not existing
1420 }
1421
1422 $this->replace( $linkTarget->getDBkey(), $msgText );
1423
1424 if ( $this->contLangConverter->hasVariants() ) {
1425 $this->contLangConverter->updateConversionTable( $linkTarget );
1426 }
1427 }
1428
1433 public function getCheckKey( $code ) {
1434 return $this->wanCache->makeKey( 'messages', $code );
1435 }
1436
1441 private function getMessageTextFromContent( Content $content = null ) {
1442 // @TODO: could skip pseudo-messages like js/css here, based on content model
1443 if ( $content ) {
1444 // Message page exists...
1445 // XXX: Is this the right way to turn a Content object into a message?
1446 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1447 // CssContent. MessageContent is *not* used for storing messages, it's
1448 // only used for wrapping them when needed.
1449 $msgText = $content->getWikitextForTransclusion();
1450 if ( $msgText === false || $msgText === null ) {
1451 // This might be due to some kind of misconfiguration...
1452 $msgText = null;
1453 $this->logger->warning(
1454 __METHOD__ . ": message content doesn't provide wikitext "
1455 . "(content model: " . $content->getModel() . ")" );
1456 }
1457 } else {
1458 // Message page does not exist...
1459 $msgText = false;
1460 }
1461
1462 return $msgText;
1463 }
1464
1470 private function bigMessageCacheKey( $hash, $title ) {
1471 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1472 }
1473}
serialize()
$wgLanguageCode
Site language code.
$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.
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.
$wgTitle
Definition Setup.php:799
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:71
A BagOStuff object with no objects in it.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition Language.php:41
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.
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.
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 ...
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
transform( $message, $interface=false, $language=null, $title=null)
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.
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
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:85
Represents a title within MediaWiki.
Definition Title.php:42
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:50
const NS_MEDIAWIKI
Definition Defines.php:78
const NS_SPECIAL
Definition Defines.php:59
Base interface for content objects.
Definition Content.php:35
The shared interface for all language converters.
getDBkey()
Get the main part with underscores.
$cache
Definition mcc.php:33
A helper class for throttling authentication attempts.
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:29
$content
Definition router.php:76
return true
Definition router.php:92
if(!isset( $args[0])) $lang