Removed remaining profile calls
[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
314 if ( $success ) {
315 # Done, no need to retry
316 break;
317 }
318
319 # We need to call loadFromDB. Limit the concurrency to a single
320 # process. This prevents the site from going down when the cache
321 # expires.
322 $statusKey = wfMemcKey( 'messages', $code, 'status' );
323 $acquired = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
324 if ( $acquired ) {
325 # Unlock the status key if there is an exception
326 $that = $this;
327 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
328 $that->mMemc->delete( $statusKey );
329 } );
330
331 # Now let's regenerate
332 $where[] = 'loading from database';
333
334 # Lock the cache to prevent conflicting writes
335 # If this lock fails, it doesn't really matter, it just means the
336 # write is potentially non-atomic, e.g. the results of a replace()
337 # may be discarded.
338 if ( $this->lock( $cacheKey ) ) {
339 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
340 $that->unlock( $cacheKey );
341 } );
342 } else {
343 $mainUnlocker = null;
344 $where[] = 'could not acquire main lock';
345 }
346
347 $cache = $this->loadFromDB( $code );
348 $this->mCache[$code] = $cache;
349 $success = true;
350 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
351
352 # Unlock
353 ScopedCallback::consume( $mainUnlocker );
354 ScopedCallback::consume( $statusUnlocker );
355
356 if ( !$saveSuccess ) {
357 # Cache save has failed.
358 # There are two main scenarios where this could be a problem:
359 #
360 # - The cache is more than the maximum size (typically
361 # 1MB compressed).
362 #
363 # - Memcached has no space remaining in the relevant slab
364 # class. This is unlikely with recent versions of
365 # memcached.
366 #
367 # Either way, if there is a local cache, nothing bad will
368 # happen. If there is no local cache, disabling the message
369 # cache for all requests avoids incurring a loadFromDB()
370 # overhead on every request, and thus saves the wiki from
371 # complete downtime under moderate traffic conditions.
372 if ( !$wgUseLocalMessageCache ) {
373 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
374 $where[] = 'could not save cache, disabled globally for 5 minutes';
375 } else {
376 $where[] = "could not save global cache";
377 }
378 }
379
380 # Load from DB complete, no need to retry
381 break;
382 } elseif ( $staleCache ) {
383 # Use the stale cache while some other thread constructs the new one
384 $where[] = 'using stale cache';
385 $this->mCache[$code] = $staleCache;
386 $success = true;
387 break;
388 } elseif ( $failedAttempts > 0 ) {
389 # Already retried once, still failed, so don't do another lock/unlock cycle
390 # This case will typically be hit if memcached is down, or if
391 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
392 $where[] = "could not acquire status key.";
393 break;
394 } else {
395 $status = $this->mMemc->get( $statusKey );
396 if ( $status === 'error' ) {
397 # Disable cache
398 break;
399 } else {
400 # Wait for the other thread to finish, then retry
401 $where[] = 'waited for other thread to complete';
402 $this->lock( $cacheKey );
403 $this->unlock( $cacheKey );
404 }
405 }
406 }
407 }
408
409 if ( !$success ) {
410 $where[] = 'loading FAILED - cache is disabled';
411 $this->mDisable = true;
412 $this->mCache = false;
413 # This used to throw an exception, but that led to nasty side effects like
414 # the whole wiki being instantly down if the memcached server died
415 } else {
416 # All good, just record the success
417 $this->mLoadedLanguages[$code] = true;
418 }
419 $info = implode( ', ', $where );
420 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
421
422 return $success;
423 }
424
425 /**
426 * Loads cacheable messages from the database. Messages bigger than
427 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
428 * on-demand from the database later.
429 *
430 * @param string $code Language code.
431 * @return array Loaded messages for storing in caches.
432 */
433 function loadFromDB( $code ) {
434 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
435 $dbr = wfGetDB( DB_SLAVE );
436 $cache = array();
437
438 # Common conditions
439 $conds = array(
440 'page_is_redirect' => 0,
441 'page_namespace' => NS_MEDIAWIKI,
442 );
443
444 $mostused = array();
445 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
446 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
447 $this->load( $wgLanguageCode );
448 }
449 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
450 foreach ( $mostused as $key => $value ) {
451 $mostused[$key] = "$value/$code";
452 }
453 }
454
455 if ( count( $mostused ) ) {
456 $conds['page_title'] = $mostused;
457 } elseif ( $code !== $wgLanguageCode ) {
458 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
459 } else {
460 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
461 # other than language code.
462 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
463 }
464
465 # Conditions to fetch oversized pages to ignore them
466 $bigConds = $conds;
467 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
468
469 # Load titles for all oversized pages in the MediaWiki namespace
470 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
471 foreach ( $res as $row ) {
472 $cache[$row->page_title] = '!TOO BIG';
473 }
474
475 # Conditions to load the remaining pages with their contents
476 $smallConds = $conds;
477 $smallConds[] = 'page_latest=rev_id';
478 $smallConds[] = 'rev_text_id=old_id';
479 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
480
481 $res = $dbr->select(
482 array( 'page', 'revision', 'text' ),
483 array( 'page_title', 'old_text', 'old_flags' ),
484 $smallConds,
485 __METHOD__ . "($code)-small"
486 );
487
488 foreach ( $res as $row ) {
489 $text = Revision::getRevisionText( $row );
490 if ( $text === false ) {
491 // Failed to fetch data; possible ES errors?
492 // Store a marker to fetch on-demand as a workaround...
493 $entry = '!TOO BIG';
494 wfDebugLog(
495 'MessageCache',
496 __METHOD__
497 . ": failed to load message page text for {$row->page_title} ($code)"
498 );
499 } else {
500 $entry = ' ' . $text;
501 }
502 $cache[$row->page_title] = $entry;
503 }
504
505 $cache['VERSION'] = MSG_CACHE_VERSION;
506 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
507
508 return $cache;
509 }
510
511 /**
512 * Updates cache as necessary when message page is changed
513 *
514 * @param string $title Name of the page changed.
515 * @param mixed $text New contents of the page.
516 */
517 public function replace( $title, $text ) {
518 global $wgMaxMsgCacheEntrySize;
519
520 if ( $this->mDisable ) {
521
522 return;
523 }
524
525 list( $msg, $code ) = $this->figureMessage( $title );
526
527 $cacheKey = wfMemcKey( 'messages', $code );
528 $this->load( $code );
529 $this->lock( $cacheKey );
530
531 $titleKey = wfMemcKey( 'messages', 'individual', $title );
532
533 if ( $text === false ) {
534 # Article was deleted
535 $this->mCache[$code][$title] = '!NONEXISTENT';
536 $this->mMemc->delete( $titleKey );
537 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
538 # Check for size
539 $this->mCache[$code][$title] = '!TOO BIG';
540 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
541 } else {
542 $this->mCache[$code][$title] = ' ' . $text;
543 $this->mMemc->delete( $titleKey );
544 }
545
546 # Update caches
547 $this->saveToCaches( $this->mCache[$code], 'all', $code );
548 $this->unlock( $cacheKey );
549
550 // Also delete cached sidebar... just in case it is affected
551 $codes = array( $code );
552 if ( $code === 'en' ) {
553 // Delete all sidebars, like for example on action=purge on the
554 // sidebar messages
555 $codes = array_keys( Language::fetchLanguageNames() );
556 }
557
558 global $wgMemc;
559 foreach ( $codes as $code ) {
560 $sidebarKey = wfMemcKey( 'sidebar', $code );
561 $wgMemc->delete( $sidebarKey );
562 }
563
564 // Update the message in the message blob store
565 global $wgContLang;
566 MessageBlobStore::getInstance()->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
621 return $success;
622 }
623
624 /**
625 * Represents a write lock on the messages key.
626 *
627 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
628 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
629 *
630 * @param string $key
631 * @return bool Success
632 */
633 function lock( $key ) {
634 $lockKey = $key . ':lock';
635 $acquired = false;
636 $testDone = false;
637 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
638 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
639 if ( $acquired ) {
640 break;
641 }
642
643 # Fail fast if memcached is totally down
644 if ( !$testDone ) {
645 $testDone = true;
646 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
647 break;
648 }
649 }
650 sleep( 1 );
651 }
652
653 return $acquired;
654 }
655
656 function unlock( $key ) {
657 $lockKey = $key . ':lock';
658 $this->mMemc->delete( $lockKey );
659 }
660
661 /**
662 * Get a message from either the content language or the user language.
663 *
664 * First, assemble a list of languages to attempt getting the message from. This
665 * chain begins with the requested language and its fallbacks and then continues with
666 * the content language and its fallbacks. For each language in the chain, the following
667 * process will occur (in this order):
668 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
669 * Note: for the content language, there is no /lang subpage.
670 * 2. Fetch from the static CDB cache.
671 * 3. If available, check the database for fallback language overrides.
672 *
673 * This process provides a number of guarantees. When changing this code, make sure all
674 * of these guarantees are preserved.
675 * * If the requested language is *not* the content language, then the CDB cache for that
676 * specific language will take precedence over the root database page ([[MW:msg]]).
677 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
678 * the message is available *anywhere* in the language for which it is a fallback.
679 *
680 * @param string $key The message key
681 * @param bool $useDB If true, look for the message in the DB, false
682 * to use only the compiled l10n cache.
683 * @param bool|string|object $langcode Code of the language to get the message for.
684 * - If string and a valid code, will create a standard language object
685 * - If string but not a valid code, will create a basic language object
686 * - If boolean and false, create object from the current users language
687 * - If boolean and true, create object from the wikis content language
688 * - If language object, use it as given
689 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
690 *
691 * @throws MWException When given an invalid key
692 * @return string|bool False if the message doesn't exist, otherwise the
693 * message (which can be empty)
694 */
695 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
696 global $wgContLang;
697
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( $lckey ) < 128 ) {
720 $lckey[0] = strtolower( $lckey[0] );
721 } else {
722 $lckey = $wgContLang->lcfirst( $lckey );
723 }
724
725 Hooks::run( 'MessageCache::get', array( &$lckey ) );
726
727 if ( ord( $lckey ) < 128 ) {
728 $uckey = ucfirst( $lckey );
729 } else {
730 $uckey = $wgContLang->ucfirst( $lckey );
731 }
732
733 // Loop through each language in the fallback list until we find something useful
734 $lang = wfGetLangObj( $langcode );
735 $message = $this->getMessageFromFallbackChain(
736 $lang,
737 $lckey,
738 $uckey,
739 !$this->mDisable && $useDB
740 );
741
742 // If we still have no message, maybe the key was in fact a full key so try that
743 if ( $message === false ) {
744 $parts = explode( '/', $lckey );
745 // We may get calls for things that are http-urls from sidebar
746 // Let's not load nonexistent languages for those
747 // They usually have more than one slash.
748 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
749 $message = Language::getMessageFor( $parts[0], $parts[1] );
750 if ( $message === null ) {
751 $message = false;
752 }
753 }
754 }
755
756 // Post-processing if the message exists
757 if ( $message !== false ) {
758 // Fix whitespace
759 $message = str_replace(
760 array(
761 # Fix for trailing whitespace, removed by textarea
762 '&#32;',
763 # Fix for NBSP, converted to space by firefox
764 '&nbsp;',
765 '&#160;',
766 ),
767 array(
768 ' ',
769 "\xc2\xa0",
770 "\xc2\xa0"
771 ),
772 $message
773 );
774 }
775
776 return $message;
777 }
778
779 /**
780 * Given a language, try and fetch a message from that language, then the
781 * fallbacks of that language, then the site language, then the fallbacks for the
782 * site language.
783 *
784 * @param Language $lang Requested language
785 * @param string $lckey Lowercase key for the message
786 * @param string $uckey Uppercase key for the message
787 * @param bool $useDB Whether to use the database
788 *
789 * @see MessageCache::get
790 * @return string|bool The message, or false if not found
791 */
792 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
793 global $wgLanguageCode, $wgContLang;
794
795 $langcode = $lang->getCode();
796 $message = false;
797
798 // First try the requested language.
799 if ( $useDB ) {
800 if ( $langcode === $wgLanguageCode ) {
801 // Messages created in the content language will not have the /lang extension
802 $message = $this->getMsgFromNamespace( $uckey, $langcode );
803 } else {
804 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
805 }
806 }
807
808 if ( $message !== false ) {
809 return $message;
810 }
811
812 // Check the CDB cache
813 $message = $lang->getMessage( $lckey );
814 if ( $message !== null ) {
815 return $message;
816 }
817
818 list( $fallbackChain, $siteFallbackChain ) =
819 Language::getFallbacksIncludingSiteLanguage( $langcode );
820
821 // Next try checking the database for all of the fallback languages of the requested language.
822 if ( $useDB ) {
823 foreach ( $fallbackChain as $code ) {
824 if ( $code === $wgLanguageCode ) {
825 // Messages created in the content language will not have the /lang extension
826 $message = $this->getMsgFromNamespace( $uckey, $code );
827 } else {
828 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
829 }
830
831 if ( $message !== false ) {
832 // Found the message.
833 return $message;
834 }
835 }
836 }
837
838 // Now try checking the site language.
839 if ( $useDB ) {
840 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
841 if ( $message !== false ) {
842 return $message;
843 }
844 }
845
846 $message = $wgContLang->getMessage( $lckey );
847 if ( $message !== null ) {
848 return $message;
849 }
850
851 // Finally try the DB for the site language's fallbacks.
852 if ( $useDB ) {
853 foreach ( $siteFallbackChain as $code ) {
854 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
855 if ( $message === false && $code === $wgLanguageCode ) {
856 // Messages created in the content language will not have the /lang extension
857 $message = $this->getMsgFromNamespace( $uckey, $code );
858 }
859
860 if ( $message !== false ) {
861 // Found the message.
862 return $message;
863 }
864 }
865 }
866
867 return false;
868 }
869
870 /**
871 * Get a message from the MediaWiki namespace, with caching. The key must
872 * first be converted to two-part lang/msg form if necessary.
873 *
874 * Unlike self::get(), this function doesn't resolve fallback chains, and
875 * some callers require this behavior. LanguageConverter::parseCachedTable()
876 * and self::get() are some examples in core.
877 *
878 * @param string $title Message cache key with initial uppercase letter.
879 * @param string $code Code denoting the language to try.
880 * @return string|bool The message, or false if it does not exist or on error
881 */
882 function getMsgFromNamespace( $title, $code ) {
883 $this->load( $code );
884 if ( isset( $this->mCache[$code][$title] ) ) {
885 $entry = $this->mCache[$code][$title];
886 if ( substr( $entry, 0, 1 ) === ' ' ) {
887 // The message exists, so make sure a string
888 // is returned.
889 return (string)substr( $entry, 1 );
890 } elseif ( $entry === '!NONEXISTENT' ) {
891 return false;
892 } elseif ( $entry === '!TOO BIG' ) {
893 // Fall through and try invididual message cache below
894 }
895 } else {
896 // XXX: This is not cached in process cache, should it?
897 $message = false;
898 Hooks::run( 'MessagesPreLoad', array( $title, &$message ) );
899 if ( $message !== false ) {
900 return $message;
901 }
902
903 return false;
904 }
905
906 # Try the individual message cache
907 $titleKey = wfMemcKey( 'messages', 'individual', $title );
908 $entry = $this->mMemc->get( $titleKey );
909 if ( $entry ) {
910 if ( substr( $entry, 0, 1 ) === ' ' ) {
911 $this->mCache[$code][$title] = $entry;
912
913 // The message exists, so make sure a string
914 // is returned.
915 return (string)substr( $entry, 1 );
916 } elseif ( $entry === '!NONEXISTENT' ) {
917 $this->mCache[$code][$title] = '!NONEXISTENT';
918
919 return false;
920 } else {
921 # Corrupt/obsolete entry, delete it
922 $this->mMemc->delete( $titleKey );
923 }
924 }
925
926 # Try loading it from the database
927 $revision = Revision::newFromTitle(
928 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
929 );
930 if ( $revision ) {
931 $content = $revision->getContent();
932 if ( !$content ) {
933 // A possibly temporary loading failure.
934 wfDebugLog(
935 'MessageCache',
936 __METHOD__ . ": failed to load message page text for {$title} ($code)"
937 );
938 $message = null; // no negative caching
939 } else {
940 // XXX: Is this the right way to turn a Content object into a message?
941 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
942 // CssContent. MessageContent is *not* used for storing messages, it's
943 // only used for wrapping them when needed.
944 $message = $content->getWikitextForTransclusion();
945
946 if ( $message === false || $message === null ) {
947 wfDebugLog(
948 'MessageCache',
949 __METHOD__ . ": message content doesn't provide wikitext "
950 . "(content model: " . $content->getContentHandler() . ")"
951 );
952
953 $message = false; // negative caching
954 } else {
955 $this->mCache[$code][$title] = ' ' . $message;
956 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
957 }
958 }
959 } else {
960 $message = false; // negative caching
961 }
962
963 if ( $message === false ) { // negative caching
964 $this->mCache[$code][$title] = '!NONEXISTENT';
965 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
966 }
967
968 return $message;
969 }
970
971 /**
972 * @param string $message
973 * @param bool $interface
974 * @param string $language Language code
975 * @param Title $title
976 * @return string
977 */
978 function transform( $message, $interface = false, $language = null, $title = null ) {
979 // Avoid creating parser if nothing to transform
980 if ( strpos( $message, '{{' ) === false ) {
981 return $message;
982 }
983
984 if ( $this->mInParser ) {
985 return $message;
986 }
987
988 $parser = $this->getParser();
989 if ( $parser ) {
990 $popts = $this->getParserOptions();
991 $popts->setInterfaceMessage( $interface );
992 $popts->setTargetLanguage( $language );
993
994 $userlang = $popts->setUserLang( $language );
995 $this->mInParser = true;
996 $message = $parser->transformMsg( $message, $popts, $title );
997 $this->mInParser = false;
998 $popts->setUserLang( $userlang );
999 }
1000
1001 return $message;
1002 }
1003
1004 /**
1005 * @return Parser
1006 */
1007 function getParser() {
1008 global $wgParser, $wgParserConf;
1009 if ( !$this->mParser && isset( $wgParser ) ) {
1010 # Do some initialisation so that we don't have to do it twice
1011 $wgParser->firstCallInit();
1012 # Clone it and store it
1013 $class = $wgParserConf['class'];
1014 if ( $class == 'ParserDiffTest' ) {
1015 # Uncloneable
1016 $this->mParser = new $class( $wgParserConf );
1017 } else {
1018 $this->mParser = clone $wgParser;
1019 }
1020 }
1021
1022 return $this->mParser;
1023 }
1024
1025 /**
1026 * @param string $text
1027 * @param Title $title
1028 * @param bool $linestart Whether or not this is at the start of a line
1029 * @param bool $interface Whether this is an interface message
1030 * @param string $language Language code
1031 * @return ParserOutput|string
1032 */
1033 public function parse( $text, $title = null, $linestart = true,
1034 $interface = false, $language = null
1035 ) {
1036 if ( $this->mInParser ) {
1037 return htmlspecialchars( $text );
1038 }
1039
1040 $parser = $this->getParser();
1041 $popts = $this->getParserOptions();
1042 $popts->setInterfaceMessage( $interface );
1043 $popts->setTargetLanguage( $language );
1044
1045 if ( !$title || !$title instanceof Title ) {
1046 global $wgTitle;
1047 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1048 $title = $wgTitle;
1049 }
1050 // Sometimes $wgTitle isn't set either...
1051 if ( !$title ) {
1052 # It's not uncommon having a null $wgTitle in scripts. See r80898
1053 # Create a ghost title in such case
1054 $title = Title::newFromText( 'Dwimmerlaik' );
1055 }
1056
1057 $this->mInParser = true;
1058 $res = $parser->parse( $text, $title, $popts, $linestart );
1059 $this->mInParser = false;
1060
1061
1062 return $res;
1063 }
1064
1065 function disable() {
1066 $this->mDisable = true;
1067 }
1068
1069 function enable() {
1070 $this->mDisable = false;
1071 }
1072
1073 /**
1074 * Clear all stored messages. Mainly used after a mass rebuild.
1075 */
1076 function clear() {
1077 $langs = Language::fetchLanguageNames( null, 'mw' );
1078 foreach ( array_keys( $langs ) as $code ) {
1079 # Global cache
1080 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
1081 # Invalidate all local caches
1082 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1083 }
1084 $this->mLoadedLanguages = array();
1085 }
1086
1087 /**
1088 * @param string $key
1089 * @return array
1090 */
1091 public function figureMessage( $key ) {
1092 global $wgLanguageCode;
1093 $pieces = explode( '/', $key );
1094 if ( count( $pieces ) < 2 ) {
1095 return array( $key, $wgLanguageCode );
1096 }
1097
1098 $lang = array_pop( $pieces );
1099 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1100 return array( $key, $wgLanguageCode );
1101 }
1102
1103 $message = implode( '/', $pieces );
1104
1105 return array( $message, $lang );
1106 }
1107
1108 /**
1109 * Get all message keys stored in the message cache for a given language.
1110 * If $code is the content language code, this will return all message keys
1111 * for which MediaWiki:msgkey exists. If $code is another language code, this
1112 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1113 * @param string $code Language code
1114 * @return array Array of message keys (strings)
1115 */
1116 public function getAllMessageKeys( $code ) {
1117 global $wgContLang;
1118 $this->load( $code );
1119 if ( !isset( $this->mCache[$code] ) ) {
1120 // Apparently load() failed
1121 return null;
1122 }
1123 // Remove administrative keys
1124 $cache = $this->mCache[$code];
1125 unset( $cache['VERSION'] );
1126 unset( $cache['EXPIRY'] );
1127 // Remove any !NONEXISTENT keys
1128 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1129
1130 // Keys may appear with a capital first letter. lcfirst them.
1131 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
1132 }
1133 }