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