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