doc: various updates
[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 * @param string $key The message cache key
664 * @param bool $useDB Get the message from the DB, false to use only
665 * the localisation
666 * @param bool|string $langcode Code of the language to get the message for, if
667 * it is a valid code create a language for that language,
668 * if it is a string but not a valid code then make a basic
669 * language object, if it is a false boolean then use the
670 * current users language (as a fallback for the old
671 * parameter functionality), or if it is a true boolean
672 * then use the wikis content language (also as a
673 * fallback).
674 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
675 *
676 * @throws MWException
677 * @return string|bool
678 */
679 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
680 global $wgLanguageCode, $wgContLang;
681
682 if ( is_int( $key ) ) {
683 // "Non-string key given" exception sometimes happens for numerical
684 // strings that become ints somewhere on their way here
685 $key = strval( $key );
686 }
687
688 if ( !is_string( $key ) ) {
689 throw new MWException( 'Non-string key given' );
690 }
691
692 if ( strval( $key ) === '' ) {
693 # Shortcut: the empty key is always missing
694 return false;
695 }
696
697 $lang = wfGetLangObj( $langcode );
698 if ( !$lang ) {
699 throw new MWException( "Bad lang code $langcode given" );
700 }
701
702 $langcode = $lang->getCode();
703
704 $message = false;
705
706 # Normalise title-case input (with some inlining)
707 $lckey = str_replace( ' ', '_', $key );
708 if ( ord( $key ) < 128 ) {
709 $lckey[0] = strtolower( $lckey[0] );
710 $uckey = ucfirst( $lckey );
711 } else {
712 $lckey = $wgContLang->lcfirst( $lckey );
713 $uckey = $wgContLang->ucfirst( $lckey );
714 }
715
716 # Try the MediaWiki namespace
717 if ( !$this->mDisable && $useDB ) {
718 $title = $uckey;
719 if ( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
720 $title .= '/' . $langcode;
721 }
722 $message = $this->getMsgFromNamespace( $title, $langcode );
723 }
724
725 # Try the array in the language object
726 if ( $message === false ) {
727 $message = $lang->getMessage( $lckey );
728 if ( is_null( $message ) ) {
729 $message = false;
730 }
731 }
732
733 # Try the array of another language
734 if ( $message === false ) {
735 $parts = explode( '/', $lckey );
736 # We may get calls for things that are http-urls from sidebar
737 # Let's not load nonexistent languages for those
738 # They usually have more than one slash.
739 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
740 $message = Language::getMessageFor( $parts[0], $parts[1] );
741 if ( is_null( $message ) ) {
742 $message = false;
743 }
744 }
745 }
746
747 # Is this a custom message? Try the default language in the db...
748 if ( ( $message === false || $message === '-' ) &&
749 !$this->mDisable && $useDB &&
750 !$isFullKey && ( $langcode != $wgLanguageCode )
751 ) {
752 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
753 }
754
755 # Final fallback
756 if ( $message === false ) {
757 return false;
758 }
759
760 # Fix whitespace
761 $message = strtr( $message,
762 array(
763 # Fix for trailing whitespace, removed by textarea
764 '&#32;' => ' ',
765 # Fix for NBSP, converted to space by firefox
766 '&nbsp;' => "\xc2\xa0",
767 '&#160;' => "\xc2\xa0",
768 ) );
769
770 return $message;
771 }
772
773 /**
774 * Get a message from the MediaWiki namespace, with caching. The key must
775 * first be converted to two-part lang/msg form if necessary.
776 *
777 * Unlike self::get(), this function doesn't resolve fallback chains, and
778 * some callers require this behavior. LanguageConverter::parseCachedTable()
779 * and self::get() are some examples in core.
780 *
781 * @param string $title Message cache key with initial uppercase letter.
782 * @param string $code Code denoting the language to try.
783 * @return string|bool False on failure
784 */
785 function getMsgFromNamespace( $title, $code ) {
786 $this->load( $code );
787 if ( isset( $this->mCache[$code][$title] ) ) {
788 $entry = $this->mCache[$code][$title];
789 if ( substr( $entry, 0, 1 ) === ' ' ) {
790 return substr( $entry, 1 );
791 } elseif ( $entry === '!NONEXISTENT' ) {
792 return false;
793 } elseif ( $entry === '!TOO BIG' ) {
794 // Fall through and try invididual message cache below
795 }
796 } else {
797 // XXX: This is not cached in process cache, should it?
798 $message = false;
799 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
800 if ( $message !== false ) {
801 return $message;
802 }
803
804 return false;
805 }
806
807 # Try the individual message cache
808 $titleKey = wfMemcKey( 'messages', 'individual', $title );
809 $entry = $this->mMemc->get( $titleKey );
810 if ( $entry ) {
811 if ( substr( $entry, 0, 1 ) === ' ' ) {
812 $this->mCache[$code][$title] = $entry;
813 return substr( $entry, 1 );
814 } elseif ( $entry === '!NONEXISTENT' ) {
815 $this->mCache[$code][$title] = '!NONEXISTENT';
816 return false;
817 } else {
818 # Corrupt/obsolete entry, delete it
819 $this->mMemc->delete( $titleKey );
820 }
821 }
822
823 # Try loading it from the database
824 $revision = Revision::newFromTitle(
825 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
826 );
827 if ( $revision ) {
828 $content = $revision->getContent();
829 if ( !$content ) {
830 // A possibly temporary loading failure.
831 wfDebugLog(
832 'MessageCache',
833 __METHOD__ . ": failed to load message page text for {$title} ($code)"
834 );
835 $message = null; // no negative caching
836 } else {
837 // XXX: Is this the right way to turn a Content object into a message?
838 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
839 // CssContent. MessageContent is *not* used for storing messages, it's
840 // only used for wrapping them when needed.
841 $message = $content->getWikitextForTransclusion();
842
843 if ( $message === false || $message === null ) {
844 wfDebugLog(
845 'MessageCache',
846 __METHOD__ . ": message content doesn't provide wikitext "
847 . "(content model: " . $content->getContentHandler() . ")"
848 );
849
850 $message = false; // negative caching
851 } else {
852 $this->mCache[$code][$title] = ' ' . $message;
853 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
854 }
855 }
856 } else {
857 $message = false; // negative caching
858 }
859
860 if ( $message === false ) { // negative caching
861 $this->mCache[$code][$title] = '!NONEXISTENT';
862 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
863 }
864
865 return $message;
866 }
867
868 /**
869 * @param string $message
870 * @param bool $interface
871 * @param string $language Language code
872 * @param Title $title
873 * @return string
874 */
875 function transform( $message, $interface = false, $language = null, $title = null ) {
876 // Avoid creating parser if nothing to transform
877 if ( strpos( $message, '{{' ) === false ) {
878 return $message;
879 }
880
881 if ( $this->mInParser ) {
882 return $message;
883 }
884
885 $parser = $this->getParser();
886 if ( $parser ) {
887 $popts = $this->getParserOptions();
888 $popts->setInterfaceMessage( $interface );
889 $popts->setTargetLanguage( $language );
890
891 $userlang = $popts->setUserLang( $language );
892 $this->mInParser = true;
893 $message = $parser->transformMsg( $message, $popts, $title );
894 $this->mInParser = false;
895 $popts->setUserLang( $userlang );
896 }
897 return $message;
898 }
899
900 /**
901 * @return Parser
902 */
903 function getParser() {
904 global $wgParser, $wgParserConf;
905 if ( !$this->mParser && isset( $wgParser ) ) {
906 # Do some initialisation so that we don't have to do it twice
907 $wgParser->firstCallInit();
908 # Clone it and store it
909 $class = $wgParserConf['class'];
910 if ( $class == 'Parser_DiffTest' ) {
911 # Uncloneable
912 $this->mParser = new $class( $wgParserConf );
913 } else {
914 $this->mParser = clone $wgParser;
915 }
916 }
917 return $this->mParser;
918 }
919
920 /**
921 * @param string $text
922 * @param Title $title
923 * @param bool $linestart Whether or not this is at the start of a line
924 * @param bool $interface Whether this is an interface message
925 * @param string $language Language code
926 * @return ParserOutput|string
927 */
928 public function parse( $text, $title = null, $linestart = true,
929 $interface = false, $language = null
930 ) {
931 if ( $this->mInParser ) {
932 return htmlspecialchars( $text );
933 }
934
935 $parser = $this->getParser();
936 $popts = $this->getParserOptions();
937 $popts->setInterfaceMessage( $interface );
938 $popts->setTargetLanguage( $language );
939
940 wfProfileIn( __METHOD__ );
941 if ( !$title || !$title instanceof Title ) {
942 global $wgTitle;
943 $title = $wgTitle;
944 }
945 // Sometimes $wgTitle isn't set either...
946 if ( !$title ) {
947 # It's not uncommon having a null $wgTitle in scripts. See r80898
948 # Create a ghost title in such case
949 $title = Title::newFromText( 'Dwimmerlaik' );
950 }
951
952 $this->mInParser = true;
953 $res = $parser->parse( $text, $title, $popts, $linestart );
954 $this->mInParser = false;
955
956 wfProfileOut( __METHOD__ );
957 return $res;
958 }
959
960 function disable() {
961 $this->mDisable = true;
962 }
963
964 function enable() {
965 $this->mDisable = false;
966 }
967
968 /**
969 * Clear all stored messages. Mainly used after a mass rebuild.
970 */
971 function clear() {
972 $langs = Language::fetchLanguageNames( null, 'mw' );
973 foreach ( array_keys( $langs ) as $code ) {
974 # Global cache
975 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
976 # Invalidate all local caches
977 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
978 }
979 $this->mLoadedLanguages = array();
980 }
981
982 /**
983 * @param $key
984 * @return array
985 */
986 public function figureMessage( $key ) {
987 global $wgLanguageCode;
988 $pieces = explode( '/', $key );
989 if ( count( $pieces ) < 2 ) {
990 return array( $key, $wgLanguageCode );
991 }
992
993 $lang = array_pop( $pieces );
994 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
995 return array( $key, $wgLanguageCode );
996 }
997
998 $message = implode( '/', $pieces );
999 return array( $message, $lang );
1000 }
1001
1002 /**
1003 * Get all message keys stored in the message cache for a given language.
1004 * If $code is the content language code, this will return all message keys
1005 * for which MediaWiki:msgkey exists. If $code is another language code, this
1006 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1007 * @param string $code Language code
1008 * @return array of message keys (strings)
1009 */
1010 public function getAllMessageKeys( $code ) {
1011 global $wgContLang;
1012 $this->load( $code );
1013 if ( !isset( $this->mCache[$code] ) ) {
1014 // Apparently load() failed
1015 return null;
1016 }
1017 // Remove administrative keys
1018 $cache = $this->mCache[$code];
1019 unset( $cache['VERSION'] );
1020 unset( $cache['EXPIRY'] );
1021 // Remove any !NONEXISTENT keys
1022 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1023 // Keys may appear with a capital first letter. lcfirst them.
1024 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
1025 }
1026 }