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