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