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