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