Update undelete.php to use short option aliases.
[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 wfProfileOut( __METHOD__ );
444 return;
445 }
446
447 list( $msg, $code ) = $this->figureMessage( $title );
448
449 $cacheKey = wfMemcKey( 'messages', $code );
450 $this->load( $code );
451 $this->lock( $cacheKey );
452
453 $titleKey = wfMemcKey( 'messages', 'individual', $title );
454
455 if ( $text === false ) {
456 # Article was deleted
457 $this->mCache[$code][$title] = '!NONEXISTENT';
458 $this->mMemc->delete( $titleKey );
459 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
460 # Check for size
461 $this->mCache[$code][$title] = '!TOO BIG';
462 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
463 } else {
464 $this->mCache[$code][$title] = ' ' . $text;
465 $this->mMemc->delete( $titleKey );
466 }
467
468 # Update caches
469 $this->saveToCaches( $this->mCache[$code], true, $code );
470 $this->unlock( $cacheKey );
471
472 // Also delete cached sidebar... just in case it is affected
473 $codes = array( $code );
474 if ( $code === 'en' ) {
475 // Delete all sidebars, like for example on action=purge on the
476 // sidebar messages
477 $codes = array_keys( Language::getLanguageNames() );
478 }
479
480 global $parserMemc;
481 foreach ( $codes as $code ) {
482 $sidebarKey = wfMemcKey( 'sidebar', $code );
483 $parserMemc->delete( $sidebarKey );
484 }
485
486 // Update the message in the message blob store
487 global $wgContLang;
488 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
489
490 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
491
492 wfProfileOut( __METHOD__ );
493 }
494
495 /**
496 * Shortcut to update caches.
497 *
498 * @param $cache Array: cached messages with a version.
499 * @param $memc Bool: Wether to update or not memcache.
500 * @param $code String: Language code.
501 * @return False on somekind of error.
502 */
503 protected function saveToCaches( $cache, $memc = true, $code = false ) {
504 wfProfileIn( __METHOD__ );
505 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
506
507 $cacheKey = wfMemcKey( 'messages', $code );
508
509 if ( $memc ) {
510 $success = $this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
511 } else {
512 $success = true;
513 }
514
515 # Save to local cache
516 if ( $wgUseLocalMessageCache ) {
517 $serialized = serialize( $cache );
518 $hash = md5( $serialized );
519 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
520 if ($wgLocalMessageCacheSerialized) {
521 $this->saveToLocal( $serialized, $hash, $code );
522 } else {
523 $this->saveToScript( $cache, $hash, $code );
524 }
525 }
526
527 wfProfileOut( __METHOD__ );
528 return $success;
529 }
530
531 /**
532 * Represents a write lock on the messages key
533 *
534 * @return Boolean: success
535 */
536 function lock( $key ) {
537 $lockKey = $key . ':lock';
538 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
539 sleep( 1 );
540 }
541
542 return $i >= MSG_WAIT_TIMEOUT;
543 }
544
545 function unlock( $key ) {
546 $lockKey = $key . ':lock';
547 $this->mMemc->delete( $lockKey );
548 }
549
550 /**
551 * Get a message from either the content language or the user language.
552 *
553 * @param $key String: the message cache key
554 * @param $useDB Boolean: get the message from the DB, false to use only
555 * the localisation
556 * @param $langcode String: code of the language to get the message for, if
557 * it is a valid code create a language for that language,
558 * if it is a string but not a valid code then make a basic
559 * language object, if it is a false boolean then use the
560 * current users language (as a fallback for the old
561 * parameter functionality), or if it is a true boolean
562 * then use the wikis content language (also as a
563 * fallback).
564 * @param $isFullKey Boolean: specifies whether $key is a two part key
565 * "msg/lang".
566 */
567 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
568 global $wgLanguageCode, $wgContLang;
569
570 if ( !is_string( $key ) ) {
571 throw new MWException( 'Non-string key given' );
572 }
573
574 if ( strval( $key ) === '' ) {
575 # Shortcut: the empty key is always missing
576 return false;
577 }
578
579 $lang = wfGetLangObj( $langcode );
580 if ( !$lang ) {
581 throw new MWException( "Bad lang code $langcode given" );
582 }
583
584 $langcode = $lang->getCode();
585
586 $message = false;
587
588 # Normalise title-case input (with some inlining)
589 $lckey = str_replace( ' ', '_', $key );
590 if ( ord( $key ) < 128 ) {
591 $lckey[0] = strtolower( $lckey[0] );
592 $uckey = ucfirst( $lckey );
593 } else {
594 $lckey = $wgContLang->lcfirst( $lckey );
595 $uckey = $wgContLang->ucfirst( $lckey );
596 }
597
598 /**
599 * Record each message request, but only once per request.
600 * This information is not used unless $wgAdaptiveMessageCache
601 * is enabled.
602 */
603 $this->mRequestedMessages[$uckey] = true;
604
605 # Try the MediaWiki namespace
606 if( !$this->mDisable && $useDB ) {
607 $title = $uckey;
608 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
609 $title .= '/' . $langcode;
610 }
611 $message = $this->getMsgFromNamespace( $title, $langcode );
612 }
613
614 # Try the array in the language object
615 if ( $message === false ) {
616 $message = $lang->getMessage( $lckey );
617 if ( is_null( $message ) ) {
618 $message = false;
619 }
620 }
621
622 # Try the array of another language
623 if( $message === false ) {
624 $parts = explode( '/', $lckey );
625 # We may get calls for things that are http-urls from sidebar
626 # Let's not load nonexistent languages for those
627 # They usually have more than one slash.
628 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
629 $message = Language::getMessageFor( $parts[0], $parts[1] );
630 if ( is_null( $message ) ) {
631 $message = false;
632 }
633 }
634 }
635
636 # Is this a custom message? Try the default language in the db...
637 if( ( $message === false || $message === '-' ) &&
638 !$this->mDisable && $useDB &&
639 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
640 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
641 }
642
643 # Final fallback
644 if( $message === false ) {
645 return false;
646 }
647
648 # Fix whitespace
649 $message = strtr( $message,
650 array(
651 # Fix for trailing whitespace, removed by textarea
652 '&#32;' => ' ',
653 # Fix for NBSP, converted to space by firefox
654 '&nbsp;' => "\xc2\xa0",
655 '&#160;' => "\xc2\xa0",
656 ) );
657
658 return $message;
659 }
660
661 /**
662 * Get a message from the MediaWiki namespace, with caching. The key must
663 * first be converted to two-part lang/msg form if necessary.
664 *
665 * @param $title String: Message cache key with initial uppercase letter.
666 * @param $code String: code denoting the language to try.
667 */
668 function getMsgFromNamespace( $title, $code ) {
669 global $wgAdaptiveMessageCache;
670
671 $this->load( $code );
672 if ( isset( $this->mCache[$code][$title] ) ) {
673 $entry = $this->mCache[$code][$title];
674 if ( substr( $entry, 0, 1 ) === ' ' ) {
675 return substr( $entry, 1 );
676 } elseif ( $entry === '!NONEXISTENT' ) {
677 return false;
678 } elseif( $entry === '!TOO BIG' ) {
679 // Fall through and try invididual message cache below
680 }
681 } else {
682 // XXX: This is not cached in process cache, should it?
683 $message = false;
684 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
685 if ( $message !== false ) {
686 return $message;
687 }
688
689 /**
690 * If message cache is in normal mode, it is guaranteed
691 * (except bugs) that there is always entry (or placeholder)
692 * in the cache if message exists. Thus we can do minor
693 * performance improvement and return false early.
694 */
695 if ( !$wgAdaptiveMessageCache ) {
696 return false;
697 }
698 }
699
700 # Try the individual message cache
701 $titleKey = wfMemcKey( 'messages', 'individual', $title );
702 $entry = $this->mMemc->get( $titleKey );
703 if ( $entry ) {
704 if ( substr( $entry, 0, 1 ) === ' ' ) {
705 $this->mCache[$code][$title] = $entry;
706 return substr( $entry, 1 );
707 } elseif ( $entry === '!NONEXISTENT' ) {
708 $this->mCache[$code][$title] = '!NONEXISTENT';
709 return false;
710 } else {
711 # Corrupt/obsolete entry, delete it
712 $this->mMemc->delete( $titleKey );
713 }
714 }
715
716 # Try loading it from the database
717 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
718 if ( $revision ) {
719 $message = $revision->getText();
720 $this->mCache[$code][$title] = ' ' . $message;
721 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
722 } else {
723 $message = false;
724 $this->mCache[$code][$title] = '!NONEXISTENT';
725 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
726 }
727
728 return $message;
729 }
730
731 function transform( $message, $interface = false, $language = null, $title = null ) {
732 // Avoid creating parser if nothing to transform
733 if( strpos( $message, '{{' ) === false ) {
734 return $message;
735 }
736
737 global $wgParser, $wgParserConf;
738 if ( !$this->mParser && isset( $wgParser ) ) {
739 # Do some initialisation so that we don't have to do it twice
740 $wgParser->firstCallInit();
741 # Clone it and store it
742 $class = $wgParserConf['class'];
743 if ( $class == 'Parser_DiffTest' ) {
744 # Uncloneable
745 $this->mParser = new $class( $wgParserConf );
746 } else {
747 $this->mParser = clone $wgParser;
748 }
749 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
750 }
751 if ( $this->mParser ) {
752 $popts = $this->getParserOptions();
753 $popts->setInterfaceMessage( $interface );
754 $popts->setTargetLanguage( $language );
755 $popts->setUserLang( $language );
756 $message = $this->mParser->transformMsg( $message, $popts, $title );
757 }
758 return $message;
759 }
760
761 function disable() {
762 $this->mDisable = true;
763 }
764
765 function enable() {
766 $this->mDisable = false;
767 }
768
769 /**
770 * Clear all stored messages. Mainly used after a mass rebuild.
771 */
772 function clear() {
773 $langs = Language::getLanguageNames( false );
774 foreach ( array_keys($langs) as $code ) {
775 # Global cache
776 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
777 # Invalidate all local caches
778 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
779 }
780 $this->mLoadedLanguages = array();
781 }
782
783 public function figureMessage( $key ) {
784 global $wgLanguageCode;
785 $pieces = explode( '/', $key );
786 if( count( $pieces ) < 2 ) {
787 return array( $key, $wgLanguageCode );
788 }
789
790 $lang = array_pop( $pieces );
791 $validCodes = Language::getLanguageNames();
792 if( !array_key_exists( $lang, $validCodes ) ) {
793 return array( $key, $wgLanguageCode );
794 }
795
796 $message = implode( '/', $pieces );
797 return array( $message, $lang );
798 }
799
800 public static function logMessages() {
801 wfProfileIn( __METHOD__ );
802 global $wgAdaptiveMessageCache;
803 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
804 wfProfileOut( __METHOD__ );
805 return;
806 }
807
808 $cachekey = wfMemckey( 'message-profiling' );
809 $cache = wfGetCache( CACHE_DB );
810 $data = $cache->get( $cachekey );
811
812 if ( !$data ) {
813 $data = array();
814 }
815
816 $age = self::$mAdaptiveDataAge;
817 $filterDate = substr( wfTimestamp( TS_MW, time() - $age ), 0, 8 );
818 foreach ( array_keys( $data ) as $key ) {
819 if ( $key < $filterDate ) {
820 unset( $data[$key] );
821 }
822 }
823
824 $index = substr( wfTimestampNow(), 0, 8 );
825 if ( !isset( $data[$index] ) ) {
826 $data[$index] = array();
827 }
828
829 foreach ( self::$instance->mRequestedMessages as $message => $_ ) {
830 if ( !isset( $data[$index][$message] ) ) {
831 $data[$index][$message] = 0;
832 }
833 $data[$index][$message]++;
834 }
835
836 $cache->set( $cachekey, $data );
837 wfProfileOut( __METHOD__ );
838 }
839
840 public function getMostUsedMessages() {
841 wfProfileIn( __METHOD__ );
842 $cachekey = wfMemcKey( 'message-profiling' );
843 $cache = wfGetCache( CACHE_DB );
844 $data = $cache->get( $cachekey );
845 if ( !$data ) {
846 wfProfileOut( __METHOD__ );
847 return array();
848 }
849
850 $list = array();
851
852 foreach( $data as $messages ) {
853 foreach( $messages as $message => $count ) {
854 $key = $message;
855 if ( !isset( $list[$key] ) ) {
856 $list[$key] = 0;
857 }
858 $list[$key] += $count;
859 }
860 }
861
862 $max = max( $list );
863 foreach ( $list as $message => $count ) {
864 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
865 unset( $list[$message] );
866 }
867 }
868
869 wfProfileOut( __METHOD__ );
870 return array_keys( $list );
871 }
872
873 }