93fdb162e283688b8381f5efdcff9bac6cfd0673
[lhc/web/wiklou.git] / includes / cache / MessageCache.php
1 <?php
2 /**
3 * Localisation messages cache.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Cache
22 */
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\ScopedCallback;
25 use MediaWiki\Logger\LoggerFactory;
26 use Wikimedia\Rdbms\Database;
27
28 /**
29 * MediaWiki message cache structure version.
30 * Bump this whenever the message cache format has changed.
31 */
32 define( 'MSG_CACHE_VERSION', 2 );
33
34 /**
35 * Cache of messages that are defined by MediaWiki namespace pages or by hooks
36 *
37 * Performs various MediaWiki namespace-related functions
38 * @ingroup Cache
39 */
40 class MessageCache {
41 const FOR_UPDATE = 1; // force message reload
42
43 /** How long to wait for memcached locks */
44 const WAIT_SEC = 15;
45 /** How long memcached locks last */
46 const LOCK_TTL = 30;
47
48 /**
49 * Process cache of loaded messages that are defined in MediaWiki namespace
50 *
51 * @var MapCacheLRU Map of (language code => key => " <MESSAGE>" or "!TOO BIG" or "!ERROR")
52 */
53 protected $cache;
54
55 /**
56 * Map of (lowercase message key => index) for all software defined messages
57 *
58 * @var array
59 */
60 protected $overridable;
61
62 /**
63 * @var bool[] Map of (language code => boolean)
64 */
65 protected $cacheVolatile = [];
66
67 /**
68 * Should mean that database cannot be used, but check
69 * @var bool $mDisable
70 */
71 protected $mDisable;
72
73 /**
74 * Lifetime for cache, used by object caching.
75 * Set on construction, see __construct().
76 */
77 protected $mExpiry;
78
79 /**
80 * Message cache has its own parser which it uses to transform messages
81 * @var ParserOptions
82 */
83 protected $mParserOptions;
84 /** @var Parser */
85 protected $mParser;
86
87 /**
88 * @var bool $mInParser
89 */
90 protected $mInParser = false;
91
92 /** @var WANObjectCache */
93 protected $wanCache;
94 /** @var BagOStuff */
95 protected $clusterCache;
96 /** @var BagOStuff */
97 protected $srvCache;
98 /** @var Language */
99 protected $contLang;
100
101 /**
102 * Track which languages have been loaded by load().
103 * @var array
104 */
105 private $loadedLanguages = [];
106
107 /**
108 * Get the singleton instance of this class
109 *
110 * @deprecated in 1.34 inject an instance of this class instead of using global state
111 * @since 1.18
112 * @return MessageCache
113 */
114 public static function singleton() {
115 return MediaWikiServices::getInstance()->getMessageCache();
116 }
117
118 /**
119 * Normalize message key input
120 *
121 * @param string $key Input message key to be normalized
122 * @return string Normalized message key
123 */
124 public static function normalizeKey( $key ) {
125 $lckey = strtr( $key, ' ', '_' );
126 if ( ord( $lckey ) < 128 ) {
127 $lckey[0] = strtolower( $lckey[0] );
128 } else {
129 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
130 }
131
132 return $lckey;
133 }
134
135 /**
136 * @param WANObjectCache $wanCache
137 * @param BagOStuff $clusterCache
138 * @param BagOStuff $serverCache
139 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
140 * @param int $expiry Lifetime for cache. @see $mExpiry.
141 * @param Language|null $contLang Content language of site
142 */
143 public function __construct(
144 WANObjectCache $wanCache,
145 BagOStuff $clusterCache,
146 BagOStuff $serverCache,
147 $useDB,
148 $expiry,
149 Language $contLang = null
150 ) {
151 $this->wanCache = $wanCache;
152 $this->clusterCache = $clusterCache;
153 $this->srvCache = $serverCache;
154
155 $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
156
157 $this->mDisable = !$useDB;
158 $this->mExpiry = $expiry;
159 $this->contLang = $contLang ?? MediaWikiServices::getInstance()->getContentLanguage();
160 }
161
162 /**
163 * ParserOptions is lazy initialised.
164 *
165 * @return ParserOptions
166 */
167 function getParserOptions() {
168 global $wgUser;
169
170 if ( !$this->mParserOptions ) {
171 if ( !$wgUser->isSafeToLoad() ) {
172 // $wgUser isn't unstubbable yet, so don't try to get a
173 // ParserOptions for it. And don't cache this ParserOptions
174 // either.
175 $po = ParserOptions::newFromAnon();
176 $po->setAllowUnsafeRawHtml( false );
177 $po->setTidy( true );
178 return $po;
179 }
180
181 $this->mParserOptions = new ParserOptions;
182 // Messages may take parameters that could come
183 // from malicious sources. As a precaution, disable
184 // the <html> parser tag when parsing messages.
185 $this->mParserOptions->setAllowUnsafeRawHtml( false );
186 // For the same reason, tidy the output!
187 $this->mParserOptions->setTidy( true );
188 }
189
190 return $this->mParserOptions;
191 }
192
193 /**
194 * Try to load the cache from APC.
195 *
196 * @param string $code Optional language code, see documentation of load().
197 * @return array|bool The cache array, or false if not in cache.
198 */
199 protected function getLocalCache( $code ) {
200 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
201
202 return $this->srvCache->get( $cacheKey );
203 }
204
205 /**
206 * Save the cache to APC.
207 *
208 * @param string $code
209 * @param array $cache The cache array
210 */
211 protected function saveToLocalCache( $code, $cache ) {
212 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
213 $this->srvCache->set( $cacheKey, $cache );
214 }
215
216 /**
217 * Loads messages from caches or from database in this order:
218 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
219 * (2) memcached
220 * (3) from the database.
221 *
222 * When successfully loading from (2) or (3), all higher level caches are
223 * updated for the newest version.
224 *
225 * Nothing is loaded if member variable mDisable is true, either manually
226 * set by calling code or if message loading fails (is this possible?).
227 *
228 * Returns true if cache is already populated or it was successfully populated,
229 * or false if populating empty cache fails. Also returns true if MessageCache
230 * is disabled.
231 *
232 * @param string $code Language to which load messages
233 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
234 * @throws InvalidArgumentException
235 * @return bool
236 */
237 protected function load( $code, $mode = null ) {
238 if ( !is_string( $code ) ) {
239 throw new InvalidArgumentException( "Missing language code" );
240 }
241
242 # Don't do double loading...
243 if ( isset( $this->loadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
244 return true;
245 }
246
247 $this->overridable = array_flip( Language::getMessageKeysFor( $code ) );
248
249 # 8 lines of code just to say (once) that message cache is disabled
250 if ( $this->mDisable ) {
251 static $shownDisabled = false;
252 if ( !$shownDisabled ) {
253 wfDebug( __METHOD__ . ": disabled\n" );
254 $shownDisabled = true;
255 }
256
257 return true;
258 }
259
260 # Loading code starts
261 $success = false; # Keep track of success
262 $staleCache = false; # a cache array with expired data, or false if none has been loaded
263 $where = []; # Debug info, delayed to avoid spamming debug log too much
264
265 # Hash of the contents is stored in memcache, to detect if data-center cache
266 # or local cache goes out of date (e.g. due to replace() on some other server)
267 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
268 $this->cacheVolatile[$code] = $hashVolatile;
269
270 # Try the local cache and check against the cluster hash key...
271 $cache = $this->getLocalCache( $code );
272 if ( !$cache ) {
273 $where[] = 'local cache is empty';
274 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
275 $where[] = 'local cache has the wrong hash';
276 $staleCache = $cache;
277 } elseif ( $this->isCacheExpired( $cache ) ) {
278 $where[] = 'local cache is expired';
279 $staleCache = $cache;
280 } elseif ( $hashVolatile ) {
281 $where[] = 'local cache validation key is expired/volatile';
282 $staleCache = $cache;
283 } else {
284 $where[] = 'got from local cache';
285 $this->cache->set( $code, $cache );
286 $success = true;
287 }
288
289 if ( !$success ) {
290 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
291 # Try the global cache. If it is empty, try to acquire a lock. If
292 # the lock can't be acquired, wait for the other thread to finish
293 # and then try the global cache a second time.
294 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
295 if ( $hashVolatile && $staleCache ) {
296 # Do not bother fetching the whole cache blob to avoid I/O.
297 # Instead, just try to get the non-blocking $statusKey lock
298 # below, and use the local stale value if it was not acquired.
299 $where[] = 'global cache is presumed expired';
300 } else {
301 $cache = $this->clusterCache->get( $cacheKey );
302 if ( !$cache ) {
303 $where[] = 'global cache is empty';
304 } elseif ( $this->isCacheExpired( $cache ) ) {
305 $where[] = 'global cache is expired';
306 $staleCache = $cache;
307 } elseif ( $hashVolatile ) {
308 # DB results are replica DB lag prone until the holdoff TTL passes.
309 # By then, updates should be reflected in loadFromDBWithLock().
310 # One thread regenerates the cache while others use old values.
311 $where[] = 'global cache is expired/volatile';
312 $staleCache = $cache;
313 } else {
314 $where[] = 'got from global cache';
315 $this->cache->set( $code, $cache );
316 $this->saveToCaches( $cache, 'local-only', $code );
317 $success = true;
318 }
319 }
320
321 if ( $success ) {
322 # Done, no need to retry
323 break;
324 }
325
326 # We need to call loadFromDB. Limit the concurrency to one process.
327 # This prevents the site from going down when the cache expires.
328 # Note that the DB slam protection lock here is non-blocking.
329 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
330 if ( $loadStatus === true ) {
331 $success = true;
332 break;
333 } elseif ( $staleCache ) {
334 # Use the stale cache while some other thread constructs the new one
335 $where[] = 'using stale cache';
336 $this->cache->set( $code, $staleCache );
337 $success = true;
338 break;
339 } elseif ( $failedAttempts > 0 ) {
340 # Already blocked once, so avoid another lock/unlock cycle.
341 # This case will typically be hit if memcached is down, or if
342 # loadFromDB() takes longer than LOCK_WAIT.
343 $where[] = "could not acquire status key.";
344 break;
345 } elseif ( $loadStatus === 'cantacquire' ) {
346 # Wait for the other thread to finish, then retry. Normally,
347 # the memcached get() will then yield the other thread's result.
348 $where[] = 'waited for other thread to complete';
349 $this->getReentrantScopedLock( $cacheKey );
350 } else {
351 # Disable cache; $loadStatus is 'disabled'
352 break;
353 }
354 }
355 }
356
357 if ( !$success ) {
358 $where[] = 'loading FAILED - cache is disabled';
359 $this->mDisable = true;
360 $this->cache->set( $code, [] );
361 wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
362 # This used to throw an exception, but that led to nasty side effects like
363 # the whole wiki being instantly down if the memcached server died
364 } else {
365 # All good, just record the success
366 $this->loadedLanguages[$code] = true;
367 }
368
369 if ( !$this->cache->has( $code ) ) { // sanity
370 throw new LogicException( "Process cache for '$code' should be set by now." );
371 }
372
373 $info = implode( ', ', $where );
374 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
375
376 return $success;
377 }
378
379 /**
380 * @param string $code
381 * @param array &$where List of wfDebug() comments
382 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
383 * @return bool|string True on success or one of ("cantacquire", "disabled")
384 */
385 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
386 # If cache updates on all levels fail, give up on message overrides.
387 # This is to avoid easy site outages; see $saveSuccess comments below.
388 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
389 $status = $this->clusterCache->get( $statusKey );
390 if ( $status === 'error' ) {
391 $where[] = "could not load; method is still globally disabled";
392 return 'disabled';
393 }
394
395 # Now let's regenerate
396 $where[] = 'loading from database';
397
398 # Lock the cache to prevent conflicting writes.
399 # This lock is non-blocking so stale cache can quickly be used.
400 # Note that load() will call a blocking getReentrantScopedLock()
401 # after this if it really need to wait for any current thread.
402 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
403 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
404 if ( !$scopedLock ) {
405 $where[] = 'could not acquire main lock';
406 return 'cantacquire';
407 }
408
409 $cache = $this->loadFromDB( $code, $mode );
410 $this->cache->set( $code, $cache );
411 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
412
413 if ( !$saveSuccess ) {
414 /**
415 * Cache save has failed.
416 *
417 * There are two main scenarios where this could be a problem:
418 * - The cache is more than the maximum size (typically 1MB compressed).
419 * - Memcached has no space remaining in the relevant slab class. This is
420 * unlikely with recent versions of memcached.
421 *
422 * Either way, if there is a local cache, nothing bad will happen. If there
423 * is no local cache, disabling the message cache for all requests avoids
424 * incurring a loadFromDB() overhead on every request, and thus saves the
425 * wiki from complete downtime under moderate traffic conditions.
426 */
427 if ( $this->srvCache instanceof EmptyBagOStuff ) {
428 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
429 $where[] = 'could not save cache, disabled globally for 5 minutes';
430 } else {
431 $where[] = "could not save global cache";
432 }
433 }
434
435 return true;
436 }
437
438 /**
439 * Loads cacheable messages from the database. Messages bigger than
440 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
441 * on-demand from the database later.
442 *
443 * @param string $code Language code
444 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
445 * @return array Loaded messages for storing in caches
446 */
447 protected function loadFromDB( $code, $mode = null ) {
448 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
449
450 // (T164666) The query here performs really poorly on WMF's
451 // contributions replicas. We don't have a way to say "any group except
452 // contributions", so for the moment let's specify 'api'.
453 // @todo: Get rid of this hack.
454 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
455
456 $cache = [];
457
458 $mostused = []; // list of "<cased message key>/<code>"
459 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
460 if ( !$this->cache->has( $wgLanguageCode ) ) {
461 $this->load( $wgLanguageCode );
462 }
463 $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
464 foreach ( $mostused as $key => $value ) {
465 $mostused[$key] = "$value/$code";
466 }
467 }
468
469 // Get the list of software-defined messages in core/extensions
470 $overridable = array_flip( Language::getMessageKeysFor( $wgLanguageCode ) );
471
472 // Common conditions
473 $conds = [
474 'page_is_redirect' => 0,
475 'page_namespace' => NS_MEDIAWIKI,
476 ];
477 if ( count( $mostused ) ) {
478 $conds['page_title'] = $mostused;
479 } elseif ( $code !== $wgLanguageCode ) {
480 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
481 } else {
482 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
483 # other than language code.
484 $conds[] = 'page_title NOT' .
485 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
486 }
487
488 // Set the stubs for oversized software-defined messages in the main cache map
489 $res = $dbr->select(
490 'page',
491 [ 'page_title', 'page_latest' ],
492 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
493 __METHOD__ . "($code)-big"
494 );
495 foreach ( $res as $row ) {
496 // Include entries/stubs for all keys in $mostused in adaptive mode
497 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title, $overridable ) ) {
498 $cache[$row->page_title] = '!TOO BIG';
499 }
500 // At least include revision ID so page changes are reflected in the hash
501 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
502 }
503
504 // Set the text for small software-defined messages in the main cache map
505 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
506 $revQuery = $revisionStore->getQueryInfo( [ 'page', 'user' ] );
507 $res = $dbr->select(
508 $revQuery['tables'],
509 $revQuery['fields'],
510 array_merge( $conds, [
511 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
512 'page_latest = rev_id' // get the latest revision only
513 ] ),
514 __METHOD__ . "($code)-small",
515 [],
516 $revQuery['joins']
517 );
518 foreach ( $res as $row ) {
519 // Include entries/stubs for all keys in $mostused in adaptive mode
520 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title, $overridable ) ) {
521 try {
522 $rev = $revisionStore->newRevisionFromRow( $row );
523 $content = $rev->getContent( MediaWiki\Revision\SlotRecord::MAIN );
524 $text = $this->getMessageTextFromContent( $content );
525 } catch ( Exception $ex ) {
526 $text = false;
527 }
528
529 if ( !is_string( $text ) ) {
530 $entry = '!ERROR';
531 wfDebugLog(
532 'MessageCache',
533 __METHOD__
534 . ": failed to load message page text for {$row->page_title} ($code)"
535 );
536 } else {
537 $entry = ' ' . $text;
538 }
539 $cache[$row->page_title] = $entry;
540 } else {
541 // T193271: cache object gets too big and slow to generate.
542 // At least include revision ID so page changes are reflected in the hash.
543 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
544 }
545 }
546
547 $cache['VERSION'] = MSG_CACHE_VERSION;
548 ksort( $cache );
549
550 # Hash for validating local cache (APC). No need to take into account
551 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
552 # stored and fetched from memcache.
553 $cache['HASH'] = md5( serialize( $cache ) );
554 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
555 unset( $cache['EXCESSIVE'] ); // only needed for hash
556
557 return $cache;
558 }
559
560 /**
561 * @param string $name Message name (possibly with /code suffix)
562 * @param array $overridable Map of (key => unused) for software-defined messages
563 * @return bool
564 */
565 private function isMainCacheable( $name, array $overridable ) {
566 // Convert first letter to lowercase, and strip /code suffix
567 $name = $this->contLang->lcfirst( $name );
568 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
569 // Include common conversion table pages. This also avoids problems with
570 // Installer::parse() bailing out due to disallowed DB queries (T207979).
571 return ( isset( $overridable[$msg] ) || strpos( $name, 'conversiontable/' ) === 0 );
572 }
573
574 /**
575 * Updates cache as necessary when message page is changed
576 *
577 * @param string $title Message cache key with initial uppercase letter
578 * @param string|bool $text New contents of the page (false if deleted)
579 */
580 public function replace( $title, $text ) {
581 global $wgLanguageCode;
582
583 if ( $this->mDisable ) {
584 return;
585 }
586
587 list( $msg, $code ) = $this->figureMessage( $title );
588 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
589 // Content language overrides do not use the /<code> suffix
590 return;
591 }
592
593 // (a) Update the process cache with the new message text
594 if ( $text === false ) {
595 // Page deleted
596 $this->cache->setField( $code, $title, '!NONEXISTENT' );
597 } else {
598 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
599 $this->cache->setField( $code, $title, ' ' . $text );
600 }
601
602 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
603 DeferredUpdates::addUpdate(
604 new MessageCacheUpdate( $code, $title, $msg ),
605 DeferredUpdates::PRESEND
606 );
607 }
608
609 /**
610 * @param string $code
611 * @param array[] $replacements List of (title, message key) pairs
612 * @throws MWException
613 */
614 public function refreshAndReplaceInternal( $code, array $replacements ) {
615 global $wgMaxMsgCacheEntrySize;
616
617 // Allow one caller at a time to avoid race conditions
618 $scopedLock = $this->getReentrantScopedLock(
619 $this->clusterCache->makeKey( 'messages', $code )
620 );
621 if ( !$scopedLock ) {
622 foreach ( $replacements as list( $title ) ) {
623 LoggerFactory::getInstance( 'MessageCache' )->error(
624 __METHOD__ . ': could not acquire lock to update {title} ({code})',
625 [ 'title' => $title, 'code' => $code ] );
626 }
627
628 return;
629 }
630
631 // Load the existing cache to update it in the local DC cache.
632 // The other DCs will see a hash mismatch.
633 if ( $this->load( $code, self::FOR_UPDATE ) ) {
634 $cache = $this->cache->get( $code );
635 } else {
636 // Err? Fall back to loading from the database.
637 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
638 }
639 // Check if individual cache keys should exist and update cache accordingly
640 $newTextByTitle = []; // map of (title => content)
641 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
642 foreach ( $replacements as list( $title ) ) {
643 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
644 $page->loadPageData( $page::READ_LATEST );
645 $text = $this->getMessageTextFromContent( $page->getContent() );
646 // Remember the text for the blob store update later on
647 $newTextByTitle[$title] = $text;
648 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
649 if ( !is_string( $text ) ) {
650 $cache[$title] = '!NONEXISTENT';
651 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
652 $cache[$title] = '!TOO BIG';
653 $newBigTitles[$title] = $page->getLatest();
654 } else {
655 $cache[$title] = ' ' . $text;
656 }
657 }
658 // Update HASH for the new key. Incorporates various administrative keys,
659 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
660 // and previous replace() calls), but that doesn't really matter since we
661 // only ever compare it for equality with a copy saved by saveToCaches().
662 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
663 // Update the too-big WAN cache entries now that we have the new HASH
664 foreach ( $newBigTitles as $title => $id ) {
665 // Match logic of loadCachedMessagePageEntry()
666 $this->wanCache->set(
667 $this->bigMessageCacheKey( $cache['HASH'], $title ),
668 ' ' . $newTextByTitle[$title],
669 $this->mExpiry
670 );
671 }
672 // Mark this cache as definitely being "latest" (non-volatile) so
673 // load() calls do not try to refresh the cache with replica DB data
674 $cache['LATEST'] = time();
675 // Update the process cache
676 $this->cache->set( $code, $cache );
677 // Pre-emptively update the local datacenter cache so things like edit filter and
678 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
679 // The datacenter handling replace() calls should be the same one handling edits
680 // as they require HTTP POST.
681 $this->saveToCaches( $cache, 'all', $code );
682 // Release the lock now that the cache is saved
683 ScopedCallback::consume( $scopedLock );
684
685 // Relay the purge. Touching this check key expires cache contents
686 // and local cache (APC) validation hash across all datacenters.
687 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
688
689 // Purge the messages in the message blob store and fire any hook handlers
690 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
691 foreach ( $replacements as list( $title, $msg ) ) {
692 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
693 Hooks::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
694 }
695 }
696
697 /**
698 * Is the given cache array expired due to time passing or a version change?
699 *
700 * @param array $cache
701 * @return bool
702 */
703 protected function isCacheExpired( $cache ) {
704 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
705 return true;
706 }
707 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
708 return true;
709 }
710 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
711 return true;
712 }
713
714 return false;
715 }
716
717 /**
718 * Shortcut to update caches.
719 *
720 * @param array $cache Cached messages with a version.
721 * @param string $dest Either "local-only" to save to local caches only
722 * or "all" to save to all caches.
723 * @param string|bool $code Language code (default: false)
724 * @return bool
725 */
726 protected function saveToCaches( array $cache, $dest, $code = false ) {
727 if ( $dest === 'all' ) {
728 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
729 $success = $this->clusterCache->set( $cacheKey, $cache );
730 $this->setValidationHash( $code, $cache );
731 } else {
732 $success = true;
733 }
734
735 $this->saveToLocalCache( $code, $cache );
736
737 return $success;
738 }
739
740 /**
741 * Get the md5 used to validate the local APC cache
742 *
743 * @param string $code
744 * @return array (hash or false, bool expiry/volatility status)
745 */
746 protected function getValidationHash( $code ) {
747 $curTTL = null;
748 $value = $this->wanCache->get(
749 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
750 $curTTL,
751 [ $this->getCheckKey( $code ) ]
752 );
753
754 if ( $value ) {
755 $hash = $value['hash'];
756 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
757 // Cache was recently updated via replace() and should be up-to-date.
758 // That method is only called in the primary datacenter and uses FOR_UPDATE.
759 // Also, it is unlikely that the current datacenter is *now* secondary one.
760 $expired = false;
761 } else {
762 // See if the "check" key was bumped after the hash was generated
763 $expired = ( $curTTL < 0 );
764 }
765 } else {
766 // No hash found at all; cache must regenerate to be safe
767 $hash = false;
768 $expired = true;
769 }
770
771 return [ $hash, $expired ];
772 }
773
774 /**
775 * Set the md5 used to validate the local disk cache
776 *
777 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
778 * be treated as "volatile" by getValidationHash() for the next few seconds.
779 * This is triggered when $cache is generated using FOR_UPDATE mode.
780 *
781 * @param string $code
782 * @param array $cache Cached messages with a version
783 */
784 protected function setValidationHash( $code, array $cache ) {
785 $this->wanCache->set(
786 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
787 [
788 'hash' => $cache['HASH'],
789 'latest' => $cache['LATEST'] ?? 0
790 ],
791 WANObjectCache::TTL_INDEFINITE
792 );
793 }
794
795 /**
796 * @param string $key A language message cache key that stores blobs
797 * @param int $timeout Wait timeout in seconds
798 * @return null|ScopedCallback
799 */
800 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
801 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
802 }
803
804 /**
805 * Get a message from either the content language or the user language.
806 *
807 * First, assemble a list of languages to attempt getting the message from. This
808 * chain begins with the requested language and its fallbacks and then continues with
809 * the content language and its fallbacks. For each language in the chain, the following
810 * process will occur (in this order):
811 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
812 * Note: for the content language, there is no /lang subpage.
813 * 2. Fetch from the static CDB cache.
814 * 3. If available, check the database for fallback language overrides.
815 *
816 * This process provides a number of guarantees. When changing this code, make sure all
817 * of these guarantees are preserved.
818 * * If the requested language is *not* the content language, then the CDB cache for that
819 * specific language will take precedence over the root database page ([[MW:msg]]).
820 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
821 * the message is available *anywhere* in the language for which it is a fallback.
822 *
823 * @param string $key The message key
824 * @param bool $useDB If true, look for the message in the DB, false
825 * to use only the compiled l10n cache.
826 * @param bool|string|object $langcode Code of the language to get the message for.
827 * - If string and a valid code, will create a standard language object
828 * - If string but not a valid code, will create a basic language object
829 * - If boolean and false, create object from the current users language
830 * - If boolean and true, create object from the wikis content language
831 * - If language object, use it as given
832 *
833 * @throws MWException When given an invalid key
834 * @return string|bool False if the message doesn't exist, otherwise the
835 * message (which can be empty)
836 */
837 function get( $key, $useDB = true, $langcode = true ) {
838 if ( is_int( $key ) ) {
839 // Fix numerical strings that somehow become ints
840 // on their way here
841 $key = (string)$key;
842 } elseif ( !is_string( $key ) ) {
843 throw new MWException( 'Non-string key given' );
844 } elseif ( $key === '' ) {
845 // Shortcut: the empty key is always missing
846 return false;
847 }
848
849 // Normalise title-case input (with some inlining)
850 $lckey = self::normalizeKey( $key );
851
852 Hooks::run( 'MessageCache::get', [ &$lckey ] );
853
854 // Loop through each language in the fallback list until we find something useful
855 $message = $this->getMessageFromFallbackChain(
856 wfGetLangObj( $langcode ),
857 $lckey,
858 !$this->mDisable && $useDB
859 );
860
861 // If we still have no message, maybe the key was in fact a full key so try that
862 if ( $message === false ) {
863 $parts = explode( '/', $lckey );
864 // We may get calls for things that are http-urls from sidebar
865 // Let's not load nonexistent languages for those
866 // They usually have more than one slash.
867 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
868 $message = Language::getMessageFor( $parts[0], $parts[1] );
869 if ( $message === null ) {
870 $message = false;
871 }
872 }
873 }
874
875 // Post-processing if the message exists
876 if ( $message !== false ) {
877 // Fix whitespace
878 $message = str_replace(
879 [
880 # Fix for trailing whitespace, removed by textarea
881 '&#32;',
882 # Fix for NBSP, converted to space by firefox
883 '&nbsp;',
884 '&#160;',
885 '&shy;'
886 ],
887 [
888 ' ',
889 "\u{00A0}",
890 "\u{00A0}",
891 "\u{00AD}"
892 ],
893 $message
894 );
895 }
896
897 return $message;
898 }
899
900 /**
901 * Given a language, try and fetch messages from that language.
902 *
903 * Will also consider fallbacks of that language, the site language, and fallbacks for
904 * the site language.
905 *
906 * @see MessageCache::get
907 * @param Language|StubObject $lang Preferred language
908 * @param string $lckey Lowercase key for the message (as for localisation cache)
909 * @param bool $useDB Whether to include messages from the wiki database
910 * @return string|bool The message, or false if not found
911 */
912 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
913 $alreadyTried = [];
914
915 // First try the requested language.
916 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
917 if ( $message !== false ) {
918 return $message;
919 }
920
921 // Now try checking the site language.
922 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
923 return $message;
924 }
925
926 /**
927 * Given a language, try and fetch messages from that language and its fallbacks.
928 *
929 * @see MessageCache::get
930 * @param Language|StubObject $lang Preferred language
931 * @param string $lckey Lowercase key for the message (as for localisation cache)
932 * @param bool $useDB Whether to include messages from the wiki database
933 * @param bool[] $alreadyTried Contains true for each language that has been tried already
934 * @return string|bool The message, or false if not found
935 */
936 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
937 $langcode = $lang->getCode();
938
939 // Try checking the database for the requested language
940 if ( $useDB ) {
941 $uckey = $this->contLang->ucfirst( $lckey );
942
943 if ( !isset( $alreadyTried[$langcode] ) ) {
944 $message = $this->getMsgFromNamespace(
945 $this->getMessagePageName( $langcode, $uckey ),
946 $langcode
947 );
948 if ( $message !== false ) {
949 return $message;
950 }
951 $alreadyTried[$langcode] = true;
952 }
953 } else {
954 $uckey = null;
955 }
956
957 // Check the CDB cache
958 $message = $lang->getMessage( $lckey );
959 if ( $message !== null ) {
960 return $message;
961 }
962
963 // Try checking the database for all of the fallback languages
964 if ( $useDB ) {
965 $fallbackChain = Language::getFallbacksFor( $langcode );
966
967 foreach ( $fallbackChain as $code ) {
968 if ( isset( $alreadyTried[$code] ) ) {
969 continue;
970 }
971
972 $message = $this->getMsgFromNamespace(
973 $this->getMessagePageName( $code, $uckey ), $code );
974
975 if ( $message !== false ) {
976 return $message;
977 }
978 $alreadyTried[$code] = true;
979 }
980 }
981
982 return false;
983 }
984
985 /**
986 * Get the message page name for a given language
987 *
988 * @param string $langcode
989 * @param string $uckey Uppercase key for the message
990 * @return string The page name
991 */
992 private function getMessagePageName( $langcode, $uckey ) {
993 global $wgLanguageCode;
994
995 if ( $langcode === $wgLanguageCode ) {
996 // Messages created in the content language will not have the /lang extension
997 return $uckey;
998 } else {
999 return "$uckey/$langcode";
1000 }
1001 }
1002
1003 /**
1004 * Get a message from the MediaWiki namespace, with caching. The key must
1005 * first be converted to two-part lang/msg form if necessary.
1006 *
1007 * Unlike self::get(), this function doesn't resolve fallback chains, and
1008 * some callers require this behavior. LanguageConverter::parseCachedTable()
1009 * and self::get() are some examples in core.
1010 *
1011 * @param string $title Message cache key with initial uppercase letter
1012 * @param string $code Code denoting the language to try
1013 * @return string|bool The message, or false if it does not exist or on error
1014 */
1015 public function getMsgFromNamespace( $title, $code ) {
1016 // Load all MediaWiki page definitions into cache. Note that individual keys
1017 // already loaded into cache during this request remain in the cache, which
1018 // includes the value of hook-defined messages.
1019 $this->load( $code );
1020
1021 $entry = $this->cache->getField( $code, $title );
1022
1023 if ( $entry !== null ) {
1024 // Message page exists as an override of a software messages
1025 if ( substr( $entry, 0, 1 ) === ' ' ) {
1026 // The message exists and is not '!TOO BIG' or '!ERROR'
1027 return (string)substr( $entry, 1 );
1028 } elseif ( $entry === '!NONEXISTENT' ) {
1029 // The text might be '-' or missing due to some data loss
1030 return false;
1031 }
1032 // Load the message page, utilizing the individual message cache.
1033 // If the page does not exist, there will be no hook handler fallbacks.
1034 $entry = $this->loadCachedMessagePageEntry(
1035 $title,
1036 $code,
1037 $this->cache->getField( $code, 'HASH' )
1038 );
1039 } else {
1040 // Message page either does not exist or does not override a software message
1041 if ( !$this->isMainCacheable( $title, $this->overridable ) ) {
1042 // Message page does not override any software-defined message. A custom
1043 // message might be defined to have content or settings specific to the wiki.
1044 // Load the message page, utilizing the individual message cache as needed.
1045 $entry = $this->loadCachedMessagePageEntry(
1046 $title,
1047 $code,
1048 $this->cache->getField( $code, 'HASH' )
1049 );
1050 }
1051 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1052 // Message does not have a MediaWiki page definition; try hook handlers
1053 $message = false;
1054 Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1055 if ( $message !== false ) {
1056 $this->cache->setField( $code, $title, ' ' . $message );
1057 } else {
1058 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1059 }
1060
1061 return $message;
1062 }
1063 }
1064
1065 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1066 if ( $this->cacheVolatile[$code] ) {
1067 // Make sure that individual keys respect the WAN cache holdoff period too
1068 LoggerFactory::getInstance( 'MessageCache' )->debug(
1069 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1070 [ 'titleKey' => $title, 'code' => $code ] );
1071 } else {
1072 $this->cache->setField( $code, $title, $entry );
1073 }
1074 // The message exists, so make sure a string is returned
1075 return (string)substr( $entry, 1 );
1076 }
1077
1078 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1079
1080 return false;
1081 }
1082
1083 /**
1084 * @param string $dbKey
1085 * @param string $code
1086 * @param string $hash
1087 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1088 */
1089 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1090 $fname = __METHOD__;
1091 return $this->srvCache->getWithSetCallback(
1092 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1093 IExpiringStore::TTL_MINUTE,
1094 function () use ( $code, $dbKey, $hash, $fname ) {
1095 return $this->wanCache->getWithSetCallback(
1096 $this->bigMessageCacheKey( $hash, $dbKey ),
1097 $this->mExpiry,
1098 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1099 // Try loading the message from the database
1100 $dbr = wfGetDB( DB_REPLICA );
1101 $setOpts += Database::getCacheSetOptions( $dbr );
1102 // Use newKnownCurrent() to avoid querying revision/user tables
1103 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1104 $revision = Revision::newKnownCurrent( $dbr, $title );
1105 if ( !$revision ) {
1106 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1107 // When overrides are created, self::replace() takes care of the cache.
1108 return '!NONEXISTENT';
1109 }
1110 $content = $revision->getContent();
1111 if ( $content ) {
1112 $message = $this->getMessageTextFromContent( $content );
1113 } else {
1114 LoggerFactory::getInstance( 'MessageCache' )->warning(
1115 $fname . ': failed to load page text for \'{titleKey}\'',
1116 [ 'titleKey' => $dbKey, 'code' => $code ]
1117 );
1118 $message = null;
1119 }
1120
1121 if ( !is_string( $message ) ) {
1122 // Revision failed to load Content, or Content is incompatible with wikitext.
1123 // Possibly a temporary loading failure.
1124 $ttl = 5;
1125
1126 return '!NONEXISTENT';
1127 }
1128
1129 return ' ' . $message;
1130 }
1131 );
1132 }
1133 );
1134 }
1135
1136 /**
1137 * @param string $message
1138 * @param bool $interface
1139 * @param Language|null $language
1140 * @param Title|null $title
1141 * @return string
1142 */
1143 public function transform( $message, $interface = false, $language = null, $title = null ) {
1144 // Avoid creating parser if nothing to transform
1145 if ( strpos( $message, '{{' ) === false ) {
1146 return $message;
1147 }
1148
1149 if ( $this->mInParser ) {
1150 return $message;
1151 }
1152
1153 $parser = $this->getParser();
1154 if ( $parser ) {
1155 $popts = $this->getParserOptions();
1156 $popts->setInterfaceMessage( $interface );
1157 $popts->setTargetLanguage( $language );
1158
1159 $userlang = $popts->setUserLang( $language );
1160 $this->mInParser = true;
1161 $message = $parser->transformMsg( $message, $popts, $title );
1162 $this->mInParser = false;
1163 $popts->setUserLang( $userlang );
1164 }
1165
1166 return $message;
1167 }
1168
1169 /**
1170 * @return Parser
1171 */
1172 public function getParser() {
1173 global $wgParserConf;
1174 if ( !$this->mParser ) {
1175 $parser = MediaWikiServices::getInstance()->getParser();
1176 # Do some initialisation so that we don't have to do it twice
1177 $parser->firstCallInit();
1178 # Clone it and store it
1179 $class = $wgParserConf['class'];
1180 if ( $class == ParserDiffTest::class ) {
1181 # Uncloneable
1182 $this->mParser = new $class( $wgParserConf );
1183 } else {
1184 $this->mParser = clone $parser;
1185 }
1186 }
1187
1188 return $this->mParser;
1189 }
1190
1191 /**
1192 * @param string $text
1193 * @param Title|null $title
1194 * @param bool $linestart Whether or not this is at the start of a line
1195 * @param bool $interface Whether this is an interface message
1196 * @param Language|string|null $language Language code
1197 * @return ParserOutput|string
1198 */
1199 public function parse( $text, $title = null, $linestart = true,
1200 $interface = false, $language = null
1201 ) {
1202 global $wgTitle;
1203
1204 if ( $this->mInParser ) {
1205 return htmlspecialchars( $text );
1206 }
1207
1208 $parser = $this->getParser();
1209 $popts = $this->getParserOptions();
1210 $popts->setInterfaceMessage( $interface );
1211
1212 if ( is_string( $language ) ) {
1213 $language = Language::factory( $language );
1214 }
1215 $popts->setTargetLanguage( $language );
1216
1217 if ( !$title || !$title instanceof Title ) {
1218 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1219 wfGetAllCallers( 6 ) . ' with no title set.' );
1220 $title = $wgTitle;
1221 }
1222 // Sometimes $wgTitle isn't set either...
1223 if ( !$title ) {
1224 # It's not uncommon having a null $wgTitle in scripts. See r80898
1225 # Create a ghost title in such case
1226 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1227 }
1228
1229 $this->mInParser = true;
1230 $res = $parser->parse( $text, $title, $popts, $linestart );
1231 $this->mInParser = false;
1232
1233 return $res;
1234 }
1235
1236 public function disable() {
1237 $this->mDisable = true;
1238 }
1239
1240 public function enable() {
1241 $this->mDisable = false;
1242 }
1243
1244 /**
1245 * Whether DB/cache usage is disabled for determining messages
1246 *
1247 * If so, this typically indicates either:
1248 * - a) load() failed to find a cached copy nor query the DB
1249 * - b) we are in a special context or error mode that cannot use the DB
1250 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1251 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1252 *
1253 * @return bool
1254 * @since 1.27
1255 */
1256 public function isDisabled() {
1257 return $this->mDisable;
1258 }
1259
1260 /**
1261 * Clear all stored messages in global and local cache
1262 *
1263 * Mainly used after a mass rebuild
1264 */
1265 public function clear() {
1266 $langs = Language::fetchLanguageNames( null, 'mw' );
1267 foreach ( array_keys( $langs ) as $code ) {
1268 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1269 }
1270 $this->cache->clear();
1271 $this->loadedLanguages = [];
1272 }
1273
1274 /**
1275 * @param string $key
1276 * @return array
1277 */
1278 public function figureMessage( $key ) {
1279 global $wgLanguageCode;
1280
1281 $pieces = explode( '/', $key );
1282 if ( count( $pieces ) < 2 ) {
1283 return [ $key, $wgLanguageCode ];
1284 }
1285
1286 $lang = array_pop( $pieces );
1287 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1288 return [ $key, $wgLanguageCode ];
1289 }
1290
1291 $message = implode( '/', $pieces );
1292
1293 return [ $message, $lang ];
1294 }
1295
1296 /**
1297 * Get all message keys stored in the message cache for a given language.
1298 * If $code is the content language code, this will return all message keys
1299 * for which MediaWiki:msgkey exists. If $code is another language code, this
1300 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1301 * @param string $code Language code
1302 * @return array Array of message keys (strings)
1303 */
1304 public function getAllMessageKeys( $code ) {
1305 $this->load( $code );
1306 if ( !$this->cache->has( $code ) ) {
1307 // Apparently load() failed
1308 return null;
1309 }
1310 // Remove administrative keys
1311 $cache = $this->cache->get( $code );
1312 unset( $cache['VERSION'] );
1313 unset( $cache['EXPIRY'] );
1314 unset( $cache['EXCESSIVE'] );
1315 // Remove any !NONEXISTENT keys
1316 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1317
1318 // Keys may appear with a capital first letter. lcfirst them.
1319 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1320 }
1321
1322 /**
1323 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1324 *
1325 * @param Title $title Message page title
1326 * @param Content|null $content New content for edit/create, null on deletion
1327 * @since 1.29
1328 */
1329 public function updateMessageOverride( Title $title, Content $content = null ) {
1330 $msgText = $this->getMessageTextFromContent( $content );
1331 if ( $msgText === null ) {
1332 $msgText = false; // treat as not existing
1333 }
1334
1335 $this->replace( $title->getDBkey(), $msgText );
1336
1337 if ( $this->contLang->hasVariants() ) {
1338 $this->contLang->updateConversionTable( $title );
1339 }
1340 }
1341
1342 /**
1343 * @param string $code Language code
1344 * @return string WAN cache key usable as a "check key" against language page edits
1345 */
1346 public function getCheckKey( $code ) {
1347 return $this->wanCache->makeKey( 'messages', $code );
1348 }
1349
1350 /**
1351 * @param Content|null $content Content or null if the message page does not exist
1352 * @return string|bool|null Returns false if $content is null and null on error
1353 */
1354 private function getMessageTextFromContent( Content $content = null ) {
1355 // @TODO: could skip pseudo-messages like js/css here, based on content model
1356 if ( $content ) {
1357 // Message page exists...
1358 // XXX: Is this the right way to turn a Content object into a message?
1359 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1360 // CssContent. MessageContent is *not* used for storing messages, it's
1361 // only used for wrapping them when needed.
1362 $msgText = $content->getWikitextForTransclusion();
1363 if ( $msgText === false || $msgText === null ) {
1364 // This might be due to some kind of misconfiguration...
1365 $msgText = null;
1366 LoggerFactory::getInstance( 'MessageCache' )->warning(
1367 __METHOD__ . ": message content doesn't provide wikitext "
1368 . "(content model: " . $content->getModel() . ")" );
1369 }
1370 } else {
1371 // Message page does not exist...
1372 $msgText = false;
1373 }
1374
1375 return $msgText;
1376 }
1377
1378 /**
1379 * @param string $hash Hash for this version of the entire key/value overrides map
1380 * @param string $title Message cache key with initial uppercase letter
1381 * @return string
1382 */
1383 private function bigMessageCacheKey( $hash, $title ) {
1384 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1385 }
1386 }