Debian Codegraph @

includes/language/MessageCache.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Config\ServiceOptions;
22 use MediaWiki\Content\Content;
23 use MediaWiki\Context\RequestContext;
24 use MediaWiki\Deferred\DeferredUpdates;
25 use MediaWiki\Deferred\MessageCacheUpdate;
26 use MediaWiki\HookContainer\HookContainer;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\Language\ILanguageConverter;
29 use MediaWiki\Language\Language;
30 use MediaWiki\Languages\LanguageConverterFactory;
31 use MediaWiki\Languages\LanguageFactory;
32 use MediaWiki\Languages\LanguageFallback;
33 use MediaWiki\Languages\LanguageNameUtils;
34 use MediaWiki\Linker\LinkTarget;
35 use MediaWiki\Logger\LoggerFactory;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Page\PageReference;
39 use MediaWiki\Page\PageReferenceValue;
40 use MediaWiki\Parser\Parser;
41 use MediaWiki\Parser\ParserFactory;
42 use MediaWiki\Parser\ParserOptions;
43 use MediaWiki\Parser\ParserOutput;
44 use MediaWiki\Revision\SlotRecord;
45 use MediaWiki\StubObject\StubObject;
46 use MediaWiki\StubObject\StubUserLang;
47 use MediaWiki\Title\Title;
48 use Psr\Log\LoggerAwareInterface;
49 use Psr\Log\LoggerInterface;
50 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
51 use Wikimedia\ObjectCache\BagOStuff;
52 use Wikimedia\ObjectCache\EmptyBagOStuff;
53 use Wikimedia\ObjectCache\WANObjectCache;
54 use Wikimedia\Rdbms\Database;
55 use Wikimedia\Rdbms\IDBAccessObject;
56 use Wikimedia\Rdbms\IExpression;
57 use Wikimedia\Rdbms\IResultWrapper;
58 use Wikimedia\Rdbms\LikeValue;
59 use Wikimedia\RequestTimeout\TimeoutException;
60 use Wikimedia\ScopedCallback;
61
62 /**
63 * MediaWiki message cache structure version.
64 * Bump this whenever the message cache format has changed.
65 */
66 define( 'MSG_CACHE_VERSION', 2 );
67
68 /**
69 * Cache messages that are defined by MediaWiki-namespace pages or by hooks.
70 *
71 * @ingroup Language
72 */
73 class MessageCache implements LoggerAwareInterface {
74 /**
75 * Options to be included in the ServiceOptions
76 */
77 public const CONSTRUCTOR_OPTIONS = [
78 MainConfigNames::UseDatabaseMessages,
79 MainConfigNames::MaxMsgCacheEntrySize,
80 MainConfigNames::AdaptiveMessageCache,
81 MainConfigNames::UseXssLanguage,
82 MainConfigNames::RawHtmlMessages,
83 ];
84
85 /**
86 * The size of the MapCacheLRU which stores message data. The maximum
87 * number of languages which can be efficiently loaded in a given request.
88 */
89 public const MAX_REQUEST_LANGUAGES = 10;
90
91 private const FOR_UPDATE = 1; // force message reload
92
93 /** How long to wait for memcached locks */
94 private const WAIT_SEC = 15;
95 /** How long memcached locks last */
96 private const LOCK_TTL = 30;
97
98 /**
99 * Lifetime for cache, for keys stored in $wanCache, in seconds.
100 */
101 private const WAN_TTL = ExpirationAwareness::TTL_DAY;
102
103 /** @var LoggerInterface */
104 private $logger;
105
106 /**
107 * Process cache of loaded messages that are defined in MediaWiki namespace
108 *
109 * @var MapCacheLRU Map of (language code => key => " <MESSAGE>" or "!TOO BIG" or "!ERROR")
110 */
111 private $cache;
112
113 /**
114 * Map of (lowercase message key => unused) for all software-defined messages
115 *
116 * @var array
117 */
118 private $systemMessageNames;
119
120 /**
121 * @var bool[] Map of (language code => boolean)
122 */
123 private $cacheVolatile = [];
124
125 /**
126 * Should mean that database cannot be used, but check
127 * @var bool
128 */
129 private $disable;
130
131 /** @var int Maximum entry size in bytes */
132 private $maxEntrySize;
133
134 /** @var bool */
135 private $adaptive;
136
137 /** @var bool */
138 private $useXssLanguage;
139
140 /** @var string[] */
141 private $rawHtmlMessages;
142
143 /**
144 * Message cache has its own parser which it uses to transform messages
145 * @var ParserOptions
146 */
147 private $parserOptions;
148
149 /** @var ?Parser Lazy-created via self::getParser() */
150 private $parser = null;
151
152 /**
153 * @var bool
154 */
155 private $inParser = false;
156
157 /** @var WANObjectCache */
158 private $wanCache;
159 /** @var BagOStuff */
160 private $clusterCache;
161 /** @var BagOStuff */
162 private $srvCache;
163 /** @var Language */
164 private $contLang;
165 /** @var string */
166 private $contLangCode;
167 /** @var ILanguageConverter */
168 private $contLangConverter;
169 /** @var LanguageFactory */
170 private $langFactory;
171 /** @var LocalisationCache */
172 private $localisationCache;
173 /** @var LanguageNameUtils */
174 private $languageNameUtils;
175 /** @var LanguageFallback */
176 private $languageFallback;
177 /** @var HookRunner */
178 private $hookRunner;
179 /** @var ParserFactory */
180 private $parserFactory;
181
182 /** @var (string|callable)[]|null */
183 private $messageKeyOverrides;
184
185 /**
186 * Normalize message key input
187 *
188 * @param string $key Input message key to be normalized
189 * @return string Normalized message key
190 */
191 public static function normalizeKey( $key ) {
192 $lckey = strtr( $key, ' ', '_' );
193 if ( $lckey === '' ) {
194 // T300792
195 return $lckey;
196 }
197
198 if ( ord( $lckey[0] ) < 128 ) {
199 $lckey[0] = strtolower( $lckey[0] );
200 } else {
201 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
202 }
203
204 return $lckey;
205 }
206
207 /**
208 * @internal For use by ServiceWiring
209 * @param WANObjectCache $wanCache
210 * @param BagOStuff $clusterCache
211 * @param BagOStuff $serverCache
212 * @param Language $contLang Content language of site
213 * @param LanguageConverterFactory $langConverterFactory
214 * @param LoggerInterface $logger
215 * @param ServiceOptions $options
216 * @param LanguageFactory $langFactory
217 * @param LocalisationCache $localisationCache
218 * @param LanguageNameUtils $languageNameUtils
219 * @param LanguageFallback $languageFallback
220 * @param HookContainer $hookContainer
221 * @param ParserFactory $parserFactory
222 */
223 public function __construct(
224 WANObjectCache $wanCache,
225 BagOStuff $clusterCache,
226 BagOStuff $serverCache,
227 Language $contLang,
228 LanguageConverterFactory $langConverterFactory,
229 LoggerInterface $logger,
230 ServiceOptions $options,
231 LanguageFactory $langFactory,
232 LocalisationCache $localisationCache,
233 LanguageNameUtils $languageNameUtils,
234 LanguageFallback $languageFallback,
235 HookContainer $hookContainer,
236 ParserFactory $parserFactory
237 ) {
238 $this->wanCache = $wanCache;
239 $this->clusterCache = $clusterCache;
240 $this->srvCache = $serverCache;
241 $this->contLang = $contLang;
242 $this->contLangConverter = $langConverterFactory->getLanguageConverter( $contLang );
243 $this->contLangCode = $contLang->getCode();
244 $this->logger = $logger;
245 $this->langFactory = $langFactory;
246 $this->localisationCache = $localisationCache;
247 $this->languageNameUtils = $languageNameUtils;
248 $this->languageFallback = $languageFallback;
249 $this->hookRunner = new HookRunner( $hookContainer );
250 $this->parserFactory = $parserFactory;
251
252 // limit size
253 $this->cache = new MapCacheLRU( self::MAX_REQUEST_LANGUAGES );
254
255 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
256 $this->disable = !$options->get( MainConfigNames::UseDatabaseMessages );
257 $this->maxEntrySize = $options->get( MainConfigNames::MaxMsgCacheEntrySize );
258 $this->adaptive = $options->get( MainConfigNames::AdaptiveMessageCache );
259 $this->useXssLanguage = $options->get( MainConfigNames::UseXssLanguage );
260 $this->rawHtmlMessages = $options->get( MainConfigNames::RawHtmlMessages );
261 }
262
263 public function setLogger( LoggerInterface $logger ) {
264 $this->logger = $logger;
265 }
266
267 /**
268 * ParserOptions is lazily initialised.
269 *
270 * @return ParserOptions
271 */
272 private function getParserOptions() {
273 if ( !$this->parserOptions ) {
274 $context = RequestContext::getMain();
275 $user = $context->getUser();
276 if ( !$user->isSafeToLoad() ) {
277 // It isn't safe to use the context user yet, so don't try to get a
278 // ParserOptions for it. And don't cache this ParserOptions
279 // either.
280 $po = ParserOptions::newFromAnon();
281 $po->setAllowUnsafeRawHtml( false );
282 return $po;
283 }
284
285 $this->parserOptions = ParserOptions::newFromContext( $context );
286 // Messages may take parameters that could come
287 // from malicious sources. As a precaution, disable
288 // the <html> parser tag when parsing messages.
289 $this->parserOptions->setAllowUnsafeRawHtml( false );
290 }
291
292 return $this->parserOptions;
293 }
294
295 /**
296 * Try to load the cache from APC.
297 *
298 * @param string $code Optional language code, see documentation of load().
299 * @return array|false The cache array, or false if not in cache.
300 */
301 private function getLocalCache( $code ) {
302 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
303
304 return $this->srvCache->get( $cacheKey );
305 }
306
307 /**
308 * Save the cache to APC.
309 *
310 * @param string $code
311 * @param array $cache The cache array
312 */
313 private function saveToLocalCache( $code, $cache ) {
314 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
315 $this->srvCache->set( $cacheKey, $cache );
316 }
317
318 /**
319 * Loads messages from caches or from database in this order:
320 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
321 * (2) memcached
322 * (3) from the database.
323 *
324 * When successfully loading from (2) or (3), all higher level caches are
325 * updated for the newest version.
326 *
327 * Nothing is loaded if member variable mDisable is true, either manually
328 * set by calling code or if message loading fails (is this possible?).
329 *
330 * Returns true if cache is already populated, or it was successfully populated,
331 * or false if populating empty cache fails. Also returns true if MessageCache
332 * is disabled.
333 *
334 * @param string $code Which language to load messages for
335 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
336 * @return bool
337 */
338 private function load( string $code, $mode = null ) {
339 // Don't do double loading...
340 if ( $this->isLanguageLoaded( $code ) && $mode !== self::FOR_UPDATE ) {
341 return true;
342 }
343
344 // Show a log message (once) if loading is disabled
345 if ( $this->disable ) {
346 static $shownDisabled = false;
347 if ( !$shownDisabled ) {
348 $this->logger->debug( __METHOD__ . ': disabled' );
349 $shownDisabled = true;
350 }
351
352 return true;
353 }
354
355 try {
356 return $this->loadUnguarded( $code, $mode );
357 } catch ( Throwable $e ) {
358 // Don't try to load again during the exception handler
359 $this->disable = true;
360 throw $e;
361 }
362 }
363
364 /**
365 * Load messages from the cache or database, without exception guarding.
366 *
367 * @param string $code Which language to load messages for
368 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
369 * @return bool
370 */
371 private function loadUnguarded( $code, $mode ) {
372 $success = false; // Keep track of success
373 $staleCache = false; // a cache array with expired data, or false if none has been loaded
374 $where = []; // Debug info, delayed to avoid spamming debug log too much
375
376 // A hash of the expected content is stored in a WAN cache key, providing a way
377 // to invalid the local cache on every server whenever a message page changes.
378 [ $hash, $hashVolatile ] = $this->getValidationHash( $code );
379 $this->cacheVolatile[$code] = $hashVolatile;
380 $volatilityOnlyStaleness = false;
381
382 // Try the local cache and check against the cluster hash key...
383 $cache = $this->getLocalCache( $code );
384 if ( !$cache ) {
385 $where[] = 'local cache is empty';
386 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
387 $where[] = 'local cache has the wrong hash';
388 $staleCache = $cache;
389 } elseif ( $this->isCacheExpired( $cache ) ) {
390 $where[] = 'local cache is expired';
391 $staleCache = $cache;
392 } elseif ( $hashVolatile ) {
393 // Some recent message page changes might not show due to DB lag
394 $where[] = 'local cache validation key is expired/volatile';
395 $staleCache = $cache;
396 $volatilityOnlyStaleness = true;
397 } else {
398 $where[] = 'got from local cache';
399 $this->cache->set( $code, $cache );
400 $success = true;
401 }
402
403 if ( !$success ) {
404 // Try the cluster cache, using a lock for regeneration...
405 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
406 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
407 if ( $volatilityOnlyStaleness && $staleCache ) {
408 // While the cluster cache *might* be more up-to-date, we do not want
409 // the I/O strain of every application server fetching the key here during
410 // the volatility period. Either this thread wins the lock and regenerates
411 // the cache or the stale local cache value gets reused.
412 $where[] = 'global cache is presumed expired';
413 } else {
414 $cache = $this->clusterCache->get( $cacheKey );
415 if ( !$cache ) {
416 $where[] = 'global cache is empty';
417 } elseif ( $this->isCacheExpired( $cache ) ) {
418 $where[] = 'global cache is expired';
419 $staleCache = $cache;
420 } elseif ( $hashVolatile ) {
421 // Some recent message page changes might not show due to DB lag
422 $where[] = 'global cache is expired/volatile';
423 $staleCache = $cache;
424 } else {
425 $where[] = 'got from global cache';
426 $this->cache->set( $code, $cache );
427 $this->saveToCaches( $cache, 'local-only', $code );
428 $success = true;
429 break;
430 }
431 }
432
433 // We need to call loadFromDB(). Limit the concurrency to one thread.
434 // This prevents the site from going down when the cache expires.
435 // Note that the DB slam protection lock here is non-blocking.
436 $loadStatus = $this->loadFromDBWithMainLock( $code, $where, $mode );
437 if ( $loadStatus === true ) {
438 $success = true;
439 break;
440 } elseif ( $staleCache ) {
441 // Use the stale cache while some other thread constructs the new one
442 $where[] = 'using stale cache';
443 $this->cache->set( $code, $staleCache );
444 $success = true;
445 break;
446 } elseif ( $failedAttempts > 0 ) {
447 $where[] = 'failed to find cache after waiting';
448 // Already blocked once, so avoid another lock/unlock cycle.
449 // This case will typically be hit if memcached is down, or if
450 // loadFromDB() takes longer than LOCK_WAIT.
451 break;
452 } elseif ( $loadStatus === 'cantacquire' ) {
453 // Wait for the other thread to finish, then retry. Normally,
454 // the memcached get() will then yield the other thread's result.
455 $where[] = 'waiting for other thread to complete';
456 [ , $ioError ] = $this->getReentrantScopedLock( $code );
457 if ( $ioError ) {
458 $where[] = 'failed waiting';
459 // Call loadFromDB() with concurrency limited to one thread per server.
460 // It should be rare for all servers to lack even a stale local cache.
461 $success = $this->loadFromDBWithLocalLock( $code, $where, $mode );
462 break;
463 }
464 } else {
465 // Disable cache; $loadStatus is 'disabled'
466 break;
467 }
468 }
469 }
470
471 if ( !$success ) {
472 $where[] = 'loading FAILED - cache is disabled';
473 $this->disable = true;
474 $this->cache->set( $code, [] );
475 $this->logger->error( __METHOD__ . ": Failed to load $code" );
476 // This used to throw an exception, but that led to nasty side effects like
477 // the whole wiki being instantly down if the memcached server died
478 }
479
480 if ( !$this->isLanguageLoaded( $code ) ) {
481 throw new LogicException( "Process cache for '$code' should be set by now." );
482 }
483
484 $info = implode( ', ', $where );
485 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
486
487 return $success;
488 }
489
490 /**
491 * @param string $code
492 * @param string[] &$where List of debug comments
493 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_PRIMARY
494 * @return true|string One (true, "cantacquire", "disabled")
495 */
496 private function loadFromDBWithMainLock( $code, array &$where, $mode = null ) {
497 // If cache updates on all levels fail, give up on message overrides.
498 // This is to avoid easy site outages; see $saveSuccess comments below.
499 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
500 $status = $this->clusterCache->get( $statusKey );
501 if ( $status === 'error' ) {
502 $where[] = "could not load; method is still globally disabled";
503 return 'disabled';
504 }
505
506 // Now let's regenerate
507 $where[] = 'loading from DB';
508
509 // Lock the cache to prevent conflicting writes.
510 // This lock is non-blocking so stale cache can quickly be used.
511 // Note that load() will call a blocking getReentrantScopedLock()
512 // after this if it really needs to wait for any current thread.
513 [ $scopedLock ] = $this->getReentrantScopedLock( $code, 0 );
514 if ( !$scopedLock ) {
515 $where[] = 'could not acquire main lock';
516 return 'cantacquire';
517 }
518
519 $cache = $this->loadFromDB( $code, $mode );
520 $this->cache->set( $code, $cache );
521 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
522
523 if ( !$saveSuccess ) {
524 /**
525 * Cache save has failed.
526 *
527 * There are two main scenarios where this could be a problem:
528 * - The cache is more than the maximum size (typically 1MB compressed).
529 * - Memcached has no space remaining in the relevant slab class. This is
530 * unlikely with recent versions of memcached.
531 *
532 * Either way, if there is a local cache, nothing bad will happen. If there
533 * is no local cache, disabling the message cache for all requests avoids
534 * incurring a loadFromDB() overhead on every request, and thus saves the
535 * wiki from complete downtime under moderate traffic conditions.
536 */
537 if ( $this->srvCache instanceof EmptyBagOStuff ) {
538 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
539 $where[] = 'could not save cache, disabled globally for 5 minutes';
540 } else {
541 $where[] = "could not save global cache";
542 }
543 }
544
545 return true;
546 }
547
548 /**
549 * @param string $code
550 * @param string[] &$where List of debug comments
551 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_PRIMARY
552 * @return bool Success
553 */
554 private function loadFromDBWithLocalLock( $code, array &$where, $mode = null ) {
555 $success = false;
556 $where[] = 'loading from DB using local lock';
557
558 $scopedLock = $this->srvCache->getScopedLock(
559 $this->srvCache->makeKey( 'messages', $code ),
560 self::WAIT_SEC,
561 self::LOCK_TTL,
562 __METHOD__
563 );
564 if ( $scopedLock ) {
565 $cache = $this->loadFromDB( $code, $mode );
566 $this->cache->set( $code, $cache );
567 $this->saveToCaches( $cache, 'local-only', $code );
568 $success = true;
569 }
570
571 return $success;
572 }
573
574 /**
575 * Loads cacheable messages from the database. Messages bigger than
576 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
577 * on-demand from the database later.
578 *
579 * @param string $code Language code
580 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
581 * @return array Loaded messages for storing in caches
582 */
583 private function loadFromDB( $code, $mode = null ) {
584 $icp = MediaWikiServices::getInstance()->getConnectionProvider();
585
586 $dbr = ( $mode === self::FOR_UPDATE ) ? $icp->getPrimaryDatabase() : $icp->getReplicaDatabase();
587
588 $cache = [];
589
590 $mostused = []; // list of "<cased message key>/<code>"
591 if ( $this->adaptive && $code !== $this->contLangCode ) {
592 if ( !$this->cache->has( $this->contLangCode ) ) {
593 $this->load( $this->contLangCode );
594 }
595 $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
596 foreach ( $mostused as $key => $value ) {
597 $mostused[$key] = "$value/$code";
598 }
599 }
600
601 // Common conditions
602 $conds = [
603 // Treat redirects as not existing (T376398)
604 'page_is_redirect' => 0,
605 'page_namespace' => NS_MEDIAWIKI,
606 ];
607 if ( count( $mostused ) ) {
608 $conds['page_title'] = $mostused;
609 } elseif ( $code !== $this->contLangCode ) {
610 $conds[] = $dbr->expr(
611 'page_title',
612 IExpression::LIKE,
613 new LikeValue( $dbr->anyString(), '/', $code )
614 );
615 } else {
616 // Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
617 // other than language code.
618 $conds[] = $dbr->expr(
619 'page_title',
620 IExpression::NOT_LIKE,
621 new LikeValue( $dbr->anyString(), '/', $dbr->anyString() )
622 );
623 }
624
625 // Set the stubs for oversized software-defined messages in the main cache map
626 $res = $dbr->newSelectQueryBuilder()
627 ->select( [ 'page_title', 'page_latest' ] )
628 ->from( 'page' )
629 ->where( $conds )
630 ->andWhere( $dbr->expr( 'page_len', '>', intval( $this->maxEntrySize ) ) )
631 ->caller( __METHOD__ . "($code)-big" )->fetchResultSet();
632 foreach ( $res as $row ) {
633 // Include entries/stubs for all keys in $mostused in adaptive mode
634 if ( $this->adaptive || $this->isMainCacheable( $row->page_title ) ) {
635 $cache[$row->page_title] = '!TOO BIG';
636 }
637 // At least include revision ID so page changes are reflected in the hash
638 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
639 }
640
641 // RevisionStore cannot be injected as it would break the installer since
642 // it instantiates MessageCache before the DB.
643 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
644 // Set the text for small software-defined messages in the main cache map
645 $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
646
647 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
648 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
649 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
650 // `revision` first rather than `page`).
651 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
652 unset( $revQuery['joins']['page'] );
653 // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
654 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
655 // `page` to the start.
656 $revQuery['tables'] = array_merge(
657 [ 'page' ],
658 array_diff( $revQuery['tables'], [ 'page' ] )
659 );
660
661 $res = $dbr->newSelectQueryBuilder()
662 ->queryInfo( $revQuery )
663 ->where( $conds )
664 ->andWhere( [
665 $dbr->expr( 'page_len', '<=', intval( $this->maxEntrySize ) ),
666 'page_latest = rev_id' // get the latest revision only
667 ] )
668 ->caller( __METHOD__ . "($code)-small" )
669 ->straightJoinOption()
670 ->fetchResultSet();
671
672 // Don't load content from uncacheable rows (T313004)
673 [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
674 $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
675 'slots' => [ SlotRecord::MAIN ],
676 'content' => true
677 ] );
678 $revisions = $result->isOK() ? $result->getValue() : [];
679
680 foreach ( $cacheableRows as $row ) {
681 try {
682 $rev = $revisions[$row->rev_id] ?? null;
683 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
684 $text = $this->getMessageTextFromContent( $content );
685 } catch ( TimeoutException $e ) {
686 throw $e;
687 } catch ( Exception $ex ) {
688 $text = false;
689 }
690
691 if ( !is_string( $text ) ) {
692 $entry = '!ERROR';
693 $this->logger->error(
694 __METHOD__
695 . ": failed to load message page text for {$row->page_title} ($code)"
696 );
697 } else {
698 $entry = ' ' . $text;
699 }
700 $cache[$row->page_title] = $entry;
701 }
702
703 foreach ( $uncacheableRows as $row ) {
704 // T193271: The cache object gets too big and slow to generate.
705 // At least include revision ID, so that page changes are reflected in the hash.
706 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
707 }
708
709 $cache['VERSION'] = MSG_CACHE_VERSION;
710 ksort( $cache );
711
712 // Hash for validating local cache (APC). No need to take into account
713 // messages larger than $wgMaxMsgCacheEntrySize, since those are only
714 // stored and fetched from memcache.
715 $cache['HASH'] = md5( serialize( $cache ) );
716 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
717 unset( $cache['EXCESSIVE'] ); // only needed for hash
718
719 return $cache;
720 }
721
722 /**
723 * Whether the language was loaded and its data is still in the process cache.
724 *
725 * @param string $lang
726 * @return bool
727 */
728 private function isLanguageLoaded( $lang ) {
729 // It is important that this only returns true if the cache was fully
730 // populated by load(), so that callers can assume all cache keys exist.
731 // It is possible for $this->cache to be only partially populated through
732 // methods like MessageCache::replace(), which must not make this method
733 // return true (T208897). And this method must cease to return true
734 // if the language was evicted by MapCacheLRU (T230690).
735 return $this->cache->hasField( $lang, 'VERSION' );
736 }
737
738 /**
739 * Can the given DB key be added to the main cache blob? To reduce the
740 * abuse impact of the MediaWiki namespace by {{int:}} and CentralNotice,
741 * this is only true if the page overrides a predefined message.
742 *
743 * @param string $name Message name (possibly with /code suffix)
744 * @param string|null $code The language code. If this is null, message
745 * presence will be bulk loaded for the content language. Otherwise,
746 * presence will be detected by loading the specified message.
747 * @return bool
748 */
749 private function isMainCacheable( $name, $code = null ) {
750 // Convert the first letter to lowercase, and strip /code suffix
751 $name = $this->contLang->lcfirst( $name );
752 // Include common conversion table pages. This also avoids problems with
753 // Installer::parse() bailing out due to disallowed DB queries (T207979).
754 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
755 return true;
756 }
757 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
758
759 if ( $code === null ) {
760 // Bulk load
761 if ( $this->systemMessageNames === null ) {
762 $this->systemMessageNames = array_fill_keys(
763 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
764 true );
765 }
766 return isset( $this->systemMessageNames[$msg] );
767 } else {
768 // Use individual subitem
769 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
770 }
771 }
772
773 /**
774 * Separate cacheable from uncacheable rows in a page/revsion query result.
775 *
776 * @param IResultWrapper $res
777 * @return array{0:IResultWrapper|stdClass[],1:stdClass[]} An array with the cacheable
778 * rows in the first element and the uncacheable rows in the second.
779 */
780 private function separateCacheableRows( $res ) {
781 if ( $this->adaptive ) {
782 // Include entries/stubs for all keys in $mostused in adaptive mode
783 return [ $res, [] ];
784 }
785 $cacheableRows = [];
786 $uncacheableRows = [];
787 foreach ( $res as $row ) {
788 if ( $this->isMainCacheable( $row->page_title ) ) {
789 $cacheableRows[] = $row;
790 } else {
791 $uncacheableRows[] = $row;
792 }
793 }
794 return [ $cacheableRows, $uncacheableRows ];
795 }
796
797 /**
798 * Updates cache as necessary when message page is changed
799 *
800 * @param string $title Message cache key with the initial uppercase letter
801 * @param string|false $text New contents of the page (false if deleted)
802 */
803 public function replace( $title, $text ) {
804 if ( $this->disable ) {
805 return;
806 }
807
808 [ $msg, $code ] = $this->figureMessage( $title );
809 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
810 // Content language overrides do not use the /<code> suffix
811 return;
812 }
813
814 // (a) Update the process cache with the new message text
815 if ( $text === false ) {
816 // Page deleted
817 $this->cache->setField( $code, $title, '!NONEXISTENT' );
818 } else {
819 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up-to-date
820 $this->cache->setField( $code, $title, ' ' . $text );
821 }
822
823 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
824 DeferredUpdates::addUpdate(
825 new MessageCacheUpdate( $code, $title, $msg ),
826 DeferredUpdates::PRESEND
827 );
828 }
829
830 /**
831 * @param string $code
832 * @param array[] $replacements List of (title, message key) pairs
833 */
834 public function refreshAndReplaceInternal( string $code, array $replacements ) {
835 // Allow one caller at a time to avoid race conditions
836 [ $scopedLock ] = $this->getReentrantScopedLock( $code );
837 if ( !$scopedLock ) {
838 foreach ( $replacements as [ $title ] ) {
839 $this->logger->error(
840 __METHOD__ . ': could not acquire lock to update {title} ({code})',
841 [ 'title' => $title, 'code' => $code ] );
842 }
843
844 return;
845 }
846
847 // Load the existing cache to update it in the local DC cache.
848 // The other DCs will see a hash mismatch.
849 if ( $this->load( $code, self::FOR_UPDATE ) ) {
850 $cache = $this->cache->get( $code );
851 } else {
852 // Err? Fall back to loading from the database.
853 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
854 }
855 // Check if individual cache keys should exist and update cache accordingly
856 $newTextByTitle = []; // map of (title => content)
857 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
858 // Can not inject the WikiPageFactory as it would break the installer since
859 // it instantiates MessageCache before the DB.
860 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
861 foreach ( $replacements as [ $title ] ) {
862 $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
863 $page->loadPageData( IDBAccessObject::READ_LATEST );
864 $text = $this->getMessageTextFromContent( $page->getContent() );
865 // Remember the text for the blob store update later on
866 $newTextByTitle[$title] = $text ?? '';
867 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
868 if ( !is_string( $text ) ) {
869 $cache[$title] = '!NONEXISTENT';
870 } elseif ( strlen( $text ) > $this->maxEntrySize ) {
871 $cache[$title] = '!TOO BIG';
872 $newBigTitles[$title] = $page->getLatest();
873 } else {
874 $cache[$title] = ' ' . $text;
875 }
876 }
877 // Update HASH for the new key. Incorporates various administrative keys,
878 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
879 // and previous replace() calls), but that doesn't really matter since we
880 // only ever compare it for equality with a copy saved by saveToCaches().
881 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
882 // Update the too-big WAN cache entries now that we have the new HASH
883 foreach ( $newBigTitles as $title => $id ) {
884 // Match logic of loadCachedMessagePageEntry()
885 $this->wanCache->set(
886 $this->bigMessageCacheKey( $cache['HASH'], $title ),
887 ' ' . $newTextByTitle[$title],
888 self::WAN_TTL
889 );
890 }
891 // Mark this cache as definitely being "latest" (non-volatile) so
892 // load() calls do not try to refresh the cache with replica DB data
893 $cache['LATEST'] = time();
894 // Update the process cache
895 $this->cache->set( $code, $cache );
896 // Pre-emptively update the local datacenter cache so things like edit filter and
897 // prevented changes are reflected immediately; these often use MediaWiki: pages.
898 // The datacenter handling replace() calls should be the same one handling edits
899 // as they require HTTP POST.
900 $this->saveToCaches( $cache, 'all', $code );
901 // Release the lock now that the cache is saved
902 ScopedCallback::consume( $scopedLock );
903
904 // Relay the purge. Touching this check key expires cache contents
905 // and local cache (APC) validation hash across all datacenters.
906 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
907
908 // Purge the messages in the message blob store and fire any hook handlers
909 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
910 foreach ( $replacements as [ $title, $msg ] ) {
911 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
912 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
913 }
914 }
915
916 /**
917 * Is the given cache array expired due-to-time passing or a version change?
918 *
919 * @param array $cache
920 * @return bool
921 */
922 private function isCacheExpired( $cache ) {
923 return !isset( $cache['VERSION'] ) ||
924 !isset( $cache['EXPIRY'] ) ||
925 $cache['VERSION'] !== MSG_CACHE_VERSION ||
926 $cache['EXPIRY'] <= wfTimestampNow();
927 }
928
929 /**
930 * Shortcut to update caches.
931 *
932 * @param array $cache Cached messages with a version.
933 * @param string $dest Either "local-only" to save to local caches only
934 * or "all" to save to all caches.
935 * @param string|false $code Language code (default: false)
936 * @return bool
937 */
938 private function saveToCaches( array $cache, $dest, $code = false ) {
939 if ( $dest === 'all' ) {
940 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
941 $success = $this->clusterCache->set( $cacheKey, $cache );
942 $this->setValidationHash( $code, $cache );
943 } else {
944 $success = true;
945 }
946
947 $this->saveToLocalCache( $code, $cache );
948
949 return $success;
950 }
951
952 /**
953 * Get the md5 used to validate the local server cache
954 *
955 * @param string $code
956 * @return array (hash or false, bool expiry/volatility status)
957 */
958 private function getValidationHash( $code ) {
959 $curTTL = null;
960 $value = $this->wanCache->get(
961 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
962 $curTTL,
963 [ $this->getCheckKey( $code ) ]
964 );
965
966 if ( $value ) {
967 $hash = $value['hash'];
968 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
969 // Cache was recently updated via replace() and should be up-to-date.
970 // That method is only called in the primary datacenter and uses FOR_UPDATE.
971 $expired = false;
972 } else {
973 // See if the "check" key was bumped after the hash was generated
974 $expired = ( $curTTL < 0 );
975 }
976 } else {
977 // No hash found at all; cache must regenerate to be safe
978 $hash = false;
979 $expired = true;
980 }
981
982 return [ $hash, $expired ];
983 }
984
985 /**
986 * Set the md5 used to validate the local server cache
987 *
988 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
989 * be treated as "volatile" by getValidationHash() for the next few seconds.
990 * This is triggered when $cache is generated using FOR_UPDATE mode.
991 *
992 * @param string $code
993 * @param array $cache Cached messages with a version
994 */
995 private function setValidationHash( $code, array $cache ) {
996 $this->wanCache->set(
997 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
998 [
999 'hash' => $cache['HASH'],
1000 'latest' => $cache['LATEST'] ?? 0
1001 ],
1002 WANObjectCache::TTL_INDEFINITE
1003 );
1004 }
1005
1006 /**
1007 * @param string $code Which language to load messages for
1008 * @param int $timeout Wait timeout in seconds
1009 * @return array (ScopedCallback or null, whether locking failed due to an I/O error)
1010 * @phan-return array{0:ScopedCallback|null,1:bool}
1011 */
1012 private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
1013 $key = $this->clusterCache->makeKey( 'messages', $code );
1014
1015 $watchPoint = $this->clusterCache->watchErrors();
1016 $scopedLock = $this->clusterCache->getScopedLock(
1017 $key,
1018 $timeout,
1019 self::LOCK_TTL,
1020 __METHOD__
1021 );
1022 $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
1023
1024 return [ $scopedLock, $error ];
1025 }
1026
1027 /**
1028 * Get a message from either the content language or the user language.
1029 *
1030 * First, assemble a list of languages to attempt getting the message from. This
1031 * chain begins with the requested language and its fallbacks and then continues with
1032 * the content language and its fallbacks. For each language in the chain, the following
1033 * process will occur (in this order):
1034 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
1035 * Note: for the content language, there is no /lang subpage.
1036 * 2. Fetch from the static CDB cache.
1037 * 3. If available, check the database for fallback language overrides.
1038 *
1039 * This process provides a number of guarantees. When changing this code, make sure all
1040 * of these guarantees are preserved.
1041 * * If the requested language is *not* the content language, then the CDB cache for that
1042 * specific language will take precedence over the root database page ([[MW:msg]]).
1043 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
1044 * the message is available *anywhere* in the language for which it is a fallback.
1045 *
1046 * @param string $key The message key
1047 * @param bool $useDB If true, look for the message in the DB, false
1048 * to use only the compiled l10n cache.
1049 * @param bool|string|Language|null $language Code of the language to get the message for.
1050 * - If string and a valid code, will create a standard language object
1051 * - If string but not a valid code, will create a basic language object
1052 * - If false, create object from the current users language
1053 * - If true or null, create object from the wikis content language
1054 * - If language object, use it as given
1055 * - If this parameter omitted the object from the wikis content language is used
1056 * - Other values than a Language object or null are deprecated.
1057 * @param string &$usedKey @phan-output-reference If given, will be set to the message key
1058 * that the message was fetched from (the requested key may be overridden by hooks).
1059 *
1060 * @return string|false False if the message doesn't exist, otherwise the
1061 * message (which can be empty)
1062 */
1063 public function get( $key, $useDB = true, $language = null, &$usedKey = '' ) {
1064 if ( is_int( $key ) ) {
1065 // Fix numerical strings that somehow become ints on their way here
1066 $key = (string)$key;
1067 } elseif ( !is_string( $key ) ) {
1068 throw new TypeError( 'Message key must be a string' );
1069 } elseif ( $key === '' ) {
1070 // Shortcut: the empty key is always missing
1071 return false;
1072 }
1073
1074 $language ??= $this->contLang;
1075 $language = $this->getLanguageObject( $language );
1076
1077 // Normalise title-case input (with some inlining)
1078 $lckey = self::normalizeKey( $key );
1079
1080 // Initialize the overrides here to prevent calling the hook too early.
1081 if ( $this->messageKeyOverrides === null ) {
1082 $this->messageKeyOverrides = [];
1083 $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1084 }
1085
1086 if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1087 $override = $this->messageKeyOverrides[$lckey];
1088
1089 // Strings are deliberately interpreted as message keys,
1090 // to prevent ambiguity between message keys and functions.
1091 if ( is_string( $override ) ) {
1092 $lckey = $override;
1093 } else {
1094 $lckey = $override( $lckey, $this, $language, $useDB );
1095 }
1096 }
1097
1098 $this->hookRunner->onMessageCache__get( $lckey );
1099
1100 $usedKey = $lckey;
1101
1102 // Loop through each language in the fallback list until we find something useful
1103 $message = $this->getMessageFromFallbackChain(
1104 $language,
1105 $lckey,
1106 !$this->disable && $useDB
1107 );
1108
1109 // If we still have no message, maybe the key was in fact a full key so try that
1110 if ( $message === false ) {
1111 $parts = explode( '/', $lckey );
1112 // We may get calls for things that are http-urls from sidebar
1113 // Let's not load nonexistent languages for those
1114 // They usually have more than one slash.
1115 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1116 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1117 }
1118 }
1119
1120 // Post-processing if the message exists
1121 if ( $message !== false ) {
1122 // Fix whitespace
1123 $message = str_replace(
1124 [
1125 // Fix for trailing whitespace, removed by textarea
1126 '&#32;',
1127 // Fix for NBSP, converted to space by firefox
1128 '&nbsp;',
1129 '&#160;',
1130 '&shy;'
1131 ],
1132 [
1133 ' ',
1134 "\u{00A0}",
1135 "\u{00A0}",
1136 "\u{00AD}"
1137 ],
1138 $message
1139 );
1140 }
1141
1142 return $message;
1143 }
1144
1145 /**
1146 * Return a Language object from $langcode
1147 *
1148 * @param Language|string|bool $langcode Either:
1149 * - a Language object
1150 * - code of the language to get the message for, if it is
1151 * a valid code create a language for that language, if
1152 * it is a string but not a valid code then make a basic
1153 * language object
1154 * - a boolean: if it's false then use the global object for
1155 * the current user's language (as a fallback for the old parameter
1156 * functionality), or if it is true then use global object
1157 * for the wiki's content language.
1158 * @return Language|StubUserLang
1159 */
1160 private function getLanguageObject( $langcode ) {
1161 # Identify which language to get or create a language object for.
1162 # Using is_object here due to Stub objects.
1163 if ( is_object( $langcode ) ) {
1164 # Great, we already have the object (hopefully)!
1165 return $langcode;
1166 }
1167
1168 wfDeprecated( __METHOD__ . ' with not a Language object in $langcode', '1.43' );
1169 if ( $langcode === true || $langcode === $this->contLangCode ) {
1170 # $langcode is the language code of the wikis content language object.
1171 # or it is a boolean and value is true
1172 return $this->contLang;
1173 }
1174
1175 global $wgLang;
1176 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1177 # $langcode is the language code of user language object.
1178 # or it was a boolean and value is false
1179 return $wgLang;
1180 }
1181
1182 $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1183 if ( in_array( $langcode, $validCodes ) ) {
1184 # $langcode corresponds to a valid language.
1185 return $this->langFactory->getLanguage( $langcode );
1186 }
1187
1188 # $langcode is a string, but not a valid language code; use content language.
1189 $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1190 return $this->contLang;
1191 }
1192
1193 /**
1194 * Given a language, try and fetch messages from that language.
1195 *
1196 * Will also consider fallbacks of that language, the site language, and fallbacks for
1197 * the site language.
1198 *
1199 * @see MessageCache::get
1200 * @param Language|StubObject $lang Preferred language
1201 * @param string $lckey Lowercase key for the message (as for localisation cache)
1202 * @param bool $useDB Whether to include messages from the wiki database
1203 * @return string|false The message, or false if not found
1204 */
1205 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1206 $alreadyTried = [];
1207
1208 // First try the requested language.
1209 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1210 if ( $message !== false ) {
1211 return $message;
1212 }
1213
1214 // Now try checking the site language.
1215 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1216 return $message;
1217 }
1218
1219 /**
1220 * Given a language, try and fetch messages from that language and its fallbacks.
1221 *
1222 * @see MessageCache::get
1223 * @param Language|StubObject $lang Preferred language
1224 * @param string $lckey Lowercase key for the message (as for localisation cache)
1225 * @param bool $useDB Whether to include messages from the wiki database
1226 * @param bool[] &$alreadyTried Contains true for each language that has been tried already
1227 * @return string|false The message, or false if not found
1228 */
1229 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1230 $langcode = $lang->getCode();
1231
1232 // Try checking the database for the requested language
1233 if ( $useDB ) {
1234 $uckey = $this->contLang->ucfirst( $lckey );
1235
1236 if ( !isset( $alreadyTried[$langcode] ) ) {
1237 $message = $this->getMsgFromNamespace(
1238 $this->getMessagePageName( $langcode, $uckey ),
1239 $langcode
1240 );
1241 if ( $message !== false ) {
1242 return $message;
1243 }
1244 $alreadyTried[$langcode] = true;
1245 }
1246 } else {
1247 $uckey = null;
1248 }
1249
1250 // Return a special value handled in Message::format() to display the message key
1251 // (and fallback keys) and the parameters passed to the message.
1252 // TODO: Move to a better place.
1253 if ( $langcode === 'qqx' ) {
1254 return '($*)';
1255 } elseif (
1256 $langcode === 'x-xss' &&
1257 $this->useXssLanguage &&
1258 !in_array( $lckey, $this->rawHtmlMessages, true )
1259 ) {
1260 $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1261 $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1262 return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1263 }
1264
1265 // Check the localisation cache
1266 [ $defaultMessage, $messageSource ] =
1267 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1268 if ( $messageSource === $langcode ) {
1269 return $defaultMessage;
1270 }
1271
1272 // Try checking the database for all of the fallback languages
1273 if ( $useDB ) {
1274 $fallbackChain = $this->languageFallback->getAll( $langcode );
1275
1276 foreach ( $fallbackChain as $code ) {
1277 if ( isset( $alreadyTried[$code] ) ) {
1278 continue;
1279 }
1280
1281 $message = $this->getMsgFromNamespace(
1282 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1283 $this->getMessagePageName( $code, $uckey ), $code );
1284
1285 if ( $message !== false ) {
1286 return $message;
1287 }
1288 $alreadyTried[$code] = true;
1289
1290 // Reached the source language of the default message. Don't look for DB overrides
1291 // further back in the fallback chain. (T229992)
1292 if ( $code === $messageSource ) {
1293 return $defaultMessage;
1294 }
1295 }
1296 }
1297
1298 return $defaultMessage ?? false;
1299 }
1300
1301 /**
1302 * Get the message page name for a given language
1303 *
1304 * @param string $langcode
1305 * @param string $uckey Uppercase key for the message
1306 * @return string The page name
1307 */
1308 private function getMessagePageName( $langcode, $uckey ) {
1309 if ( $langcode === $this->contLangCode ) {
1310 // Messages created in the content language will not have the /lang extension
1311 return $uckey;
1312 } else {
1313 return "$uckey/$langcode";
1314 }
1315 }
1316
1317 /**
1318 * Get a message from the MediaWiki namespace, with caching. The key must
1319 * first be converted to two-part lang/msg form if necessary.
1320 *
1321 * Unlike self::get(), this function doesn't resolve fallback chains, and
1322 * some callers require this behavior. LanguageConverter::parseCachedTable()
1323 * and self::get() are some examples in core.
1324 *
1325 * @param string $title Message cache key with the initial uppercase letter
1326 * @param string $code Code denoting the language to try
1327 * @return string|false The message, or false if it does not exist or on error
1328 */
1329 public function getMsgFromNamespace( $title, $code ) {
1330 // Load all MediaWiki page definitions into cache. Note that individual keys
1331 // already loaded into the cache during this request remain in the cache, which
1332 // includes the value of hook-defined messages.
1333 $this->load( $code );
1334
1335 $entry = $this->cache->getField( $code, $title );
1336
1337 if ( $entry !== null ) {
1338 // Message page exists as an override of a software messages
1339 if ( substr( $entry, 0, 1 ) === ' ' ) {
1340 // The message exists and is not '!TOO BIG' or '!ERROR'
1341 return substr( $entry, 1 );
1342 } elseif ( $entry === '!NONEXISTENT' ) {
1343 // The text might be '-' or missing due to some data loss
1344 return false;
1345 }
1346 // Load the message page, utilizing the individual message cache.
1347 // If the page does not exist, there will be no hook handler fallbacks.
1348 $entry = $this->loadCachedMessagePageEntry(
1349 $title,
1350 $code,
1351 $this->cache->getField( $code, 'HASH' )
1352 );
1353 } else {
1354 // Message page either does not exist or does not override a software message
1355 if ( !$this->isMainCacheable( $title, $code ) ) {
1356 // Message page does not override any software-defined message. A custom
1357 // message might be defined to have content or settings specific to the wiki.
1358 // Load the message page, utilizing the individual message cache as needed.
1359 $entry = $this->loadCachedMessagePageEntry(
1360 $title,
1361 $code,
1362 $this->cache->getField( $code, 'HASH' )
1363 );
1364 }
1365 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1366 // Message does not have a MediaWiki page definition; try hook handlers
1367 $message = false;
1368 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1369 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1370 if ( $message !== false ) {
1371 $this->cache->setField( $code, $title, ' ' . $message );
1372 } else {
1373 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1374 }
1375
1376 return $message;
1377 }
1378 }
1379
1380 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1381 if ( $this->cacheVolatile[$code] ) {
1382 // Make sure that individual keys respect the WAN cache holdoff period too
1383 $this->logger->debug(
1384 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1385 [ 'titleKey' => $title, 'code' => $code ] );
1386 } else {
1387 $this->cache->setField( $code, $title, $entry );
1388 }
1389 // The message exists, so make sure a string is returned
1390 return substr( $entry, 1 );
1391 }
1392
1393 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1394
1395 return false;
1396 }
1397
1398 /**
1399 * @param string $dbKey
1400 * @param string $code
1401 * @param string $hash
1402 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1403 */
1404 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1405 $fname = __METHOD__;
1406 return $this->srvCache->getWithSetCallback(
1407 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1408 BagOStuff::TTL_HOUR,
1409 function () use ( $code, $dbKey, $hash, $fname ) {
1410 return $this->wanCache->getWithSetCallback(
1411 $this->bigMessageCacheKey( $hash, $dbKey ),
1412 self::WAN_TTL,
1413 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1414 // Try loading the message from the database
1415 $setOpts += Database::getCacheSetOptions(
1416 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
1417 );
1418 // Use newKnownCurrent() to avoid querying revision/user tables
1419 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1420 // Injecting RevisionStore breaks installer since it
1421 // instantiates MessageCache before DB.
1422 $revision = MediaWikiServices::getInstance()
1423 ->getRevisionLookup()
1424 ->getKnownCurrentRevision( $title );
1425 if ( !$revision ) {
1426 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1427 // When overrides are created, self::replace() takes care of the cache.
1428 return '!NONEXISTENT';
1429 }
1430 $content = $revision->getContent( SlotRecord::MAIN );
1431 if ( $content ) {
1432 $message = $this->getMessageTextFromContent( $content );
1433 } else {
1434 $this->logger->warning(
1435 $fname . ': failed to load page text for \'{titleKey}\'',
1436 [ 'titleKey' => $dbKey, 'code' => $code ]
1437 );
1438 $message = null;
1439 }
1440
1441 if ( !is_string( $message ) ) {
1442 // Revision failed to load Content, or Content is incompatible with wikitext.
1443 // Possibly a temporary loading failure.
1444 $ttl = 5;
1445
1446 return '!NONEXISTENT';
1447 }
1448
1449 return ' ' . $message;
1450 }
1451 );
1452 }
1453 );
1454 }
1455
1456 /**
1457 * @param string $message
1458 * @param bool $interface
1459 * @param Language|null $language
1460 * @param PageReference|null $page
1461 * @return string
1462 */
1463 public function transform( $message, $interface = false, $language = null, ?PageReference $page = null ) {
1464 // Avoid creating parser if nothing to transform
1465 if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1466 return $message;
1467 }
1468
1469 $parser = $this->getParser();
1470 $popts = $this->getParserOptions();
1471 $popts->setInterfaceMessage( $interface );
1472 $popts->setTargetLanguage( $language );
1473
1474 $userlang = $popts->setUserLang( $language );
1475 $this->inParser = true;
1476 $message = $parser->transformMsg( $message, $popts, $page );
1477 $this->inParser = false;
1478 $popts->setUserLang( $userlang );
1479
1480 return $message;
1481 }
1482
1483 /**
1484 * @return Parser
1485 */
1486 public function getParser() {
1487 if ( !$this->parser ) {
1488 $this->parser = $this->parserFactory->create();
1489 }
1490
1491 return $this->parser;
1492 }
1493
1494 /**
1495 * @param string $text
1496 * @param PageReference|null $page
1497 * @param bool $linestart Whether this is at the start of a line
1498 * @param bool $interface Whether this is an interface message
1499 * @param Language|StubUserLang|string|null $language Language code
1500 * @return ParserOutput|string
1501 */
1502 public function parse( $text, ?PageReference $page = null, $linestart = true,
1503 $interface = false, $language = null
1504 ) {
1505 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
1506 global $wgTitle;
1507
1508 if ( $this->inParser ) {
1509 return htmlspecialchars( $text );
1510 }
1511
1512 $parser = $this->getParser();
1513 $popts = $this->getParserOptions();
1514 $popts->setInterfaceMessage( $interface );
1515
1516 if ( is_string( $language ) ) {
1517 $language = $this->langFactory->getLanguage( $language );
1518 }
1519 $popts->setTargetLanguage( $language );
1520
1521 if ( !$page ) {
1522 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1523 $logger->info(
1524 __METHOD__ . ' called with no title set.',
1525 [ 'exception' => new RuntimeException ]
1526 );
1527 $page = $wgTitle;
1528 }
1529 // Sometimes $wgTitle isn't set either...
1530 if ( !$page ) {
1531 // It's not uncommon having a null $wgTitle in scripts. See r80898
1532 // Create a ghost title in such case
1533 $page = PageReferenceValue::localReference(
1534 NS_SPECIAL,
1535 'Badtitle/title not set in ' . __METHOD__
1536 );
1537 }
1538
1539 $this->inParser = true;
1540 $res = $parser->parse( $text, $page, $popts, $linestart );
1541 $this->inParser = false;
1542
1543 return $res;
1544 }
1545
1546 public function disable() {
1547 $this->disable = true;
1548 }
1549
1550 public function enable() {
1551 $this->disable = false;
1552 }
1553
1554 /**
1555 * Whether DB/cache usage is disabled for determining messages
1556 *
1557 * If so, this typically indicates either:
1558 * - a) load() failed to find a cached copy nor query the DB
1559 * - b) we are in a special context or error mode that cannot use the DB
1560 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1561 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1562 *
1563 * @return bool
1564 * @since 1.27
1565 */
1566 public function isDisabled() {
1567 return $this->disable;
1568 }
1569
1570 /**
1571 * Clear all stored messages in global and local cache
1572 *
1573 * Mainly used after a mass rebuild
1574 */
1575 public function clear() {
1576 $langs = $this->languageNameUtils->getLanguageNames();
1577 foreach ( $langs as $code => $_ ) {
1578 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1579 }
1580 $this->cache->clear();
1581 }
1582
1583 /**
1584 * @param string $key
1585 * @return array
1586 */
1587 public function figureMessage( $key ) {
1588 $pieces = explode( '/', $key );
1589 if ( count( $pieces ) < 2 ) {
1590 return [ $key, $this->contLangCode ];
1591 }
1592
1593 $lang = array_pop( $pieces );
1594 if ( !$this->languageNameUtils->getLanguageName(
1595 $lang,
1596 LanguageNameUtils::AUTONYMS,
1597 LanguageNameUtils::DEFINED
1598 ) ) {
1599 return [ $key, $this->contLangCode ];
1600 }
1601
1602 $message = implode( '/', $pieces );
1603
1604 return [ $message, $lang ];
1605 }
1606
1607 /**
1608 * Get all message keys stored in the message cache for a given language.
1609 * If $code is the content language code, this will return all message keys
1610 * for which MediaWiki:msgkey exists. If $code is another language code, this
1611 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1612 *
1613 * @param string $code Language code
1614 * @return string[]|null Array of message keys
1615 */
1616 public function getAllMessageKeys( $code ) {
1617 $this->load( $code );
1618 if ( !$this->cache->has( $code ) ) {
1619 // Apparently load() failed
1620 return null;
1621 }
1622 // Remove administrative keys
1623 $cache = $this->cache->get( $code );
1624 unset( $cache['VERSION'] );
1625 unset( $cache['EXPIRY'] );
1626 unset( $cache['EXCESSIVE'] );
1627 // Remove any !NONEXISTENT keys
1628 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1629
1630 // Keys may appear with a capital first letter. lcfirst them.
1631 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1632 }
1633
1634 /**
1635 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1636 *
1637 * @param LinkTarget $linkTarget Message page title
1638 * @param Content|null $content New content for edit/create, null on deletion
1639 * @since 1.29
1640 */
1641 public function updateMessageOverride( LinkTarget $linkTarget, ?Content $content = null ) {
1642 // treat null as not existing
1643 $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1644
1645 $this->replace( $linkTarget->getDBkey(), $msgText );
1646
1647 if ( $this->contLangConverter->hasVariants() ) {
1648 $this->contLangConverter->updateConversionTable( $linkTarget );
1649 }
1650 }
1651
1652 /**
1653 * @param string $code Language code
1654 * @return string WAN cache key usable as a "check key" against language page edits
1655 */
1656 public function getCheckKey( $code ) {
1657 return $this->wanCache->makeKey( 'messages', $code );
1658 }
1659
1660 /**
1661 * @param Content|null $content Content or null if the message page does not exist
1662 * @return string|false|null Returns false if $content is null and null on error
1663 */
1664 private function getMessageTextFromContent( ?Content $content = null ) {
1665 // @TODO: could skip pseudo-messages like js/css here, based on content model
1666 if ( $content && $content->isRedirect() ) {
1667 // Treat redirects as not existing (T376398)
1668 $msgText = false;
1669 } elseif ( $content ) {
1670 // Message page exists...
1671 // XXX: Is this the right way to turn a Content object into a message?
1672 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1673 // CssContent.
1674 $msgText = $content->getWikitextForTransclusion();
1675 if ( $msgText === false || $msgText === null ) {
1676 // This might be due to some kind of misconfiguration...
1677 $msgText = null;
1678 $this->logger->warning(
1679 __METHOD__ . ": message content doesn't provide wikitext "
1680 . "(content model: " . $content->getModel() . ")" );
1681 }
1682 } else {
1683 // Message page does not exist...
1684 $msgText = false;
1685 }
1686
1687 return $msgText;
1688 }
1689
1690 /**
1691 * @param string $hash Hash for this version of the entire key/value overrides map
1692 * @param string $title Message cache key with the initial uppercase letter
1693 * @return string
1694 */
1695 private function bigMessageCacheKey( $hash, $title ) {
1696 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1697 }
1698 }