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