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