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