0650f1f29cbc35c7fbd3486077af3f48f58a051a
[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 // Don't change getPreferredVariant() to getCode() / mCode, for
585 // more details, see the comment in Language::getMessage().
586 $langcode = $lang->getPreferredVariant();
587
588 $message = false;
589
590 # Normalise title-case input (with some inlining)
591 $lckey = str_replace( ' ', '_', $key );
592 if ( ord( $key ) < 128 ) {
593 $lckey[0] = strtolower( $lckey[0] );
594 $uckey = ucfirst( $lckey );
595 } else {
596 $lckey = $wgContLang->lcfirst( $lckey );
597 $uckey = $wgContLang->ucfirst( $lckey );
598 }
599
600 /**
601 * Record each message request, but only once per request.
602 * This information is not used unless $wgAdaptiveMessageCache
603 * is enabled.
604 */
605 $this->mRequestedMessages[$uckey] = true;
606
607 # Try the MediaWiki namespace
608 if( !$this->mDisable && $useDB ) {
609 $title = $uckey;
610 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
611 $title .= '/' . $langcode;
612 }
613 $message = $this->getMsgFromNamespace( $title, $langcode );
614 }
615
616 # Try the array in the language object
617 if ( $message === false ) {
618 $message = $lang->getMessage( $lckey );
619 if ( is_null( $message ) ) {
620 $message = false;
621 }
622 }
623
624 # Try the array of another language
625 if( $message === false ) {
626 $parts = explode( '/', $lckey );
627 # We may get calls for things that are http-urls from sidebar
628 # Let's not load nonexistent languages for those
629 # They usually have more than one slash.
630 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
631 $message = Language::getMessageFor( $parts[0], $parts[1] );
632 if ( is_null( $message ) ) {
633 $message = false;
634 }
635 }
636 }
637
638 # Is this a custom message? Try the default language in the db...
639 if( ( $message === false || $message === '-' ) &&
640 !$this->mDisable && $useDB &&
641 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
642 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
643 }
644
645 # Final fallback
646 if( $message === false ) {
647 return false;
648 }
649
650 # Fix whitespace
651 $message = strtr( $message,
652 array(
653 # Fix for trailing whitespace, removed by textarea
654 '&#32;' => ' ',
655 # Fix for NBSP, converted to space by firefox
656 '&nbsp;' => "\xc2\xa0",
657 '&#160;' => "\xc2\xa0",
658 ) );
659
660 return $message;
661 }
662
663 /**
664 * Get a message from the MediaWiki namespace, with caching. The key must
665 * first be converted to two-part lang/msg form if necessary.
666 *
667 * @param $title String: Message cache key with initial uppercase letter.
668 * @param $code String: code denoting the language to try.
669 */
670 function getMsgFromNamespace( $title, $code ) {
671 global $wgAdaptiveMessageCache;
672
673 $this->load( $code );
674 if ( isset( $this->mCache[$code][$title] ) ) {
675 $entry = $this->mCache[$code][$title];
676 if ( substr( $entry, 0, 1 ) === ' ' ) {
677 return substr( $entry, 1 );
678 } elseif ( $entry === '!NONEXISTENT' ) {
679 return false;
680 } elseif( $entry === '!TOO BIG' ) {
681 // Fall through and try invididual message cache below
682 }
683 } else {
684 // XXX: This is not cached in process cache, should it?
685 $message = false;
686 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
687 if ( $message !== false ) {
688 return $message;
689 }
690
691 /**
692 * If message cache is in normal mode, it is guaranteed
693 * (except bugs) that there is always entry (or placeholder)
694 * in the cache if message exists. Thus we can do minor
695 * performance improvement and return false early.
696 */
697 if ( !$wgAdaptiveMessageCache ) {
698 return false;
699 }
700 }
701
702 # Try the individual message cache
703 $titleKey = wfMemcKey( 'messages', 'individual', $title );
704 $entry = $this->mMemc->get( $titleKey );
705 if ( $entry ) {
706 if ( substr( $entry, 0, 1 ) === ' ' ) {
707 $this->mCache[$code][$title] = $entry;
708 return substr( $entry, 1 );
709 } elseif ( $entry === '!NONEXISTENT' ) {
710 $this->mCache[$code][$title] = '!NONEXISTENT';
711 return false;
712 } else {
713 # Corrupt/obsolete entry, delete it
714 $this->mMemc->delete( $titleKey );
715 }
716 }
717
718 # Try loading it from the database
719 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
720 if ( $revision ) {
721 $message = $revision->getText();
722 $this->mCache[$code][$title] = ' ' . $message;
723 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
724 } else {
725 $message = false;
726 $this->mCache[$code][$title] = '!NONEXISTENT';
727 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
728 }
729
730 return $message;
731 }
732
733 function transform( $message, $interface = false, $language = null, $title = null ) {
734 // Avoid creating parser if nothing to transform
735 if( strpos( $message, '{{' ) === false ) {
736 return $message;
737 }
738
739 global $wgParser, $wgParserConf;
740 if ( !$this->mParser && isset( $wgParser ) ) {
741 # Do some initialisation so that we don't have to do it twice
742 $wgParser->firstCallInit();
743 # Clone it and store it
744 $class = $wgParserConf['class'];
745 if ( $class == 'Parser_DiffTest' ) {
746 # Uncloneable
747 $this->mParser = new $class( $wgParserConf );
748 } else {
749 $this->mParser = clone $wgParser;
750 }
751 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
752 }
753 if ( $this->mParser ) {
754 $popts = $this->getParserOptions();
755 $popts->setInterfaceMessage( $interface );
756 $popts->setTargetLanguage( $language );
757 $popts->setUserLang( $language );
758 $message = $this->mParser->transformMsg( $message, $popts, $title );
759 }
760 return $message;
761 }
762
763 function disable() {
764 $this->mDisable = true;
765 }
766
767 function enable() {
768 $this->mDisable = false;
769 }
770
771 /**
772 * Clear all stored messages. Mainly used after a mass rebuild.
773 */
774 function clear() {
775 $langs = Language::getLanguageNames( false );
776 foreach ( array_keys($langs) as $code ) {
777 # Global cache
778 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
779 # Invalidate all local caches
780 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
781 }
782 $this->mLoadedLanguages = array();
783 }
784
785 public function figureMessage( $key ) {
786 global $wgLanguageCode;
787 $pieces = explode( '/', $key );
788 if( count( $pieces ) < 2 ) {
789 return array( $key, $wgLanguageCode );
790 }
791
792 $lang = array_pop( $pieces );
793 $validCodes = Language::getLanguageNames();
794 if( !array_key_exists( $lang, $validCodes ) ) {
795 return array( $key, $wgLanguageCode );
796 }
797
798 $message = implode( '/', $pieces );
799 return array( $message, $lang );
800 }
801
802 public static function logMessages() {
803 global $wgAdaptiveMessageCache;
804 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
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 }
838
839 public function getMostUsedMessages() {
840 $cachekey = wfMemcKey( 'message-profiling' );
841 $cache = wfGetCache( CACHE_DB );
842 $data = $cache->get( $cachekey );
843 if ( !$data ) {
844 return array();
845 }
846
847 $list = array();
848
849 foreach( $data as $messages ) {
850 foreach( $messages as $message => $count ) {
851 $key = $message;
852 if ( !isset( $list[$key] ) ) {
853 $list[$key] = 0;
854 }
855 $list[$key] += $count;
856 }
857 }
858
859 $max = max( $list );
860 foreach ( $list as $message => $count ) {
861 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
862 unset( $list[$message] );
863 }
864 }
865
866 return array_keys( $list );
867 }
868
869 }