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