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