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