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