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