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