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