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