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