Merge "Handle missing namespace prefix in XML dumps more gracefully"
[lhc/web/wiklou.git] / includes / cache / MessageCache.php
index 4e6b2fd..4facc20 100644 (file)
@@ -22,6 +22,7 @@
  */
 use MediaWiki\MediaWikiServices;
 use Wikimedia\ScopedCallback;
+use MediaWiki\Logger\LoggerFactory;
 
 /**
  * MediaWiki message cache structure version.
@@ -52,6 +53,11 @@ class MessageCache {
         */
        protected $mCache;
 
+       /**
+        * @var bool[] Map of (language code => boolean)
+        */
+       protected $mCacheVolatile = [];
+
        /**
         * Should mean that database cannot be used, but check
         * @var bool $mDisable
@@ -65,10 +71,12 @@ class MessageCache {
        protected $mExpiry;
 
        /**
-        * Message cache has its own parser which it uses to transform
-        * messages.
+        * Message cache has its own parser which it uses to transform messages
+        * @var ParserOptions
         */
-       protected $mParserOptions, $mParser;
+       protected $mParserOptions;
+       /** @var Parser */
+       protected $mParser;
 
        /**
         * Variable for tracking which variables are already loaded
@@ -81,10 +89,12 @@ class MessageCache {
         */
        protected $mInParser = false;
 
-       /** @var BagOStuff */
-       protected $mMemc;
        /** @var WANObjectCache */
        protected $wanCache;
