Merge "eslintrc: Disallow calling String/Array/Object methods introduced in ES6 or...
[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")
52 */
53 protected $cache;
54
55 /**
56 * Map of (lowercase message key => index) for all software defined messages
57 *
58 * @var array
59 */
60 protected $overridable;
61
62 /**
63 * @var bool[] Map of (language code => boolean)
64 */
65 protected $cacheVolatile = [];
66
67 /**
68 * Should mean that database cannot be used, but check
69 * @var bool $mDisable
70 */
71 protected $mDisable;
72
73 /**
74 * Lifetime for cache, used by object caching.
75 * Set on construction, see __construct().
76 */
77 protected $mExpiry;
78
79 /**
80 * Message cache has its own parser which it uses to transform messages
81 * @var ParserOptions
82 */
83 protected $mParserOptions;
84 /** @var Parser */
85 protected $mParser;
86
87 /**
88 * @var bool $mInParser
89 */
90 protected $mInParser = false;
91
92 /** @var WANObjectCache */
93 protected $wanCache;
94 /** @var BagOStuff */
95 protected $clusterCache;
96 /** @var BagOStuff */
97 protected $srvCache;
98 /** @var Language */
99 protected $contLang;
100
101 /**
102 * Singleton instance
103 *
104 * @var MessageCache $instance
105 */
106 private static $instance;
107
108 /**
109 * Get the signleton instance of this class
110 *
111 * @since 1.18
112 * @return MessageCache
113 */
114 public static function singleton() {
115 if ( self::$instance === null ) {
116 global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
117 $services = MediaWikiServices::getInstance();
118 self::$instance = new self(
119 $services->getMainWANObjectCache(),
120 wfGetMessageCacheStorage(),
121 $wgUseLocalMessageCache
122 ? $services->getLocalServerObjectCache()
123 : new EmptyBagOStuff(),
124 $wgUseDatabaseMessages,
125 $wgMsgCacheExpiry,
126 $services->getContentLanguage()
127 );
128 }
129
130 return self::$instance;
131 }
132
133 /**
134 * Destroy the singleton instance
135 *
136 * @since 1.18
137 */
138 public static function destroyInstance() {
139 self::$instance = null;
140 }
141
142 /**
143 * Normalize message key input
144 *
145 * @param string $key Input message key to be normalized
146 * @return string Normalized message key
147 */
148 public static function normalizeKey( $key ) {
149 $lckey = strtr( $key, ' ', '_' );
150 if ( ord( $lckey ) < 128 ) {
151 $lckey[0] = strtolower( $lckey[0] );
152 } else {
153 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
154 }
155
156 return $lckey;
157 }
158
159 /**
160 * @param WANObjectCache $wanCache
161 * @param BagOStuff $clusterCache
162 * @param BagOStuff $serverCache
163 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
164 * @param int $expiry Lifetime for cache. @see $mExpiry.
165 * @param Language|null $contLang Content language of site
166 */
167 public function __construct(
168 WANObjectCache $wanCache,
169 BagOStuff $clusterCache,
170 BagOStuff $serverCache,
171 $useDB,
172 $expiry,
173 Language $contLang = null
174 ) {
175 $this->wanCache = $wanCache;
176 $this->clusterCache = $clusterCache;
177 $this->srvCache = $serverCache;
178
179 $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
180
181 $this->mDisable = !$useDB;
182 $this->mExpiry = $expiry;
183 $this->contLang = $contLang ?? MediaWikiServices::getInstance()->getContentLanguage();
184 }
185
186 /**
187 * ParserOptions is lazy initialised.
188 *
189 * @return ParserOptions
190 */
191 function getParserOptions() {
192 global $wgUser;
193
194 if ( !$this->mParserOptions ) {
195 if ( !$wgUser->isSafeToLoad() ) {
196 // $wgUser isn't unstubbable yet, so don't try to get a
197 // ParserOptions for it. And don't cache this ParserOptions
198 // either.
199 $po = ParserOptions::newFromAnon();
200 $po->setAllowUnsafeRawHtml( false );
201 $po->setTidy( true );
202 return $po;
203 }
204
205 $this->mParserOptions = new ParserOptions;
206 // Messages may take parameters that could come
207 // from malicious sources. As a precaution, disable
208 // the <html> parser tag when parsing messages.
209 $this->mParserOptions->setAllowUnsafeRawHtml( false );
210 // For the same reason, tidy the output!
211 $this->mParserOptions->setTidy( true );
212 }
213
214 return $this->mParserOptions;
215 }
216
217 /**
218 * Try to load the cache from APC.
219 *
220 * @param string $code Optional language code, see documenation of load().
221 * @return array|bool The cache array, or false if not in cache.
222 */
223 protected function getLocalCache( $code ) {
224 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
225
226 return $this->srvCache->get( $cacheKey );
227 }
228
229 /**
230 * Save the cache to APC.
231 *
232 * @param string $code
233 * @param array $cache The cache array
234 */
235 protected function saveToLocalCache( $code, $cache ) {
236 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
237 $this->srvCache->set( $cacheKey, $cache );
238 }
239
240 /**
241 * Loads messages from caches or from database in this order:
242 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
243 * (2) memcached
244 * (3) from the database.
245 *
246 * When successfully loading from (2) or (3), all higher level caches are
247 * updated for the newest version.
248 *
249 * Nothing is loaded if member variable mDisable is true, either manually
250 * set by calling code or if message loading fails (is this possible?).
251 *
252 * Returns true if cache is already populated or it was successfully populated,
253 * or false if populating empty cache fails. Also returns true if MessageCache
254 * is disabled.
255 *
256 * @param string $code Language to which load messages
257 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
258 * @throws InvalidArgumentException
259 * @return bool
260 */
261 protected function load( $code, $mode = null ) {
262 if ( !is_string( $code ) ) {
263 throw new InvalidArgumentException( "Missing language code" );
264 }
265
266 # Don't do double loading...
267 if ( $this->cache->has( $code ) && $mode != self::FOR_UPDATE ) {
268 return true;
269 }
270
271 $this->overridable = array_flip( Language::getMessageKeysFor( $code ) );
272
273 # 8 lines of code just to say (once) that message cache is disabled
274 if ( $this->mDisable ) {
275 static $shownDisabled = false;
276 if ( !$shownDisabled ) {
277 wfDebug( __METHOD__ . ": disabled\n" );
278 $shownDisabled = true;
279 }
280
281 return true;
282 }
283
284 # Loading code starts
285 $success = false; # Keep track of success
286 $staleCache = false; # a cache array with expired data, or false if none has been loaded
287 $where = []; # Debug info, delayed to avoid spamming debug log too much
288
289 # Hash of the contents is stored in memcache, to detect if data-center cache
290 # or local cache goes out of date (e.g. due to replace() on some other server)
291 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
292 $this->cacheVolatile[$code] = $hashVolatile;
293
294 # Try the local cache and check against the cluster hash key...
295 $cache = $this->getLocalCache( $code );
296 if ( !$cache ) {
297 $where[] = 'local cache is empty';
298 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
299 $where[] = 'local cache has the wrong hash';
300 $staleCache = $cache;
301 } elseif ( $this->isCacheExpired( $cache ) ) {
302 $where[] = 'local cache is expired';
303 $staleCache = $cache;
304 } elseif ( $hashVolatile ) {
305 $where[] = 'local cache validation key is expired/volatile';
306 $staleCache = $cache;
307 } else {
308 $where[] = 'got from local cache';
309 $this->cache->set( $code, $cache );
310 $success = true;
311 }
312
313 if ( !$success ) {
314 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
315 # Try the global cache. If it is empty, try to acquire a lock. If
316 # the lock can't be acquired, wait for the other thread to finish
317 # and then try the global cache a second time.
318 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
319 if ( $hashVolatile && $staleCache ) {
320 # Do not bother fetching the whole cache blob to avoid I/O.
321 # Instead, just try to get the non-blocking $statusKey lock
322 # below, and use the local stale value if it was not acquired.
323 $where[] = 'global cache is presumed expired';
324 } else {
325 $cache = $this->clusterCache->get( $cacheKey );
326 if ( !$cache ) {
327 $where[] = 'global cache is empty';
328 } elseif ( $this->isCacheExpired( $cache ) ) {
329 $where[] = 'global cache is expired';
330 $staleCache = $cache;
331 } elseif ( $hashVolatile ) {
332 # DB results are replica DB lag prone until the holdoff TTL passes.
333 # By then, updates should be reflected in loadFromDBWithLock().
334 # One thread renerates the cache while others use old values.
335 $where[] = 'global cache is expired/volatile';
336 $staleCache = $cache;
337 } else {
338 $where[] = 'got from global cache';
339 $this->cache->set( $code, $cache );
340 $this->saveToCaches( $cache, 'local-only', $code );
341 $success = true;
342 }
343 }
344
345 if ( $success ) {
346 # Done, no need to retry
347 break;
348 }
349
350 # We need to call loadFromDB. Limit the concurrency to one process.
351 # This prevents the site from going down when the cache expires.
352 # Note that the DB slam protection lock here is non-blocking.
353 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
354 if ( $loadStatus === true ) {
355 $success = true;
356 break;
357 } elseif ( $staleCache ) {
358 # Use the stale cache while some other thread constructs the new one
359 $where[] = 'using stale cache';
360 $this->cache->set( $code, $staleCache );
361 $success = true;
362 break;
363 } elseif ( $failedAttempts > 0 ) {
364 # Already blocked once, so avoid another lock/unlock cycle.
365 # This case will typically be hit if memcached is down, or if
366 # loadFromDB() takes longer than LOCK_WAIT.
367 $where[] = "could not acquire status key.";
368 break;
369 } elseif ( $loadStatus === 'cantacquire' ) {
370 # Wait for the other thread to finish, then retry. Normally,
371 # the memcached get() will then yeild the other thread's result.
372 $where[] = 'waited for other thread to complete';
373 $this->getReentrantScopedLock( $cacheKey );
374 } else {
375 # Disable cache; $loadStatus is 'disabled'
376 break;
377 }
378 }
379 }
380
381 if ( !$success ) {
382 $where[] = 'loading FAILED - cache is disabled';
383 $this->mDisable = true;
384 $this->cache->set( $code, [] );
385 wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
386 # This used to throw an exception, but that led to nasty side effects like
387 # the whole wiki being instantly down if the memcached server died
388 }
389
390 if ( !$this->cache->has( $code ) ) { // sanity
391 throw new LogicException( "Process cache for '$code' should be set by now." );
392 }
393
394 $info = implode( ', ', $where );
395 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
396
397 return $success;
398 }
399
400 /**
401 * @param string $code
402 * @param array &$where List of wfDebug() comments
403 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
404 * @return bool|string True on success or one of ("cantacquire", "disabled")
405 */
406 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
407 # If cache updates on all levels fail, give up on message overrides.
408 # This is to avoid easy site outages; see $saveSuccess comments below.
409 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
410 $status = $this->clusterCache->get( $statusKey );
411 if ( $status === 'error' ) {
412 $where[] = "could not load; method is still globally disabled";
413 return 'disabled';
414 }
415
416 # Now let's regenerate
417 $where[] = 'loading from database';
418
419 # Lock the cache to prevent conflicting writes.
420 # This lock is non-blocking so stale cache can quickly be used.
421 # Note that load() will call a blocking getReentrantScopedLock()
422 # after this if it really need to wait for any current thread.
423 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
424 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
425 if ( !$scopedLock ) {
426 $where[] = 'could not acquire main lock';
427 return 'cantacquire';
428 }
429
430 $cache = $this->loadFromDB( $code, $mode );
431 $this->cache->set( $code, $cache );
432 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
433
434 if ( !$saveSuccess ) {
435 /**
436 * Cache save has failed.
437 *
438 * There are two main scenarios where this could be a problem:
439 * - The cache is more than the maximum size (typically 1MB compressed).
440 * - Memcached has no space remaining in the relevant slab class. This is
441 * unlikely with recent versions of memcached.
442 *
443 * Either way, if there is a local cache, nothing bad will happen. If there
444 * is no local cache, disabling the message cache for all requests avoids
445 * incurring a loadFromDB() overhead on every request, and thus saves the
446 * wiki from complete downtime under moderate traffic conditions.
447 */
448 if ( $this->srvCache instanceof EmptyBagOStuff ) {
449 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
450 $where[] = 'could not save cache, disabled globally for 5 minutes';
451 } else {
452 $where[] = "could not save global cache";
453 }
454 }
455
456 return true;
457 }
458
459 /**
460 * Loads cacheable messages from the database. Messages bigger than
461 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
462 * on-demand from the database later.
463 *
464 * @param string $code Language code
465 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
466 * @return array Loaded messages for storing in caches
467 */
468 protected function loadFromDB( $code, $mode = null ) {
469 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
470
471 // (T164666) The query here performs really poorly on WMF's
472 // contributions replicas. We don't have a way to say "any group except
473 // contributions", so for the moment let's specify 'api'.
474 // @todo: Get rid of this hack.
475 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
476
477 $cache = [];
478
479 $mostused = []; // list of "<cased message key>/<code>"
480 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
481 if ( !$this->cache->has( $wgLanguageCode ) ) {
482 $this->load( $wgLanguageCode );
483 }
484 $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
485 foreach ( $mostused as $key => $value ) {
486 $mostused[$key] = "$value/$code";
487 }
488 }
489
490 // Get the list of software-defined messages in core/extensions
491 $overridable = array_flip( Language::getMessageKeysFor( $wgLanguageCode ) );
492
493 // Common conditions
494 $conds = [
495 'page_is_redirect' => 0,
496 'page_namespace' => NS_MEDIAWIKI,
497 ];
498 if ( count( $mostused ) ) {
499 $conds['page_title'] = $mostused;
500 } elseif ( $code !== $wgLanguageCode ) {
501 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
502 } else {
503 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
504 # other than language code.
505 $conds[] = 'page_title NOT' .
506 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
507 }
508
509 // Set the stubs for oversized software-defined messages in the main cache map
510 $res = $dbr->select(
511 'page',
512 [ 'page_title', 'page_latest' ],
513 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
514 __METHOD__ . "($code)-big"
515 );
516 foreach ( $res as $row ) {
517 $name = $this->contLang->lcfirst( $row->page_title );
518 // Include entries/stubs for all keys in $mostused in adaptive mode
519 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $name, $overridable ) ) {
520 $cache[$row->page_title] = '!TOO BIG';
521 }
522 // At least include revision ID so page changes are reflected in the hash
523 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
524 }
525
526 // Set the text for small software-defined messages in the main cache map
527 $res = $dbr->select(
528 [ 'page', 'revision', 'text' ],
529 [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
530 array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
531 __METHOD__ . "($code)-small",
532 [],
533 [
534 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
535 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
536 ]
537 );
538 foreach ( $res as $row ) {
539 $name = $this->contLang->lcfirst( $row->page_title );
540 // Include entries/stubs for all keys in $mostused in adaptive mode
541 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $name, $overridable ) ) {
542 $text = Revision::getRevisionText( $row );
543 if ( $text === false ) {
544 // Failed to fetch data; possible ES errors?
545 // Store a marker to fetch on-demand as a workaround...
546 // TODO Use a differnt marker
547 $entry = '!TOO BIG';
548 wfDebugLog(
549 'MessageCache',
550 __METHOD__
551 . ": failed to load message page text for {$row->page_title} ($code)"
552 );
553 } else {
554 $entry = ' ' . $text;
555 }
556 $cache[$row->page_title] = $entry;
557 } else {
558 // T193271: cache object gets too big and slow to generate.
559 // At least include revision ID so page changes are reflected in the hash.
560 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
561 }
562 }
563
564 $cache['VERSION'] = MSG_CACHE_VERSION;
565 ksort( $cache );
566
567 # Hash for validating local cache (APC). No need to take into account
568 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
569 # stored and fetched from memcache.
570 $cache['HASH'] = md5( serialize( $cache ) );
571 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
572 unset( $cache['EXCESSIVE'] ); // only needed for hash
573
574 return $cache;
575 }
576
577 /**
578 * @param string $name Message name with lowercase first letter
579 * @param array $overridable Map of (key => unused) for software-defined messages
580 * @return bool
581 */
582 private function isMainCacheable( $name, array $overridable ) {
583 // Include common conversion table pages. This also avoids problems with
584 // Installer::parse() bailing out due to disallowed DB queries (T207979).
585 return ( isset( $overridable[$name] ) || strpos( $name, 'conversiontable/' ) === 0 );
586 }
587
588 /**
589 * Updates cache as necessary when message page is changed
590 *
591 * @param string $title Message cache key with initial uppercase letter
592 * @param string|bool $text New contents of the page (false if deleted)
593 */
594 public function replace( $title, $text ) {
595 global $wgLanguageCode;
596
597 if ( $this->mDisable ) {
598 return;
599 }
600
601 list( $msg, $code ) = $this->figureMessage( $title );
602 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
603 // Content language overrides do not use the /<code> suffix
604 return;
605 }
606
607 // (a) Update the process cache with the new message text
608 if ( $text === false ) {
609 // Page deleted
610 $this->cache->setField( $code, $title, '!NONEXISTENT' );
611 } else {
612 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
613 $this->cache->setField( $code, $title, ' ' . $text );
614 }
615
616 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
617 DeferredUpdates::addUpdate(
618 new MessageCacheUpdate( $code, $title, $msg ),
619 DeferredUpdates::PRESEND
620 );
621 }
622
623 /**
624 * @param string $code
625 * @param array[] $replacements List of (title, message key) pairs
626 * @throws MWException
627 */
628 public function refreshAndReplaceInternal( $code, array $replacements ) {
629 global $wgMaxMsgCacheEntrySize;
630
631 // Allow one caller at a time to avoid race conditions
632 $scopedLock = $this->getReentrantScopedLock(
633 $this->clusterCache->makeKey( 'messages', $code )
634 );
635 if ( !$scopedLock ) {
636 foreach ( $replacements as list( $title ) ) {
637 LoggerFactory::getInstance( 'MessageCache' )->error(
638 __METHOD__ . ': could not acquire lock to update {title} ({code})',
639 [ 'title' => $title, 'code' => $code ] );
640 }
641
642 return;
643 }
644
645 // Load the existing cache to update it in the local DC cache.
646 // The other DCs will see a hash mismatch.
647 if ( $this->load( $code, self::FOR_UPDATE ) ) {
648 $cache = $this->cache->get( $code );
649 } else {
650 // Err? Fall back to loading from the database.
651 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
652 }
653 // Check if individual cache keys should exist and update cache accordingly
654 $newTextByTitle = []; // map of (title => content)
655 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
656 foreach ( $replacements as list( $title ) ) {
657 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
658 $page->loadPageData( $page::READ_LATEST );
659 $text = $this->getMessageTextFromContent( $page->getContent() );
660 // Remember the text for the blob store update later on
661 $newTextByTitle[$title] = $text;
662 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
663 if ( !is_string( $text ) ) {
664 $cache[$title] = '!NONEXISTENT';
665 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
666 $cache[$title] = '!TOO BIG';
667 $newBigTitles[$title] = $page->getLatest();
668 } else {
669 $cache[$title] = ' ' . $text;
670 }
671 }
672 // Update HASH for the new key. Incorporates various administrative keys,
673 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
674 // and previous replace() calls), but that doesn't really matter since we
675 // only ever compare it for equality with a copy saved by saveToCaches().
676 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
677 // Update the too-big WAN cache entries now that we have the new HASH
678 foreach ( $newBigTitles as $title => $id ) {
679 // Match logic of loadCachedMessagePageEntry()
680 $this->wanCache->set(
681 $this->bigMessageCacheKey( $cache['HASH'], $title ),
682 ' ' . $newTextByTitle[$title],
683 $this->mExpiry
684 );
685 }
686 // Mark this cache as definitely being "latest" (non-volatile) so
687 // load() calls do not try to refresh the cache with replica DB data
688 $cache['LATEST'] = time();
689 // Update the process cache
690 $this->cache->set( $code, $cache );
691 // Pre-emptively update the local datacenter cache so things like edit filter and
692 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
693 // The datacenter handling replace() calls should be the same one handling edits
694 // as they require HTTP POST.
695 $this->saveToCaches( $cache, 'all', $code );
696 // Release the lock now that the cache is saved
697 ScopedCallback::consume( $scopedLock );
698
699 // Relay the purge. Touching this check key expires cache contents
700 // and local cache (APC) validation hash across all datacenters.
701 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
702
703 // Purge the messages in the message blob store and fire any hook handlers
704 $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
705 $blobStore = $resourceloader->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'
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 $name = $this->contLang->lcfirst( $title );
1057 if ( !$this->isMainCacheable( $name, $this->overridable ) ) {
1058 // Message page does not override any software-defined message. A custom
1059 // message might be defined to have content or settings specific to the wiki.
1060 // Load the message page, utilizing the individual message cache as needed.
1061 $entry = $this->loadCachedMessagePageEntry(
1062 $title,
1063 $code,
1064 $this->cache->getField( $code, 'HASH' )
1065 );
1066 }
1067 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1068 // Message does not have a MediaWiki page definition; try hook handlers
1069 $message = false;
1070 Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1071 if ( $message !== false ) {
1072 $this->cache->setField( $code, $title, ' ' . $message );
1073 } else {
1074 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1075 }
1076
1077 return $message;
1078 }
1079 }
1080
1081 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1082 if ( $this->cacheVolatile[$code] ) {
1083 // Make sure that individual keys respect the WAN cache holdoff period too
1084 LoggerFactory::getInstance( 'MessageCache' )->debug(
1085 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1086 [ 'titleKey' => $title, 'code' => $code ] );
1087 } else {
1088 $this->cache->setField( $code, $title, $entry );
1089 }
1090 // The message exists, so make sure a string is returned
1091 return (string)substr( $entry, 1 );
1092 }
1093
1094 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1095
1096 return false;
1097 }
1098
1099 /**
1100 * @param string $dbKey
1101 * @param string $code
1102 * @param string $hash
1103 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1104 */
1105 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1106 $fname = __METHOD__;
1107 return $this->srvCache->getWithSetCallback(
1108 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1109 IExpiringStore::TTL_MINUTE,
1110 function () use ( $code, $dbKey, $hash, $fname ) {
1111 return $this->wanCache->getWithSetCallback(
1112 $this->bigMessageCacheKey( $hash, $dbKey ),
1113 $this->mExpiry,
1114 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1115 // Try loading the message from the database
1116 $dbr = wfGetDB( DB_REPLICA );
1117 $setOpts += Database::getCacheSetOptions( $dbr );
1118 // Use newKnownCurrent() to avoid querying revision/user tables
1119 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1120 $revision = Revision::newKnownCurrent( $dbr, $title );
1121 if ( !$revision ) {
1122 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1123 // When overrides are created, self::replace() takes care of the cache.
1124 return '!NONEXISTENT';
1125 }
1126 $content = $revision->getContent();
1127 if ( $content ) {
1128 $message = $this->getMessageTextFromContent( $content );
1129 } else {
1130 LoggerFactory::getInstance( 'MessageCache' )->warning(
1131 $fname . ': failed to load page text for \'{titleKey}\'',
1132 [ 'titleKey' => $dbKey, 'code' => $code ]
1133 );
1134 $message = null;
1135 }
1136
1137 if ( !is_string( $message ) ) {
1138 // Revision failed to load Content, or Content is incompatible with wikitext.
1139 // Possibly a temporary loading failure.
1140 $ttl = 5;
1141
1142 return '!NONEXISTENT';
1143 }
1144
1145 return ' ' . $message;
1146 }
1147 );
1148 }
1149 );
1150 }
1151
1152 /**
1153 * @param string $message
1154 * @param bool $interface
1155 * @param Language|null $language
1156 * @param Title|null $title
1157 * @return string
1158 */
1159 public function transform( $message, $interface = false, $language = null, $title = null ) {
1160 // Avoid creating parser if nothing to transform
1161 if ( strpos( $message, '{{' ) === false ) {
1162 return $message;
1163 }
1164
1165 if ( $this->mInParser ) {
1166 return $message;
1167 }
1168
1169 $parser = $this->getParser();
1170 if ( $parser ) {
1171 $popts = $this->getParserOptions();
1172 $popts->setInterfaceMessage( $interface );
1173 $popts->setTargetLanguage( $language );
1174
1175 $userlang = $popts->setUserLang( $language );
1176 $this->mInParser = true;
1177 $message = $parser->transformMsg( $message, $popts, $title );
1178 $this->mInParser = false;
1179 $popts->setUserLang( $userlang );
1180 }
1181
1182 return $message;
1183 }
1184
1185 /**
1186 * @return Parser
1187 */
1188 public function getParser() {
1189 global $wgParser, $wgParserConf;
1190
1191 if ( !$this->mParser && isset( $wgParser ) ) {
1192 # Do some initialisation so that we don't have to do it twice
1193 $wgParser->firstCallInit();
1194 # Clone it and store it
1195 $class = $wgParserConf['class'];
1196 if ( $class == ParserDiffTest::class ) {
1197 # Uncloneable
1198 $this->mParser = new $class( $wgParserConf );
1199 } else {
1200 $this->mParser = clone $wgParser;
1201 }
1202 }
1203
1204 return $this->mParser;
1205 }
1206
1207 /**
1208 * @param string $text
1209 * @param Title|null $title
1210 * @param bool $linestart Whether or not this is at the start of a line
1211 * @param bool $interface Whether this is an interface message
1212 * @param Language|string|null $language Language code
1213 * @return ParserOutput|string
1214 */
1215 public function parse( $text, $title = null, $linestart = true,
1216 $interface = false, $language = null
1217 ) {
1218 global $wgTitle;
1219
1220 if ( $this->mInParser ) {
1221 return htmlspecialchars( $text );
1222 }
1223
1224 $parser = $this->getParser();
1225 $popts = $this->getParserOptions();
1226 $popts->setInterfaceMessage( $interface );
1227
1228 if ( is_string( $language ) ) {
1229 $language = Language::factory( $language );
1230 }
1231 $popts->setTargetLanguage( $language );
1232
1233 if ( !$title || !$title instanceof Title ) {
1234 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1235 wfGetAllCallers( 6 ) . ' with no title set.' );
1236 $title = $wgTitle;
1237 }
1238 // Sometimes $wgTitle isn't set either...
1239 if ( !$title ) {
1240 # It's not uncommon having a null $wgTitle in scripts. See r80898
1241 # Create a ghost title in such case
1242 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1243 }
1244
1245 $this->mInParser = true;
1246 $res = $parser->parse( $text, $title, $popts, $linestart );
1247 $this->mInParser = false;
1248
1249 return $res;
1250 }
1251
1252 public function disable() {
1253 $this->mDisable = true;
1254 }
1255
1256 public function enable() {
1257 $this->mDisable = false;
1258 }
1259
1260 /**
1261 * Whether DB/cache usage is disabled for determining messages
1262 *
1263 * If so, this typically indicates either:
1264 * - a) load() failed to find a cached copy nor query the DB
1265 * - b) we are in a special context or error mode that cannot use the DB
1266 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1267 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1268 *
1269 * @return bool
1270 * @since 1.27
1271 */
1272 public function isDisabled() {
1273 return $this->mDisable;
1274 }
1275
1276 /**
1277 * Clear all stored messages in global and local cache
1278 *
1279 * Mainly used after a mass rebuild
1280 */
1281 public function clear() {
1282 $langs = Language::fetchLanguageNames( null, 'mw' );
1283 foreach ( array_keys( $langs ) as $code ) {
1284 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1285 }
1286 $this->cache->clear();
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 }