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