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