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