Merge "Move section ID fallbacks into headers themselves"
[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 = $this->srvCache->makeKey( __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 = $this->srvCache->makeKey( __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 int $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 = $this->clusterCache->makeKey( '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 int $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 = $this->clusterCache->makeKey( '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 = $this->clusterCache->makeKey( '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 int $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 // (T164666) The query here performs really poorly on WMF's
468 // contributions replicas. We don't have a way to say "any group except
469 // contributions", so for the moment let's specify 'api'.
470 // @todo: Get rid of this hack.
471 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
472
473 $cache = [];
474
475 # Common conditions
476 $conds = [
477 'page_is_redirect' => 0,
478 'page_namespace' => NS_MEDIAWIKI,
479 ];
480
481 $mostused = [];
482 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
483 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
484 $this->load( $wgLanguageCode );
485 }
486 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
487 foreach ( $mostused as $key => $value ) {
488 $mostused[$key] = "$value/$code";
489 }
490 }
491
492 if ( count( $mostused ) ) {
493 $conds['page_title'] = $mostused;
494 } elseif ( $code !== $wgLanguageCode ) {
495 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
496 } else {
497 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
498 # other than language code.
499 $conds[] = 'page_title NOT' .
500 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
501 }
502
503 # Conditions to fetch oversized pages to ignore them
504 $bigConds = $conds;
505 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
506
507 # Load titles for all oversized pages in the MediaWiki namespace
508 $res = $dbr->select(
509 'page',
510 [ 'page_title', 'page_latest' ],
511 $bigConds,
512 __METHOD__ . "($code)-big"
513 );
514 foreach ( $res as $row ) {
515 $cache[$row->page_title] = '!TOO BIG';
516 // At least include revision ID so page changes are reflected in the hash
517 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
518 }
519
520 # Conditions to load the remaining pages with their contents
521 $smallConds = $conds;
522 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
523
524 $res = $dbr->select(
525 [ 'page', 'revision', 'text' ],
526 [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
527 $smallConds,
528 __METHOD__ . "($code)-small",
529 [],
530 [
531 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
532 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
533 ]
534 );
535
536 foreach ( $res as $row ) {
537 $text = Revision::getRevisionText( $row );
538 if ( $text === false ) {
539 // Failed to fetch data; possible ES errors?
540 // Store a marker to fetch on-demand as a workaround...
541 // TODO Use a differnt marker
542 $entry = '!TOO BIG';
543 wfDebugLog(
544 'MessageCache',
545 __METHOD__
546 . ": failed to load message page text for {$row->page_title} ($code)"
547 );
548 } else {
549 $entry = ' ' . $text;
550 }
551 $cache[$row->page_title] = $entry;
552 }
553
554 $cache['VERSION'] = MSG_CACHE_VERSION;
555 ksort( $cache );
556
557 # Hash for validating local cache (APC). No need to take into account
558 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
559 # stored and fetched from memcache.
560 $cache['HASH'] = md5( serialize( $cache ) );
561 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
562
563 return $cache;
564 }
565
566 /**
567 * Updates cache as necessary when message page is changed
568 *
569 * @param string $title Message cache key with initial uppercase letter
570 * @param string|bool $text New contents of the page (false if deleted)
571 */
572 public function replace( $title, $text ) {
573 global $wgLanguageCode;
574
575 if ( $this->mDisable ) {
576 return;
577 }
578
579 list( $msg, $code ) = $this->figureMessage( $title );
580 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
581 // Content language overrides do not use the /<code> suffix
582 return;
583 }
584
585 // (a) Update the process cache with the new message text
586 if ( $text === false ) {
587 // Page deleted
588 $this->mCache[$code][$title] = '!NONEXISTENT';
589 } else {
590 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
591 $this->mCache[$code][$title] = ' ' . $text;
592 }
593
594 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
595 DeferredUpdates::addCallableUpdate(
596 function () use ( $title, $msg, $code ) {
597 global $wgContLang, $wgMaxMsgCacheEntrySize;
598 // Allow one caller at a time to avoid race conditions
599 $scopedLock = $this->getReentrantScopedLock(
600 $this->clusterCache->makeKey( 'messages', $code )
601 );
602 if ( !$scopedLock ) {
603 LoggerFactory::getInstance( 'MessageCache' )->error(
604 __METHOD__ . ': could not acquire lock to update {title} ({code})',
605 [ 'title' => $title, 'code' => $code ] );
606 return;
607 }
608 // Load the messages from the master DB to avoid race conditions
609 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
610 $this->mCache[$code] = $cache;
611 // Load the process cache values and set the per-title cache keys
612 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
613 $page->loadPageData( $page::READ_LATEST );
614 $text = $this->getMessageTextFromContent( $page->getContent() );
615 // Check if an individual cache key should exist and update cache accordingly
616 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
617 $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
618 $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
619 }
620 // Mark this cache as definitely being "latest" (non-volatile) so
621 // load() calls do try to refresh the cache with replica DB data
622 $this->mCache[$code]['LATEST'] = time();
623 // Pre-emptively update the local datacenter cache so things like edit filter and
624 // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
625 // The datacenter handling replace() calls should be the same one handling edits
626 // as they require HTTP POST.
627 $this->saveToCaches( $this->mCache[$code], 'all', $code );
628 // Release the lock now that the cache is saved
629 ScopedCallback::consume( $scopedLock );
630
631 // Relay the purge. Touching this check key expires cache contents
632 // and local cache (APC) validation hash across all datacenters.
633 $this->wanCache->touchCheckKey( $this->wanCache->makeKey( 'messages', $code ) );
634 // Also delete cached sidebar... just in case it is affected
635 // @TODO: shouldn't this be $code === $wgLanguageCode?
636 if ( $code === 'en' ) {
637 // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
638 $codes = array_keys( Language::fetchLanguageNames() );
639 } else {
640 // Purge only the sidebar for this language
641 $codes = [ $code ];
642 }
643 foreach ( $codes as $code ) {
644 $this->wanCache->delete( $this->wanCache->makeKey( 'sidebar', $code ) );
645 }
646
647 // Purge the message in the message blob store
648 $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
649 $blobStore = $resourceloader->getMessageBlobStore();
650 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
651
652 Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
653 },
654 DeferredUpdates::PRESEND
655 );
656 }
657
658 /**
659 * Is the given cache array expired due to time passing or a version change?
660 *
661 * @param array $cache
662 * @return bool
663 */
664 protected function isCacheExpired( $cache ) {
665 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
666 return true;
667 }
668 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
669 return true;
670 }
671 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
672 return true;
673 }
674
675 return false;
676 }
677
678 /**
679 * Shortcut to update caches.
680 *
681 * @param array $cache Cached messages with a version.
682 * @param string $dest Either "local-only" to save to local caches only
683 * or "all" to save to all caches.
684 * @param string|bool $code Language code (default: false)
685 * @return bool
686 */
687 protected function saveToCaches( array $cache, $dest, $code = false ) {
688 if ( $dest === 'all' ) {
689 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
690 $success = $this->clusterCache->set( $cacheKey, $cache );
691 $this->setValidationHash( $code, $cache );
692 } else {
693 $success = true;
694 }
695
696 $this->saveToLocalCache( $code, $cache );
697
698 return $success;
699 }
700
701 /**
702 * Get the md5 used to validate the local APC cache
703 *
704 * @param string $code
705 * @return array (hash or false, bool expiry/volatility status)
706 */
707 protected function getValidationHash( $code ) {
708 $curTTL = null;
709 $value = $this->wanCache->get(
710 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
711 $curTTL,
712 [ $this->wanCache->makeKey( 'messages', $code ) ]
713 );
714
715 if ( $value ) {
716 $hash = $value['hash'];
717 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
718 // Cache was recently updated via replace() and should be up-to-date.
719 // That method is only called in the primary datacenter and uses FOR_UPDATE.
720 // Also, it is unlikely that the current datacenter is *now* secondary one.
721 $expired = false;
722 } else {
723 // See if the "check" key was bumped after the hash was generated
724 $expired = ( $curTTL < 0 );
725 }
726 } else {
727 // No hash found at all; cache must regenerate to be safe
728 $hash = false;
729 $expired = true;
730 }
731
732 return [ $hash, $expired ];
733 }
734
735 /**
736 * Set the md5 used to validate the local disk cache
737 *
738 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
739 * be treated as "volatile" by getValidationHash() for the next few seconds.
740 * This is triggered when $cache is generated using FOR_UPDATE mode.
741 *
742 * @param string $code
743 * @param array $cache Cached messages with a version
744 */
745 protected function setValidationHash( $code, array $cache ) {
746 $this->wanCache->set(
747 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
748 [
749 'hash' => $cache['HASH'],
750 'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
751 ],
752 WANObjectCache::TTL_INDEFINITE
753 );
754 }
755
756 /**
757 * @param string $key A language message cache key that stores blobs
758 * @param int $timeout Wait timeout in seconds
759 * @return null|ScopedCallback
760 */
761 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
762 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
763 }
764
765 /**
766 * Get a message from either the content language or the user language.
767 *
768 * First, assemble a list of languages to attempt getting the message from. This
769 * chain begins with the requested language and its fallbacks and then continues with
770 * the content language and its fallbacks. For each language in the chain, the following
771 * process will occur (in this order):
772 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
773 * Note: for the content language, there is no /lang subpage.
774 * 2. Fetch from the static CDB cache.
775 * 3. If available, check the database for fallback language overrides.
776 *
777 * This process provides a number of guarantees. When changing this code, make sure all
778 * of these guarantees are preserved.
779 * * If the requested language is *not* the content language, then the CDB cache for that
780 * specific language will take precedence over the root database page ([[MW:msg]]).
781 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
782 * the message is available *anywhere* in the language for which it is a fallback.
783 *
784 * @param string $key The message key
785 * @param bool $useDB If true, look for the message in the DB, false
786 * to use only the compiled l10n cache.
787 * @param bool|string|object $langcode Code of the language to get the message for.
788 * - If string and a valid code, will create a standard language object
789 * - If string but not a valid code, will create a basic language object
790 * - If boolean and false, create object from the current users language
791 * - If boolean and true, create object from the wikis content language
792 * - If language object, use it as given
793 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
794 *
795 * @throws MWException When given an invalid key
796 * @return string|bool False if the message doesn't exist, otherwise the
797 * message (which can be empty)
798 */
799 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
800 if ( is_int( $key ) ) {
801 // Fix numerical strings that somehow become ints
802 // on their way here
803 $key = (string)$key;
804 } elseif ( !is_string( $key ) ) {
805 throw new MWException( 'Non-string key given' );
806 } elseif ( $key === '' ) {
807 // Shortcut: the empty key is always missing
808 return false;
809 }
810
811 // For full keys, get the language code from the key
812 $pos = strrpos( $key, '/' );
813 if ( $isFullKey && $pos !== false ) {
814 $langcode = substr( $key, $pos + 1 );
815 $key = substr( $key, 0, $pos );
816 }
817
818 // Normalise title-case input (with some inlining)
819 $lckey = self::normalizeKey( $key );
820
821 Hooks::run( 'MessageCache::get', [ &$lckey ] );
822
823 // Loop through each language in the fallback list until we find something useful
824 $lang = wfGetLangObj( $langcode );
825 $message = $this->getMessageFromFallbackChain(
826 $lang,
827 $lckey,
828 !$this->mDisable && $useDB
829 );
830
831 // If we still have no message, maybe the key was in fact a full key so try that
832 if ( $message === false ) {
833 $parts = explode( '/', $lckey );
834 // We may get calls for things that are http-urls from sidebar
835 // Let's not load nonexistent languages for those
836 // They usually have more than one slash.
837 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
838 $message = Language::getMessageFor( $parts[0], $parts[1] );
839 if ( $message === null ) {
840 $message = false;
841 }
842 }
843 }
844
845 // Post-processing if the message exists
846 if ( $message !== false ) {
847 // Fix whitespace
848 $message = str_replace(
849 [
850 # Fix for trailing whitespace, removed by textarea
851 '&#32;',
852 # Fix for NBSP, converted to space by firefox
853 '&nbsp;',
854 '&#160;',
855 '&shy;'
856 ],
857 [
858 ' ',
859 "\xc2\xa0",
860 "\xc2\xa0",
861 "\xc2\xad"
862 ],
863 $message
864 );
865 }
866
867 return $message;
868 }
869
870 /**
871 * Given a language, try and fetch messages from that language.
872 *
873 * Will also consider fallbacks of that language, the site language, and fallbacks for
874 * the site language.
875 *
876 * @see MessageCache::get
877 * @param Language|StubObject $lang Preferred language
878 * @param string $lckey Lowercase key for the message (as for localisation cache)
879 * @param bool $useDB Whether to include messages from the wiki database
880 * @return string|bool The message, or false if not found
881 */
882 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
883 global $wgContLang;
884
885 $alreadyTried = [];
886
887 // First try the requested language.
888 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
889 if ( $message !== false ) {
890 return $message;
891 }
892
893 // Now try checking the site language.
894 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
895 return $message;
896 }
897
898 /**
899 * Given a language, try and fetch messages from that language and its fallbacks.
900 *
901 * @see MessageCache::get
902 * @param Language|StubObject $lang Preferred language
903 * @param string $lckey Lowercase key for the message (as for localisation cache)
904 * @param bool $useDB Whether to include messages from the wiki database
905 * @param bool[] $alreadyTried Contains true for each language that has been tried already
906 * @return string|bool The message, or false if not found
907 */
908 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
909 global $wgContLang;
910
911 $langcode = $lang->getCode();
912
913 // Try checking the database for the requested language
914 if ( $useDB ) {
915 $uckey = $wgContLang->ucfirst( $lckey );
916
917 if ( !isset( $alreadyTried[ $langcode ] ) ) {
918 $message = $this->getMsgFromNamespace(
919 $this->getMessagePageName( $langcode, $uckey ),
920 $langcode
921 );
922
923 if ( $message !== false ) {
924 return $message;
925 }
926 $alreadyTried[ $langcode ] = true;
927 }
928 } else {
929 $uckey = null;
930 }
931
932 // Check the CDB cache
933 $message = $lang->getMessage( $lckey );
934 if ( $message !== null ) {
935 return $message;
936 }
937
938 // Try checking the database for all of the fallback languages
939 if ( $useDB ) {
940 $fallbackChain = Language::getFallbacksFor( $langcode );
941
942 foreach ( $fallbackChain as $code ) {
943 if ( isset( $alreadyTried[ $code ] ) ) {
944 continue;
945 }
946
947 $message = $this->getMsgFromNamespace(
948 $this->getMessagePageName( $code, $uckey ), $code );
949
950 if ( $message !== false ) {
951 return $message;
952 }
953 $alreadyTried[ $code ] = true;
954 }
955 }
956
957 return false;
958 }
959
960 /**
961 * Get the message page name for a given language
962 *
963 * @param string $langcode
964 * @param string $uckey Uppercase key for the message
965 * @return string The page name
966 */
967 private function getMessagePageName( $langcode, $uckey ) {
968 global $wgLanguageCode;
969
970 if ( $langcode === $wgLanguageCode ) {
971 // Messages created in the content language will not have the /lang extension
972 return $uckey;
973 } else {
974 return "$uckey/$langcode";
975 }
976 }
977
978 /**
979 * Get a message from the MediaWiki namespace, with caching. The key must
980 * first be converted to two-part lang/msg form if necessary.
981 *
982 * Unlike self::get(), this function doesn't resolve fallback chains, and
983 * some callers require this behavior. LanguageConverter::parseCachedTable()
984 * and self::get() are some examples in core.
985 *
986 * @param string $title Message cache key with initial uppercase letter
987 * @param string $code Code denoting the language to try
988 * @return string|bool The message, or false if it does not exist or on error
989 */
990 public function getMsgFromNamespace( $title, $code ) {
991 $this->load( $code );
992
993 if ( isset( $this->mCache[$code][$title] ) ) {
994 $entry = $this->mCache[$code][$title];
995 if ( substr( $entry, 0, 1 ) === ' ' ) {
996 // The message exists, so make sure a string is returned.
997 return (string)substr( $entry, 1 );
998 } elseif ( $entry === '!NONEXISTENT' ) {
999 return false;
1000 } elseif ( $entry === '!TOO BIG' ) {
1001 // Fall through and try invididual message cache below
1002 }
1003 } else {
1004 // XXX: This is not cached in process cache, should it?
1005 $message = false;
1006 Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1007 if ( $message !== false ) {
1008 return $message;
1009 }
1010
1011 return false;
1012 }
1013
1014 // Individual message cache key
1015 $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
1016
1017 if ( $this->mCacheVolatile[$code] ) {
1018 $entry = false;
1019 // Make sure that individual keys respect the WAN cache holdoff period too
1020 LoggerFactory::getInstance( 'MessageCache' )->debug(
1021 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1022 [ 'titleKey' => $titleKey, 'code' => $code ] );
1023 } else {
1024 // Try the individual message cache
1025 $entry = $this->wanCache->get( $titleKey );
1026 }
1027
1028 if ( $entry !== false ) {
1029 if ( substr( $entry, 0, 1 ) === ' ' ) {
1030 $this->mCache[$code][$title] = $entry;
1031 // The message exists, so make sure a string is returned
1032 return (string)substr( $entry, 1 );
1033 } elseif ( $entry === '!NONEXISTENT' ) {
1034 $this->mCache[$code][$title] = '!NONEXISTENT';
1035
1036 return false;
1037 } else {
1038 // Corrupt/obsolete entry, delete it
1039 $this->wanCache->delete( $titleKey );
1040 }
1041 }
1042
1043 // Try loading the message from the database
1044 $dbr = wfGetDB( DB_REPLICA );
1045 $cacheOpts = Database::getCacheSetOptions( $dbr );
1046 // Use newKnownCurrent() to avoid querying revision/user tables
1047 $titleObj = Title::makeTitle( NS_MEDIAWIKI, $title );
1048 if ( $titleObj->getLatestRevID() ) {
1049 $revision = Revision::newKnownCurrent(
1050 $dbr,
1051 $titleObj->getArticleID(),
1052 $titleObj->getLatestRevID()
1053 );
1054 } else {
1055 $revision = false;
1056 }
1057
1058 if ( $revision ) {
1059 $content = $revision->getContent();
1060 if ( $content ) {
1061 $message = $this->getMessageTextFromContent( $content );
1062 if ( is_string( $message ) ) {
1063 $this->mCache[$code][$title] = ' ' . $message;
1064 $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry, $cacheOpts );
1065 }
1066 } else {
1067 // A possibly temporary loading failure
1068 LoggerFactory::getInstance( 'MessageCache' )->warning(
1069 __METHOD__ . ': failed to load message page text for \'{titleKey}\'',
1070 [ 'titleKey' => $titleKey, 'code' => $code ] );
1071 $message = null; // no negative caching
1072 }
1073 } else {
1074 $message = false; // negative caching
1075 }
1076
1077 if ( $message === false ) {
1078 // Negative caching in case a "too big" message is no longer available (deleted)
1079 $this->mCache[$code][$title] = '!NONEXISTENT';
1080 $this->wanCache->set( $titleKey, '!NONEXISTENT', $this->mExpiry, $cacheOpts );
1081 }
1082
1083 return $message;
1084 }
1085
1086 /**
1087 * @param string $message
1088 * @param bool $interface
1089 * @param string $language Language code
1090 * @param Title $title
1091 * @return string
1092 */
1093 function transform( $message, $interface = false, $language = null, $title = null ) {
1094 // Avoid creating parser if nothing to transform
1095 if ( strpos( $message, '{{' ) === false ) {
1096 return $message;
1097 }
1098
1099 if ( $this->mInParser ) {
1100 return $message;
1101 }
1102
1103 $parser = $this->getParser();
1104 if ( $parser ) {
1105 $popts = $this->getParserOptions();
1106 $popts->setInterfaceMessage( $interface );
1107 $popts->setTargetLanguage( $language );
1108
1109 $userlang = $popts->setUserLang( $language );
1110 $this->mInParser = true;
1111 $message = $parser->transformMsg( $message, $popts, $title );
1112 $this->mInParser = false;
1113 $popts->setUserLang( $userlang );
1114 }
1115
1116 return $message;
1117 }
1118
1119 /**
1120 * @return Parser
1121 */
1122 function getParser() {
1123 global $wgParser, $wgParserConf;
1124
1125 if ( !$this->mParser && isset( $wgParser ) ) {
1126 # Do some initialisation so that we don't have to do it twice
1127 $wgParser->firstCallInit();
1128 # Clone it and store it
1129 $class = $wgParserConf['class'];
1130 if ( $class == 'ParserDiffTest' ) {
1131 # Uncloneable
1132 $this->mParser = new $class( $wgParserConf );
1133 } else {
1134 $this->mParser = clone $wgParser;
1135 }
1136 }
1137
1138 return $this->mParser;
1139 }
1140
1141 /**
1142 * @param string $text
1143 * @param Title $title
1144 * @param bool $linestart Whether or not this is at the start of a line
1145 * @param bool $interface Whether this is an interface message
1146 * @param Language|string $language Language code
1147 * @return ParserOutput|string
1148 */
1149 public function parse( $text, $title = null, $linestart = true,
1150 $interface = false, $language = null
1151 ) {
1152 global $wgTitle;
1153
1154 if ( $this->mInParser ) {
1155 return htmlspecialchars( $text );
1156 }
1157
1158 $parser = $this->getParser();
1159 $popts = $this->getParserOptions();
1160 $popts->setInterfaceMessage( $interface );
1161
1162 if ( is_string( $language ) ) {
1163 $language = Language::factory( $language );
1164 }
1165 $popts->setTargetLanguage( $language );
1166
1167 if ( !$title || !$title instanceof Title ) {
1168 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1169 wfGetAllCallers( 6 ) . ' with no title set.' );
1170 $title = $wgTitle;
1171 }
1172 // Sometimes $wgTitle isn't set either...
1173 if ( !$title ) {
1174 # It's not uncommon having a null $wgTitle in scripts. See r80898
1175 # Create a ghost title in such case
1176 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1177 }
1178
1179 $this->mInParser = true;
1180 $res = $parser->parse( $text, $title, $popts, $linestart );
1181 $this->mInParser = false;
1182
1183 return $res;
1184 }
1185
1186 function disable() {
1187 $this->mDisable = true;
1188 }
1189
1190 function enable() {
1191 $this->mDisable = false;
1192 }
1193
1194 /**
1195 * Whether DB/cache usage is disabled for determining messages
1196 *
1197 * If so, this typically indicates either:
1198 * - a) load() failed to find a cached copy nor query the DB
1199 * - b) we are in a special context or error mode that cannot use the DB
1200 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1201 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1202 *
1203 * @return bool
1204 * @since 1.27
1205 */
1206 public function isDisabled() {
1207 return $this->mDisable;
1208 }
1209
1210 /**
1211 * Clear all stored messages. Mainly used after a mass rebuild.
1212 */
1213 function clear() {
1214 $langs = Language::fetchLanguageNames( null, 'mw' );
1215 foreach ( array_keys( $langs ) as $code ) {
1216 # Global and local caches
1217 $this->wanCache->touchCheckKey( $this->wanCache->makeKey( 'messages', $code ) );
1218 }
1219
1220 $this->mLoadedLanguages = [];
1221 }
1222
1223 /**
1224 * @param string $key
1225 * @return array
1226 */
1227 public function figureMessage( $key ) {
1228 global $wgLanguageCode;
1229
1230 $pieces = explode( '/', $key );
1231 if ( count( $pieces ) < 2 ) {
1232 return [ $key, $wgLanguageCode ];
1233 }
1234
1235 $lang = array_pop( $pieces );
1236 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1237 return [ $key, $wgLanguageCode ];
1238 }
1239
1240 $message = implode( '/', $pieces );
1241
1242 return [ $message, $lang ];
1243 }
1244
1245 /**
1246 * Get all message keys stored in the message cache for a given language.
1247 * If $code is the content language code, this will return all message keys
1248 * for which MediaWiki:msgkey exists. If $code is another language code, this
1249 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1250 * @param string $code Language code
1251 * @return array Array of message keys (strings)
1252 */
1253 public function getAllMessageKeys( $code ) {
1254 global $wgContLang;
1255
1256 $this->load( $code );
1257 if ( !isset( $this->mCache[$code] ) ) {
1258 // Apparently load() failed
1259 return null;
1260 }
1261 // Remove administrative keys
1262 $cache = $this->mCache[$code];
1263 unset( $cache['VERSION'] );
1264 unset( $cache['EXPIRY'] );
1265 unset( $cache['EXCESSIVE'] );
1266 // Remove any !NONEXISTENT keys
1267 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1268
1269 // Keys may appear with a capital first letter. lcfirst them.
1270 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1271 }
1272
1273 /**
1274 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1275 *
1276 * @param Title $title Message page title
1277 * @param Content|null $content New content for edit/create, null on deletion
1278 * @since 1.29
1279 */
1280 public function updateMessageOverride( Title $title, Content $content = null ) {
1281 global $wgContLang;
1282
1283 $msgText = $this->getMessageTextFromContent( $content );
1284 if ( $msgText === null ) {
1285 $msgText = false; // treat as not existing
1286 }
1287
1288 $this->replace( $title->getDBkey(), $msgText );
1289
1290 if ( $wgContLang->hasVariants() ) {
1291 $wgContLang->updateConversionTable( $title );
1292 }
1293 }
1294
1295 /**
1296 * @param Content|null $content Content or null if the message page does not exist
1297 * @return string|bool|null Returns false if $content is null and null on error
1298 */
1299 private function getMessageTextFromContent( Content $content = null ) {
1300 // @TODO: could skip pseudo-messages like js/css here, based on content model
1301 if ( $content ) {
1302 // Message page exists...
1303 // XXX: Is this the right way to turn a Content object into a message?
1304 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1305 // CssContent. MessageContent is *not* used for storing messages, it's
1306 // only used for wrapping them when needed.
1307 $msgText = $content->getWikitextForTransclusion();
1308 if ( $msgText === false || $msgText === null ) {
1309 // This might be due to some kind of misconfiguration...
1310 $msgText = null;
1311 LoggerFactory::getInstance( 'MessageCache' )->warning(
1312 __METHOD__ . ": message content doesn't provide wikitext "
1313 . "(content model: " . $content->getModel() . ")" );
1314 }
1315 } else {
1316 // Message page does not exist...
1317 $msgText = false;
1318 }
1319
1320 return $msgText;
1321 }
1322
1323 /**
1324 * @param string $hash Hash for this version of the entire key/value overrides map
1325 * @param string $title Message cache key with initial uppercase letter
1326 * @return string
1327 */
1328 private function bigMessageCacheKey( $hash, $title ) {
1329 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1330 }
1331 }