Don't check namespace in SpecialWantedtemplates
[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 MediaWiki\suppressWarnings();
171 $file = fopen( $filename, 'r' );
172 MediaWiki\restoreWarnings();
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 MediaWiki\suppressWarnings();
208 $file = fopen( $filename, 'w' );
209 MediaWiki\restoreWarnings();
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 MediaWiki\suppressWarnings();
220 chmod( $filename, 0666 );
221 MediaWiki\restoreWarnings();
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, $wgLanguageCode;
521
522 if ( $this->mDisable ) {
523 return;
524 }
525
526 list( $msg, $code ) = $this->figureMessage( $title );
527 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
528 # Content language overrides do not use the /<code> suffix
529 return;
530 }
531
532 $cacheKey = wfMemcKey( 'messages', $code );
533 $this->lock( $cacheKey );
534 $this->load( $code, self::FOR_UPDATE );
535
536 $titleKey = wfMemcKey( 'messages', 'individual', $title );
537
538 if ( $text === false ) {
539 # Article was deleted
540 $this->mCache[$code][$title] = '!NONEXISTENT';
541 $this->mMemc->delete( $titleKey );
542 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
543 # Check for size
544 $this->mCache[$code][$title] = '!TOO BIG';
545 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
546 } else {
547 $this->mCache[$code][$title] = ' ' . $text;
548 $this->mMemc->delete( $titleKey );
549 }
550
551 # Update caches
552 $this->saveToCaches( $this->mCache[$code], 'all', $code );
553 $this->unlock( $cacheKey );
554
555 // Also delete cached sidebar... just in case it is affected
556 $codes = array( $code );
557 if ( $code === 'en' ) {
558 // Delete all sidebars, like for example on action=purge on the
559 // sidebar messages
560 $codes = array_keys( Language::fetchLanguageNames() );
561 }
562
563 $cache = ObjectCache::getMainWANInstance();
564 foreach ( $codes as $code ) {
565 $sidebarKey = wfMemcKey( 'sidebar', $code );
566 $cache->delete( $sidebarKey, 5 );
567 }
568
569 // Update the message in the message blob store
570 $blobStore = new MessageBlobStore();
571 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
572
573 Hooks::run( 'MessageCacheReplace', array( $title, $text ) );
574 }
575
576 /**
577 * Is the given cache array expired due to time passing or a version change?
578 *
579 * @param array $cache
580 * @return bool
581 */
582 protected function isCacheExpired( $cache ) {
583 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
584 return true;
585 }
586 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
587 return true;
588 }
589 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
590 return true;
591 }
592
593 return false;
594 }
595
596 /**
597 * Shortcut to update caches.
598 *
599 * @param array $cache Cached messages with a version.
600 * @param string $dest Either "local-only" to save to local caches only
601 * or "all" to save to all caches.
602 * @param string|bool $code Language code (default: false)
603 * @return bool
604 */
605 protected function saveToCaches( $cache, $dest, $code = false ) {
606 global $wgUseLocalMessageCache;
607
608 $cacheKey = wfMemcKey( 'messages', $code );
609
610 if ( $dest === 'all' ) {
611 $success = $this->mMemc->set( $cacheKey, $cache );
612 } else {
613 $success = true;
614 }
615
616 # Save to local cache
617 if ( $wgUseLocalMessageCache ) {
618 $serialized = serialize( $cache );
619 $hash = md5( $serialized );
620 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
621 $this->saveToLocal( $serialized, $hash, $code );
622 }
623
624 return $success;
625 }
626
627 /**
628 * Represents a write lock on the messages key.
629 *
630 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
631 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
632 *
633 * @param string $key
634 * @return bool Success
635 */
636 function lock( $key ) {
637 $lockKey = $key . ':lock';
638 $acquired = false;
639 $testDone = false;
640 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
641 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
642 if ( $acquired ) {
643 break;
644 }
645
646 # Fail fast if memcached is totally down
647 if ( !$testDone ) {
648 $testDone = true;
649 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
650 break;
651 }
652 }
653 sleep( 1 );
654 }
655
656 return $acquired;
657 }
658
659 function unlock( $key ) {
660 $lockKey = $key . ':lock';
661 $this->mMemc->delete( $lockKey );
662 }
663
664 /**
665 * Get a message from either the content language or the user language.
666 *
667 * First, assemble a list of languages to attempt getting the message from. This
668 * chain begins with the requested language and its fallbacks and then continues with
669 * the content language and its fallbacks. For each language in the chain, the following
670 * process will occur (in this order):
671 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
672 * Note: for the content language, there is no /lang subpage.
673 * 2. Fetch from the static CDB cache.
674 * 3. If available, check the database for fallback language overrides.
675 *
676 * This process provides a number of guarantees. When changing this code, make sure all
677 * of these guarantees are preserved.
678 * * If the requested language is *not* the content language, then the CDB cache for that
679 * specific language will take precedence over the root database page ([[MW:msg]]).
680 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
681 * the message is available *anywhere* in the language for which it is a fallback.
682 *
683 * @param string $key The message key
684 * @param bool $useDB If true, look for the message in the DB, false
685 * to use only the compiled l10n cache.
686 * @param bool|string|object $langcode Code of the language to get the message for.
687 * - If string and a valid code, will create a standard language object
688 * - If string but not a valid code, will create a basic language object
689 * - If boolean and false, create object from the current users language
690 * - If boolean and true, create object from the wikis content language
691 * - If language object, use it as given
692 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
693 *
694 * @throws MWException When given an invalid key
695 * @return string|bool False if the message doesn't exist, otherwise the
696 * message (which can be empty)
697 */
698 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
699 global $wgContLang;
700
701 if ( is_int( $key ) ) {
702 // Fix numerical strings that somehow become ints
703 // on their way here
704 $key = (string)$key;
705 } elseif ( !is_string( $key ) ) {
706 throw new MWException( 'Non-string key given' );
707 } elseif ( $key === '' ) {
708 // Shortcut: the empty key is always missing
709 return false;
710 }
711
712 // For full keys, get the language code from the key
713 $pos = strrpos( $key, '/' );
714 if ( $isFullKey && $pos !== false ) {
715 $langcode = substr( $key, $pos + 1 );
716 $key = substr( $key, 0, $pos );
717 }
718
719 // Normalise title-case input (with some inlining)
720 $lckey = strtr( $key, ' ', '_' );
721 if ( ord( $lckey ) < 128 ) {
722 $lckey[0] = strtolower( $lckey[0] );
723 } else {
724 $lckey = $wgContLang->lcfirst( $lckey );
725 }
726
727 Hooks::run( 'MessageCache::get', array( &$lckey ) );
728
729 if ( ord( $lckey ) < 128 ) {
730 $uckey = ucfirst( $lckey );
731 } else {
732 $uckey = $wgContLang->ucfirst( $lckey );
733 }
734
735 // Loop through each language in the fallback list until we find something useful
736 $lang = wfGetLangObj( $langcode );
737 $message = $this->getMessageFromFallbackChain(
738 $lang,
739 $lckey,
740 $uckey,
741 !$this->mDisable && $useDB
742 );
743
744 // If we still have no message, maybe the key was in fact a full key so try that
745 if ( $message === false ) {
746 $parts = explode( '/', $lckey );
747 // We may get calls for things that are http-urls from sidebar
748 // Let's not load nonexistent languages for those
749 // They usually have more than one slash.
750 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
751 $message = Language::getMessageFor( $parts[0], $parts[1] );
752 if ( $message === null ) {
753 $message = false;
754 }
755 }
756 }
757
758 // Post-processing if the message exists
759 if ( $message !== false ) {
760 // Fix whitespace
761 $message = str_replace(
762 array(
763 # Fix for trailing whitespace, removed by textarea
764 '&#32;',
765 # Fix for NBSP, converted to space by firefox
766 '&nbsp;',
767 '&#160;',
768 ),
769 array(
770 ' ',
771 "\xc2\xa0",
772 "\xc2\xa0"
773 ),
774 $message
775 );
776 }
777
778 return $message;
779 }
780
781 /**
782 * Given a language, try and fetch a message from that language, then the
783 * fallbacks of that language, then the site language, then the fallbacks for the
784 * site language.
785 *
786 * @param Language $lang Requested language
787 * @param string $lckey Lowercase key for the message
788 * @param string $uckey Uppercase key for the message
789 * @param bool $useDB Whether to use the database
790 *
791 * @see MessageCache::get
792 * @return string|bool The message, or false if not found
793 */
794 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
795 global $wgLanguageCode, $wgContLang;
796
797 $langcode = $lang->getCode();
798 $message = false;
799
800 // First try the requested language.
801 if ( $useDB ) {
802 if ( $langcode === $wgLanguageCode ) {
803 // Messages created in the content language will not have the /lang extension
804 $message = $this->getMsgFromNamespace( $uckey, $langcode );
805 } else {
806 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
807 }
808 }
809
810 if ( $message !== false ) {
811 return $message;
812 }
813
814 // Check the CDB cache
815 $message = $lang->getMessage( $lckey );
816 if ( $message !== null ) {
817 return $message;
818 }
819
820 list( $fallbackChain, $siteFallbackChain ) =
821 Language::getFallbacksIncludingSiteLanguage( $langcode );
822
823 // Next try checking the database for all of the fallback languages of the requested language.
824 if ( $useDB ) {
825 foreach ( $fallbackChain as $code ) {
826 if ( $code === $wgLanguageCode ) {
827 // Messages created in the content language will not have the /lang extension
828 $message = $this->getMsgFromNamespace( $uckey, $code );
829 } else {
830 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
831 }
832
833 if ( $message !== false ) {
834 // Found the message.
835 return $message;
836 }
837 }
838 }
839
840 // Now try checking the site language.
841 if ( $useDB ) {
842 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
843 if ( $message !== false ) {
844 return $message;
845 }
846 }
847
848 $message = $wgContLang->getMessage( $lckey );
849 if ( $message !== null ) {
850 return $message;
851 }
852
853 // Finally try the DB for the site language's fallbacks.
854 if ( $useDB ) {
855 foreach ( $siteFallbackChain as $code ) {
856 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
857 if ( $message === false && $code === $wgLanguageCode ) {
858 // Messages created in the content language will not have the /lang extension
859 $message = $this->getMsgFromNamespace( $uckey, $code );
860 }
861
862 if ( $message !== false ) {
863 // Found the message.
864 return $message;
865 }
866 }
867 }
868
869 return false;
870 }
871
872 /**
873 * Get a message from the MediaWiki namespace, with caching. The key must
874 * first be converted to two-part lang/msg form if necessary.
875 *
876 * Unlike self::get(), this function doesn't resolve fallback chains, and
877 * some callers require this behavior. LanguageConverter::parseCachedTable()
878 * and self::get() are some examples in core.
879 *
880 * @param string $title Message cache key with initial uppercase letter.
881 * @param string $code Code denoting the language to try.
882 * @return string|bool The message, or false if it does not exist or on error
883 */
884 function getMsgFromNamespace( $title, $code ) {
885 $this->load( $code );
886 if ( isset( $this->mCache[$code][$title] ) ) {
887 $entry = $this->mCache[$code][$title];
888 if ( substr( $entry, 0, 1 ) === ' ' ) {
889 // The message exists, so make sure a string
890 // is returned.
891 return (string)substr( $entry, 1 );
892 } elseif ( $entry === '!NONEXISTENT' ) {
893 return false;
894 } elseif ( $entry === '!TOO BIG' ) {
895 // Fall through and try invididual message cache below
896 }
897 } else {
898 // XXX: This is not cached in process cache, should it?
899 $message = false;
900 Hooks::run( 'MessagesPreLoad', array( $title, &$message ) );
901 if ( $message !== false ) {
902 return $message;
903 }
904
905 return false;
906 }
907
908 # Try the individual message cache
909 $titleKey = wfMemcKey( 'messages', 'individual', $title );
910 $entry = $this->mMemc->get( $titleKey );
911 if ( $entry ) {
912 if ( substr( $entry, 0, 1 ) === ' ' ) {
913 $this->mCache[$code][$title] = $entry;
914
915 // The message exists, so make sure a string
916 // is returned.
917 return (string)substr( $entry, 1 );
918 } elseif ( $entry === '!NONEXISTENT' ) {
919 $this->mCache[$code][$title] = '!NONEXISTENT';
920
921 return false;
922 } else {
923 # Corrupt/obsolete entry, delete it
924 $this->mMemc->delete( $titleKey );
925 }
926 }
927
928 # Try loading it from the database
929 $revision = Revision::newFromTitle(
930 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
931 );
932 if ( $revision ) {
933 $content = $revision->getContent();
934 if ( !$content ) {
935 // A possibly temporary loading failure.
936 wfDebugLog(
937 'MessageCache',
938 __METHOD__ . ": failed to load message page text for {$title} ($code)"
939 );
940 $message = null; // no negative caching
941 } else {
942 // XXX: Is this the right way to turn a Content object into a message?
943 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
944 // CssContent. MessageContent is *not* used for storing messages, it's
945 // only used for wrapping them when needed.
946 $message = $content->getWikitextForTransclusion();
947
948 if ( $message === false || $message === null ) {
949 wfDebugLog(
950 'MessageCache',
951 __METHOD__ . ": message content doesn't provide wikitext "
952 . "(content model: " . $content->getContentHandler() . ")"
953 );
954
955 $message = false; // negative caching
956 } else {
957 $this->mCache[$code][$title] = ' ' . $message;
958 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
959 }
960 }
961 } else {
962 $message = false; // negative caching
963 }
964
965 if ( $message === false ) { // negative caching
966 $this->mCache[$code][$title] = '!NONEXISTENT';
967 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
968 }
969
970 return $message;
971 }
972
973 /**
974 * @param string $message
975 * @param bool $interface
976 * @param string $language Language code
977 * @param Title $title
978 * @return string
979 */
980 function transform( $message, $interface = false, $language = null, $title = null ) {
981 // Avoid creating parser if nothing to transform
982 if ( strpos( $message, '{{' ) === false ) {
983 return $message;
984 }
985
986 if ( $this->mInParser ) {
987 return $message;
988 }
989
990 $parser = $this->getParser();
991 if ( $parser ) {
992 $popts = $this->getParserOptions();
993 $popts->setInterfaceMessage( $interface );
994 $popts->setTargetLanguage( $language );
995
996 $userlang = $popts->setUserLang( $language );
997 $this->mInParser = true;
998 $message = $parser->transformMsg( $message, $popts, $title );
999 $this->mInParser = false;
1000 $popts->setUserLang( $userlang );
1001 }
1002
1003 return $message;
1004 }
1005
1006 /**
1007 * @return Parser
1008 */
1009 function getParser() {
1010 global $wgParser, $wgParserConf;
1011 if ( !$this->mParser && isset( $wgParser ) ) {
1012 # Do some initialisation so that we don't have to do it twice
1013 $wgParser->firstCallInit();
1014 # Clone it and store it
1015 $class = $wgParserConf['class'];
1016 if ( $class == 'ParserDiffTest' ) {
1017 # Uncloneable
1018 $this->mParser = new $class( $wgParserConf );
1019 } else {
1020 $this->mParser = clone $wgParser;
1021 }
1022 }
1023
1024 return $this->mParser;
1025 }
1026
1027 /**
1028 * @param string $text
1029 * @param Title $title
1030 * @param bool $linestart Whether or not this is at the start of a line
1031 * @param bool $interface Whether this is an interface message
1032 * @param string $language Language code
1033 * @return ParserOutput|string
1034 */
1035 public function parse( $text, $title = null, $linestart = true,
1036 $interface = false, $language = null
1037 ) {
1038 if ( $this->mInParser ) {
1039 return htmlspecialchars( $text );
1040 }
1041
1042 $parser = $this->getParser();
1043 $popts = $this->getParserOptions();
1044 $popts->setInterfaceMessage( $interface );
1045 $popts->setTargetLanguage( $language );
1046
1047 if ( !$title || !$title instanceof Title ) {
1048 global $wgTitle;
1049 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1050 $title = $wgTitle;
1051 }
1052 // Sometimes $wgTitle isn't set either...
1053 if ( !$title ) {
1054 # It's not uncommon having a null $wgTitle in scripts. See r80898
1055 # Create a ghost title in such case
1056 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1057 }
1058
1059 $this->mInParser = true;
1060 $res = $parser->parse( $text, $title, $popts, $linestart );
1061 $this->mInParser = false;
1062
1063 return $res;
1064 }
1065
1066 function disable() {
1067 $this->mDisable = true;
1068 }
1069
1070 function enable() {
1071 $this->mDisable = false;
1072 }
1073
1074 /**
1075 * Clear all stored messages. Mainly used after a mass rebuild.
1076 */
1077 function clear() {
1078 $langs = Language::fetchLanguageNames( null, 'mw' );
1079 foreach ( array_keys( $langs ) as $code ) {
1080 # Global cache
1081 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
1082 # Invalidate all local caches
1083 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1084 }
1085 $this->mLoadedLanguages = array();
1086 }
1087
1088 /**
1089 * @param string $key
1090 * @return array
1091 */
1092 public function figureMessage( $key ) {
1093 global $wgLanguageCode;
1094
1095 $pieces = explode( '/', $key );
1096 if ( count( $pieces ) < 2 ) {
1097 return array( $key, $wgLanguageCode );
1098 }
1099
1100 $lang = array_pop( $pieces );
1101 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1102 return array( $key, $wgLanguageCode );
1103 }
1104
1105 $message = implode( '/', $pieces );
1106
1107 return array( $message, $lang );
1108 }
1109
1110 /**
1111 * Get all message keys stored in the message cache for a given language.
1112 * If $code is the content language code, this will return all message keys
1113 * for which MediaWiki:msgkey exists. If $code is another language code, this
1114 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1115 * @param string $code Language code
1116 * @return array Array of message keys (strings)
1117 */
1118 public function getAllMessageKeys( $code ) {
1119 global $wgContLang;
1120 $this->load( $code );
1121 if ( !isset( $this->mCache[$code] ) ) {
1122 // Apparently load() failed
1123 return null;
1124 }
1125 // Remove administrative keys
1126 $cache = $this->mCache[$code];
1127 unset( $cache['VERSION'] );
1128 unset( $cache['EXPIRY'] );
1129 // Remove any !NONEXISTENT keys
1130 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1131
1132 // Keys may appear with a capital first letter. lcfirst them.
1133 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
1134 }
1135 }