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