+       /** @var BagOStuff */
+       protected $clusterCache;
+       /** @var BagOStuff */
+       protected $srvCache;
 
        /**
         * Singleton instance
@@ -101,9 +111,13 @@ class MessageCache {
         */
        public static function singleton() {
                if ( self::$instance === null ) {
-                       global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
+                       global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
                        self::$instance = new self(
+                               MediaWikiServices::getInstance()->getMainWANObjectCache(),
                                wfGetMessageCacheStorage(),
+                               $wgUseLocalMessageCache
+                                       ? MediaWikiServices::getInstance()->getLocalServerObjectCache()
+                                       : new EmptyBagOStuff(),
                                $wgUseDatabaseMessages,
                                $wgMsgCacheExpiry
                        );
@@ -129,6 +143,7 @@ class MessageCache {
         */
        public static function normalizeKey( $key ) {
                global $wgContLang;
+
                $lckey = strtr( $key, ' ', '_' );
                if ( ord( $lckey ) < 128 ) {
                        $lckey[0] = strtolower( $lckey[0] );
@@ -140,24 +155,25 @@ class MessageCache {
        }
 
        /**
-        * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
-        * @param bool $useDB
+        * @param WANObjectCache $wanCache WAN cache instance
+        * @param BagOStuff $clusterCache Cluster cache instance
+        * @param BagOStuff $srvCache Server cache instance
+        * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
         * @param int $expiry Lifetime for cache. @see $mExpiry.
         */
-       function __construct( BagOStuff $memCached, $useDB, $expiry ) {
-               global $wgUseLocalMessageCache;
+       public function __construct(
+               WANObjectCache $wanCache,
+               BagOStuff $clusterCache,
+               BagOStuff $srvCache,
+               $useDB,
+               $expiry
+       ) {
+               $this->wanCache = $wanCache;
+               $this->clusterCache = $clusterCache;
+               $this->srvCache = $srvCache;
 
-               $this->mMemc = $memCached;
                $this->mDisable = !$useDB;
                $this->mExpiry = $expiry;
-
-               if ( $wgUseLocalMessageCache ) {
-                       $this->localCache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
-               } else {
-                       $this->localCache = new EmptyBagOStuff();
-               }
-
-               $this->wanCache = ObjectCache::getMainWANInstance();
        }
 
        /**
@@ -194,7 +210,7 @@ class MessageCache {
        protected function getLocalCache( $code ) {
                $cacheKey = wfMemcKey( __CLASS__, $code );
 
-               return $this->localCache->get( $cacheKey );
+               return $this->srvCache->get( $cacheKey );
        }
 
        /**
@@ -205,7 +221,7 @@ class MessageCache {
         */
        protected function saveToLocalCache( $code, $cache ) {
                $cacheKey = wfMemcKey( __CLASS__, $code );
-               $this->localCache->set( $cacheKey, $cache );
+               $this->srvCache->set( $cacheKey, $cache );
        }
 
        /**
@@ -258,6 +274,7 @@ class MessageCache {
                # Hash of the contents is stored in memcache, to detect if data-center cache
                # or local cache goes out of date (e.g. due to replace() on some other server)
                list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
+               $this->mCacheVolatile[$code] = $hashVolatile;
 
                # Try the local cache and check against the cluster hash key...
                $cache = $this->getLocalCache( $code );
@@ -290,7 +307,7 @@ class MessageCache {
                                        # below, and use the local stale value if it was not acquired.
                                        $where[] = 'global cache is presumed expired';
                                } else {
-                                       $cache = $this->mMemc->get( $cacheKey );
+                                       $cache = $this->clusterCache->get( $cacheKey );
                                        if ( !$cache ) {
                                                $where[] = 'global cache is empty';
                                        } elseif ( $this->isCacheExpired( $cache ) ) {
@@ -371,12 +388,10 @@ class MessageCache {
         * @return bool|string True on success or one of ("cantacquire", "disabled")
         */
        protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
-               global $wgUseLocalMessageCache;
-
                # If cache updates on all levels fail, give up on message overrides.
                # This is to avoid easy site outages; see $saveSuccess comments below.
                $statusKey = wfMemcKey( 'messages', $code, 'status' );
-               $status = $this->mMemc->get( $statusKey );
+               $status = $this->clusterCache->get( $statusKey );
                if ( $status === 'error' ) {
                        $where[] = "could not load; method is still globally disabled";
                        return 'disabled';
@@ -414,8 +429,8 @@ class MessageCache {
                         * incurring a loadFromDB() overhead on every request, and thus saves the
                         * wiki from complete downtime under moderate traffic conditions.
                         */
-                       if ( !$wgUseLocalMessageCache ) {
-                               $this->mMemc->set( $statusKey, 'error', 60 * 5 );
+                       if ( $this->srvCache instanceof EmptyBagOStuff ) {
+                               $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
                                $where[] = 'could not save cache, disabled globally for 5 minutes';
                        } else {
                                $where[] = "could not save global cache";
@@ -434,7 +449,7 @@ class MessageCache {
         * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
         * @return array Loaded messages for storing in caches
         */
-       function loadFromDB( $code, $mode = null ) {
+       protected function loadFromDB( $code, $mode = null ) {
                global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
 
                $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA );
@@ -473,9 +488,16 @@ class MessageCache {
                $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
 
                # Load titles for all oversized pages in the MediaWiki namespace
-               $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
+               $res = $dbr->select(
+                       'page',
+                       [ 'page_title', 'page_latest' ],
+                       $bigConds,
+                       __METHOD__ . "($code)-big"
+               );
                foreach ( $res as $row ) {
                        $cache[$row->page_title] = '!TOO BIG';
+                       // At least include revision ID so page changes are reflected in the hash
+                       $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
                }
 
                # Conditions to load the remaining pages with their contents
@@ -501,7 +523,7 @@ class MessageCache {
                                wfDebugLog(
                                        'MessageCache',
                                        __METHOD__
-                                               . ": failed to load message page text for {$row->page_title} ($code)"
+                                       . ": failed to load message page text for {$row->page_title} ($code)"
                                );
                        } else {
                                $entry = ' ' . $text;
@@ -524,11 +546,11 @@ class MessageCache {
        /**
         * Updates cache as necessary when message page is changed
         *
-        * @param string|bool $title Name of the page changed (false if deleted)
-        * @param mixed $text New contents of the page.
+        * @param string $title Message cache key with initial uppercase letter.
+        * @param string|bool $text New contents of the page (false if deleted)
         */
        public function replace( $title, $text ) {
-               global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
+               global $wgLanguageCode;
 
                if ( $this->mDisable ) {
                        return;
@@ -540,62 +562,76 @@ class MessageCache {
                        return;
                }
 
-               // Note that if the cache is volatile, load() may trigger a DB fetch.
-               // In that case we reenter/reuse the existing cache key lock to avoid
-               // a self-deadlock. This is safe as no reads happen *directly* in this
-               // method between getReentrantScopedLock() and load() below. There is
-               // no risk of data "changing under our feet" for replace().
-               $cacheKey = wfMemcKey( 'messages', $code );
-               $scopedLock = $this->getReentrantScopedLock( $cacheKey );
-               $this->load( $code, self::FOR_UPDATE );
-
-               $titleKey = wfMemcKey( 'messages', 'individual', $title );
+               // (a) Update the process cache with the new message text
                if ( $text === false ) {
-                       // Article was deleted
+                       // Page deleted
                        $this->mCache[$code][$title] = '!NONEXISTENT';
-                       $this->wanCache->delete( $titleKey );
-               } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
-                       // Check for size
-                       $this->mCache[$code][$title] = '!TOO BIG';
-                       $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
                } else {
+                       // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
                        $this->mCache[$code][$title] = ' ' . $text;
-                       $this->wanCache->delete( $titleKey );
-               }
-
-               // Mark this cache as definitely "latest" (non-volatile) so
-               // load() calls do try to refresh the cache with replica DB data
-               $this->mCache[$code]['LATEST'] = time();
-
-               // Update caches if the lock was acquired
-               if ( $scopedLock ) {
-                       $this->saveToCaches( $this->mCache[$code], 'all', $code );
                }
 
-               ScopedCallback::consume( $scopedLock );
-               // Relay the purge. Touching this check key expires cache contents
-               // and local cache (APC) validation hash across all datacenters.
-               $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
-
-               // Also delete cached sidebar... just in case it is affected
-               $codes = [ $code ];
-               if ( $code === 'en' ) {
-                       // Delete all sidebars, like for example on action=purge on the
-                       // sidebar messages
-                       $codes = array_keys( Language::fetchLanguageNames() );
-               }
-
-               foreach ( $codes as $code ) {
-                       $sidebarKey = wfMemcKey( 'sidebar', $code );
-                       $this->wanCache->delete( $sidebarKey );
-               }
+               // (b) Update the shared caches in a deferred update with a fresh DB snapshot
+               DeferredUpdates::addCallableUpdate(
+                       function () use ( $title, $msg, $code ) {
+                               global $wgContLang, $wgMaxMsgCacheEntrySize;
+                               // Allow one caller at a time to avoid race conditions
+                               $scopedLock = $this->getReentrantScopedLock( wfMemcKey( 'messages', $code ) );
+                               if ( !$scopedLock ) {
+                                       LoggerFactory::getInstance( 'MessageCache' )->error(
+                                               __METHOD__ . ': could not acquire lock to update {title} ({code})',
+                                               [ 'title' => $title, 'code' => $code ] );
+                                       return;
+                               }
+                               // Load the messages from the master DB to avoid race conditions
+                               $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
+                               $this->mCache[$code] = $cache;
+                               // Load the process cache values and set the per-title cache keys
+                               $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
+                               $page->loadPageData( $page::READ_LATEST );
+                               $text = $this->getMessageTextFromContent( $page->getContent() );
+                               // Check if an individual cache key should exist and update cache accordingly
+                               $titleKey = $this->wanCache->makeKey(
+                                       'messages-big', $this->mCache[$code]['HASH'], $title );
+                               if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
+                                       $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
+                               }
+                               // Mark this cache as definitely being "latest" (non-volatile) so
+                               // load() calls do try to refresh the cache with replica DB data
+                               $this->mCache[$code]['LATEST'] = time();
+                               // Pre-emptively update the local datacenter cache so things like edit filter and
+                               // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
+                               // The datacenter handling replace() calls should be the same one handling edits
+                               // as they require HTTP POST.
+                               $this->saveToCaches( $this->mCache[$code], 'all', $code );
+                               // Release the lock now that the cache is saved
+                               ScopedCallback::consume( $scopedLock );
+
+                               // Relay the purge. Touching this check key expires cache contents
+                               // and local cache (APC) validation hash across all datacenters.
+                               $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
+                               // Also delete cached sidebar... just in case it is affected
+                               // @TODO: shouldn't this be $code === $wgLanguageCode?
+                               if ( $code === 'en' ) {
+                                       // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
+                                       $codes = array_keys( Language::fetchLanguageNames() );
+                               } else {
+                                       // Purge only the sidebar for this language
+                                       $codes = [ $code ];
+                               }
+                               foreach ( $codes as $code ) {
+                                       $this->wanCache->delete( wfMemcKey( 'sidebar', $code ) );
+                               }
 
-               // Update the message in the message blob store
-               $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
-               $blobStore = $resourceloader->getMessageBlobStore();
-               $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
+                               // Purge the message in the message blob store
+                               $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
+                               $blobStore = $resourceloader->getMessageBlobStore();
+                               $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
 
-               Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
+                               Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
+                       },
+                       DeferredUpdates::PRESEND
+               );
        }
 
        /**
@@ -630,7 +666,7 @@ class MessageCache {
        protected function saveToCaches( array $cache, $dest, $code = false ) {
                if ( $dest === 'all' ) {
                        $cacheKey = wfMemcKey( 'messages', $code );
-                       $success = $this->mMemc->set( $cacheKey, $cache );
+                       $success = $this->clusterCache->set( $cacheKey, $cache );
                        $this->setValidationHash( $code, $cache );
                } else {
                        $success = true;
@@ -650,24 +686,26 @@ class MessageCache {
        protected function getValidationHash( $code ) {
                $curTTL = null;
                $value = $this->wanCache->get(
-                       wfMemcKey( 'messages', $code, 'hash', 'v1' ),
+                       $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
                        $curTTL,
                        [ wfMemcKey( 'messages', $code ) ]
                );
 
-               if ( !$value ) {
-                       // No hash found at all; cache must regenerate to be safe
-                       $hash = false;
-                       $expired = true;
-               } else {
+               if ( $value ) {
                        $hash = $value['hash'];
-                       if ( ( time() - $value['latest'] ) < WANObjectCache::HOLDOFF_TTL ) {
-                               // Cache was recently updated via replace() and should be up-to-date
+                       if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
+                               // Cache was recently updated via replace() and should be up-to-date.
+                               // That method is only called in the primary datacenter and uses FOR_UPDATE.
+                               // Also, it is unlikely that the current datacenter is *now* secondary one.
                                $expired = false;
                        } else {
                                // See if the "check" key was bumped after the hash was generated
                                $expired = ( $curTTL < 0 );
                        }
+               } else {
+                       // No hash found at all; cache must regenerate to be safe
+                       $hash = false;
+                       $expired = true;
                }
 
                return [ $hash, $expired ];
@@ -677,14 +715,15 @@ class MessageCache {
         * Set the md5 used to validate the local disk cache
         *
         * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
-        * be treated as "volatile" by getValidationHash() for the next few seconds
+        * be treated as "volatile" by getValidationHash() for the next few seconds.
+        * This is triggered when $cache is generated using FOR_UPDATE mode.
         *
         * @param string $code
         * @param array $cache Cached messages with a version
         */
        protected function setValidationHash( $code, array $cache ) {
                $this->wanCache->set(
-                       wfMemcKey( 'messages', $code, 'hash', 'v1' ),
+                       $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
                        [
                                'hash' => $cache['HASH'],
                                'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
@@ -699,7 +738,7 @@ class MessageCache {
         * @return null|ScopedCallback
         */
        protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
-               return $this->mMemc->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
+               return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
        }
 
        /**
@@ -824,7 +863,7 @@ class MessageCache {
 
                $alreadyTried = [];
 
-                // First try the requested language.
+               // First try the requested language.
                $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
                if ( $message !== false ) {
                        return $message;
@@ -847,6 +886,7 @@ class MessageCache {
         */
        private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
                global $wgContLang;
+
                $langcode = $lang->getCode();
 
                // Try checking the database for the requested language
@@ -905,6 +945,7 @@ class MessageCache {
         */
        private function getMessagePageName( $langcode, $uckey ) {
                global $wgLanguageCode;
+
                if ( $langcode === $wgLanguageCode ) {
                        // Messages created in the content language will not have the /lang extension
                        return $uckey;
@@ -927,11 +968,11 @@ class MessageCache {
         */
        public function getMsgFromNamespace( $title, $code ) {
                $this->load( $code );
+
                if ( isset( $this->mCache[$code][$title] ) ) {
                        $entry = $this->mCache[$code][$title];
                        if ( substr( $entry, 0, 1 ) === ' ' ) {
-                               // The message exists, so make sure a string
-                               // is returned.
+                               // The message exists, so make sure a string is returned.
                                return (string)substr( $entry, 1 );
                        } elseif ( $entry === '!NONEXISTENT' ) {
                                return false;
@@ -941,7 +982,7 @@ class MessageCache {
                } else {
                        // XXX: This is not cached in process cache, should it?
                        $message = false;
-                       Hooks::run( 'MessagesPreLoad', [ $title, &$message ] );
+                       Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
                        if ( $message !== false ) {
                                return $message;
                        }
@@ -950,17 +991,19 @@ class MessageCache {
                }
 
                // Try the individual message cache
-               $titleKey = wfMemcKey( 'messages', 'individual', $title );
-
-               $curTTL = null;
-               $entry = $this->wanCache->get(
-                       $titleKey,
-                       $curTTL,
-                       [ wfMemcKey( 'messages', $code ) ]
-               );
-               $entry = ( $curTTL >= 0 ) ? $entry : false;
+               $titleKey = $this->wanCache->makeKey( 'messages-big', $this->mCache[$code]['HASH'], $title );
+
+               if ( $this->mCacheVolatile[$code] ) {
+                       $entry = false;
+                       // Make sure that individual keys respect the WAN cache holdoff period too
+                       LoggerFactory::getInstance( 'MessageCache' )->debug(
+                               __METHOD__ . ': loading volatile key \'{titleKey}\'',
+                               [ 'titleKey' => $titleKey, 'code' => $code ] );
+               } else {
+                       $entry = $this->wanCache->get( $titleKey );
+               }
 
-               if ( $entry ) {
+               if ( $entry !== false ) {
                        if ( substr( $entry, 0, 1 ) === ' ' ) {
                                $this->mCache[$code][$title] = $entry;
                                // The message exists, so make sure a string is returned
@@ -975,7 +1018,7 @@ class MessageCache {
                        }
                }
 
-               // Try loading it from the database
+               // Try loading the message from the database
                $dbr = wfGetDB( DB_REPLICA );
                $cacheOpts = Database::getCacheSetOptions( $dbr );
                // Use newKnownCurrent() to avoid querying revision/user tables
@@ -992,32 +1035,18 @@ class MessageCache {
 
                if ( $revision ) {
                        $content = $revision->getContent();
-                       if ( !$content ) {
-                               // A possibly temporary loading failure.
-                               wfDebugLog(
-                                       'MessageCache',
-                                       __METHOD__ . ": failed to load message page text for {$title} ($code)"
-                               );
-                               $message = null; // no negative caching
-                       } else {
-                               // XXX: Is this the right way to turn a Content object into a message?
-                               // NOTE: $content is typically either WikitextContent, JavaScriptContent or
-                               //       CssContent. MessageContent is *not* used for storing messages, it's
-                               //       only used for wrapping them when needed.
-                               $message = $content->getWikitextForTransclusion();
-
-                               if ( $message === false || $message === null ) {
-                                       wfDebugLog(
-                                               'MessageCache',
-                                               __METHOD__ . ": message content doesn't provide wikitext "
-                                                       . "(content model: " . $content->getModel() . ")"
-                                       );
-
-                                       $message = false; // negative caching
-                               } else {
+                       if ( $content ) {
+                               $message = $this->getMessageTextFromContent( $content );
+                               if ( is_string( $message ) ) {
                                        $this->mCache[$code][$title] = ' ' . $message;
                                        $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry, $cacheOpts );
                                }
+                       } else {
+                               // A possibly temporary loading failure
+                               LoggerFactory::getInstance( 'MessageCache' )->warning(
+                                       __METHOD__ . ': failed to load message page text for \'{titleKey}\'',
+                                       [ 'titleKey' => $titleKey, 'code' => $code ] );
+                               $message = null; // no negative caching
                        }
                } else {
                        $message = false; // negative caching
@@ -1069,6 +1098,7 @@ class MessageCache {
         */
        function getParser() {
                global $wgParser, $wgParserConf;
+
                if ( !$this->mParser && isset( $wgParser ) ) {
                        # Do some initialisation so that we don't have to do it twice
                        $wgParser->firstCallInit();
@@ -1096,6 +1126,8 @@ class MessageCache {
        public function parse( $text, $title = null, $linestart = true,
                $interface = false, $language = null
        ) {
+               global $wgTitle;
+
                if ( $this->mInParser ) {
                        return htmlspecialchars( $text );
                }
@@ -1110,7 +1142,6 @@ class MessageCache {
                $popts->setTargetLanguage( $language );
 
                if ( !$title || !$title instanceof Title ) {
-                       global $wgTitle;
                        wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
                                wfGetAllCallers( 6 ) . ' with no title set.' );
                        $title = $wgTitle;
@@ -1198,6 +1229,7 @@ class MessageCache {
         */
        public function getAllMessageKeys( $code ) {
                global $wgContLang;
+
                $this->load( $code );
                if ( !isset( $this->mCache[$code] ) ) {
                        // Apparently load() failed
@@ -1207,10 +1239,61 @@ class MessageCache {
                $cache = $this->mCache[$code];
                unset( $cache['VERSION'] );
                unset( $cache['EXPIRY'] );
+               unset( $cache['EXCESSIVE'] );
                // Remove any !NONEXISTENT keys
                $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
 
                // Keys may appear with a capital first letter. lcfirst them.
                return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
        }
+
+       /**
+        * Purge message caches when a MediaWiki: page is created, updated, or deleted
+        *
+        * @param Title $title Message page title
+        * @param Content|null $content New content for edit/create, null on deletion
+        * @since 1.29
+        */
+       public function updateMessageOverride( Title $title, Content $content = null ) {
+               global $wgContLang;
+
+               $msgText = $this->getMessageTextFromContent( $content );
+               if ( $msgText === null ) {
+                       $msgText = false; // treat as not existing
+               }
+
+               $this->replace( $title->getDBkey(), $msgText );
+
+               if ( $wgContLang->hasVariants() ) {
+                       $wgContLang->updateConversionTable( $title );
+               }
+       }
+
+       /**
+        * @param Content|null $content Content or null if the message page does not exist
+        * @return string|bool|null Returns false if $content is null and null on error
+        */
+       private function getMessageTextFromContent( Content $content = null ) {
+               // @TODO: could skip pseudo-messages like js/css here, based on content model
+               if ( $content ) {
+                       // Message page exists...
+                       // XXX: Is this the right way to turn a Content object into a message?
+                       // NOTE: $content is typically either WikitextContent, JavaScriptContent or
+                       //       CssContent. MessageContent is *not* used for storing messages, it's
+                       //       only used for wrapping them when needed.
+                       $msgText = $content->getWikitextForTransclusion();
+                       if ( $msgText === false || $msgText === null ) {
+                               // This might be due to some kind of misconfiguration...
+                               $msgText = null;
+                               LoggerFactory::getInstance( 'MessageCache' )->warning(
+                                       __METHOD__ . ": message content doesn't provide wikitext "
+                                       . "(content model: " . $content->getModel() . ")" );
+                       }
+               } else {
+                       // Message page does not exist...
+                       $msgText = false;
+               }
+
+               return $msgText;
+       }
 }