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