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