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