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