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