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