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