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