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