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