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