6b53db0f54fa3ffc6e6f1231d731fa02fe7aeb18
[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, null, __METHOD__ ); // 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, null, __METHOD__ ); // 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 $text = Revision::getRevisionText( $row );
432 if( $text === false ) {
433 // Failed to fetch data; possible ES errors?
434 // Store a marker to fetch on-demand as a workaround...
435 $entry = '!TOO BIG';
436 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$row->page_title} ($code)" );
437 } else {
438 $entry = ' ' . $text;
439 }
440 $cache[$row->page_title] = $entry;
441 }
442
443 foreach ( $mostused as $key ) {
444 if ( !isset( $cache[$key] ) ) {
445 $cache[$key] = '!NONEXISTENT';
446 }
447 }
448
449 $cache['VERSION'] = MSG_CACHE_VERSION;
450 wfProfileOut( __METHOD__ );
451 return $cache;
452 }
453
454 /**
455 * Updates cache as necessary when message page is changed
456 *
457 * @param $title String: name of the page changed.
458 * @param $text Mixed: new contents of the page.
459 */
460 public function replace( $title, $text ) {
461 global $wgMaxMsgCacheEntrySize;
462 wfProfileIn( __METHOD__ );
463
464 if ( $this->mDisable ) {
465 wfProfileOut( __METHOD__ );
466 return;
467 }
468
469 list( $msg, $code ) = $this->figureMessage( $title );
470
471 $cacheKey = wfMemcKey( 'messages', $code );
472 $this->load( $code );
473 $this->lock( $cacheKey );
474
475 $titleKey = wfMemcKey( 'messages', 'individual', $title );
476
477 if ( $text === false ) {
478 # Article was deleted
479 $this->mCache[$code][$title] = '!NONEXISTENT';
480 $this->mMemc->delete( $titleKey );
481 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
482 # Check for size
483 $this->mCache[$code][$title] = '!TOO BIG';
484 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
485 } else {
486 $this->mCache[$code][$title] = ' ' . $text;
487 $this->mMemc->delete( $titleKey );
488 }
489
490 # Update caches
491 $this->saveToCaches( $this->mCache[$code], true, $code );
492 $this->unlock( $cacheKey );
493
494 // Also delete cached sidebar... just in case it is affected
495 $codes = array( $code );
496 if ( $code === 'en' ) {
497 // Delete all sidebars, like for example on action=purge on the
498 // sidebar messages
499 $codes = array_keys( Language::getLanguageNames() );
500 }
501
502 global $wgMemc;
503 foreach ( $codes as $code ) {
504 $sidebarKey = wfMemcKey( 'sidebar', $code );
505 $wgMemc->delete( $sidebarKey );
506 }
507
508 // Update the message in the message blob store
509 global $wgContLang;
510 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
511
512 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
513
514 wfProfileOut( __METHOD__ );
515 }
516
517 /**
518 * Shortcut to update caches.
519 *
520 * @param $cache Array: cached messages with a version.
521 * @param $memc Bool: Wether to update or not memcache.
522 * @param $code String: Language code.
523 * @return False on somekind of error.
524 */
525 protected function saveToCaches( $cache, $memc = true, $code = false ) {
526 wfProfileIn( __METHOD__ );
527 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
528
529 $cacheKey = wfMemcKey( 'messages', $code );
530
531 if ( $memc ) {
532 $success = $this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
533 } else {
534 $success = true;
535 }
536
537 # Save to local cache
538 if ( $wgUseLocalMessageCache ) {
539 $serialized = serialize( $cache );
540 $hash = md5( $serialized );
541 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
542 if ($wgLocalMessageCacheSerialized) {
543 $this->saveToLocal( $serialized, $hash, $code );
544 } else {
545 $this->saveToScript( $cache, $hash, $code );
546 }
547 }
548
549 wfProfileOut( __METHOD__ );
550 return $success;
551 }
552
553 /**
554 * Represents a write lock on the messages key
555 *
556 * @param $key string
557 *
558 * @return Boolean: success
559 */
560 function lock( $key ) {
561 $lockKey = $key . ':lock';
562 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
563 sleep( 1 );
564 }
565
566 return $i >= MSG_WAIT_TIMEOUT;
567 }
568
569 function unlock( $key ) {
570 $lockKey = $key . ':lock';
571 $this->mMemc->delete( $lockKey );
572 }
573
574 /**
575 * Get a message from either the content language or the user language.
576 *
577 * @param $key String: the message cache key
578 * @param $useDB Boolean: get the message from the DB, false to use only
579 * the localisation
580 * @param $langcode String: code of the language to get the message for, if
581 * it is a valid code create a language for that language,
582 * if it is a string but not a valid code then make a basic
583 * language object, if it is a false boolean then use the
584 * current users language (as a fallback for the old
585 * parameter functionality), or if it is a true boolean
586 * then use the wikis content language (also as a
587 * fallback).
588 * @param $isFullKey Boolean: specifies whether $key is a two part key
589 * "msg/lang".
590 *
591 * @return string|false
592 */
593 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
594 global $wgLanguageCode, $wgContLang;
595
596 if ( is_int( $key ) ) {
597 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
598 $key = strval( $key );
599 }
600
601 if ( !is_string( $key ) ) {
602 throw new MWException( 'Non-string key given' );
603 }
604
605 if ( strval( $key ) === '' ) {
606 # Shortcut: the empty key is always missing
607 return false;
608 }
609
610 $lang = wfGetLangObj( $langcode );
611 if ( !$lang ) {
612 throw new MWException( "Bad lang code $langcode given" );
613 }
614
615 $langcode = $lang->getCode();
616
617 $message = false;
618
619 # Normalise title-case input (with some inlining)
620 $lckey = str_replace( ' ', '_', $key );
621 if ( ord( $key ) < 128 ) {
622 $lckey[0] = strtolower( $lckey[0] );
623 $uckey = ucfirst( $lckey );
624 } else {
625 $lckey = $wgContLang->lcfirst( $lckey );
626 $uckey = $wgContLang->ucfirst( $lckey );
627 }
628
629 /**
630 * Record each message request, but only once per request.
631 * This information is not used unless $wgAdaptiveMessageCache
632 * is enabled.
633 */
634 $this->mRequestedMessages[$uckey] = true;
635
636 # Try the MediaWiki namespace
637 if( !$this->mDisable && $useDB ) {
638 $title = $uckey;
639 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
640 $title .= '/' . $langcode;
641 }
642 $message = $this->getMsgFromNamespace( $title, $langcode );
643 }
644
645 # Try the array in the language object
646 if ( $message === false ) {
647 $message = $lang->getMessage( $lckey );
648 if ( is_null( $message ) ) {
649 $message = false;
650 }
651 }
652
653 # Try the array of another language
654 if( $message === false ) {
655 $parts = explode( '/', $lckey );
656 # We may get calls for things that are http-urls from sidebar
657 # Let's not load nonexistent languages for those
658 # They usually have more than one slash.
659 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
660 $message = Language::getMessageFor( $parts[0], $parts[1] );
661 if ( is_null( $message ) ) {
662 $message = false;
663 }
664 }
665 }
666
667 # Is this a custom message? Try the default language in the db...
668 if( ( $message === false || $message === '-' ) &&
669 !$this->mDisable && $useDB &&
670 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
671 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
672 }
673
674 # Final fallback
675 if( $message === false ) {
676 return false;
677 }
678
679 # Fix whitespace
680 $message = strtr( $message,
681 array(
682 # Fix for trailing whitespace, removed by textarea
683 '&#32;' => ' ',
684 # Fix for NBSP, converted to space by firefox
685 '&nbsp;' => "\xc2\xa0",
686 '&#160;' => "\xc2\xa0",
687 ) );
688
689 return $message;
690 }
691
692 /**
693 * Get a message from the MediaWiki namespace, with caching. The key must
694 * first be converted to two-part lang/msg form if necessary.
695 *
696 * @param $title String: Message cache key with initial uppercase letter.
697 * @param $code String: code denoting the language to try.
698 *
699 * @return string|false
700 */
701 function getMsgFromNamespace( $title, $code ) {
702 global $wgAdaptiveMessageCache;
703
704 $this->load( $code );
705 if ( isset( $this->mCache[$code][$title] ) ) {
706 $entry = $this->mCache[$code][$title];
707 if ( substr( $entry, 0, 1 ) === ' ' ) {
708 return substr( $entry, 1 );
709 } elseif ( $entry === '!NONEXISTENT' ) {
710 return false;
711 } elseif( $entry === '!TOO BIG' ) {
712 // Fall through and try invididual message cache below
713 }
714 } else {
715 // XXX: This is not cached in process cache, should it?
716 $message = false;
717 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
718 if ( $message !== false ) {
719 return $message;
720 }
721
722 /**
723 * If message cache is in normal mode, it is guaranteed
724 * (except bugs) that there is always entry (or placeholder)
725 * in the cache if message exists. Thus we can do minor
726 * performance improvement and return false early.
727 */
728 if ( !$wgAdaptiveMessageCache ) {
729 return false;
730 }
731 }
732
733 # Try the individual message cache
734 $titleKey = wfMemcKey( 'messages', 'individual', $title );
735 $entry = $this->mMemc->get( $titleKey );
736 if ( $entry ) {
737 if ( substr( $entry, 0, 1 ) === ' ' ) {
738 $this->mCache[$code][$title] = $entry;
739 return substr( $entry, 1 );
740 } elseif ( $entry === '!NONEXISTENT' ) {
741 $this->mCache[$code][$title] = '!NONEXISTENT';
742 return false;
743 } else {
744 # Corrupt/obsolete entry, delete it
745 $this->mMemc->delete( $titleKey );
746 }
747 }
748
749 # Try loading it from the database
750 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
751 if ( $revision ) {
752 $message = $revision->getText();
753 if ($message === false) {
754 // A possibly temporary loading failure.
755 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$title->getDbKey()} ($code)" );
756 } else {
757 $this->mCache[$code][$title] = ' ' . $message;
758 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
759 }
760 } else {
761 $message = false;
762 $this->mCache[$code][$title] = '!NONEXISTENT';
763 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
764 }
765
766 return $message;
767 }
768
769 /**
770 * @param $message string
771 * @param $interface bool
772 * @param $language
773 * @param $title Title
774 * @return string
775 */
776 function transform( $message, $interface = false, $language = null, $title = null ) {
777 // Avoid creating parser if nothing to transform
778 if( strpos( $message, '{{' ) === false ) {
779 return $message;
780 }
781
782 if ( $this->mInParser ) {
783 return $message;
784 }
785
786 $parser = $this->getParser();
787 if ( $parser ) {
788 $popts = $this->getParserOptions();
789 $popts->setInterfaceMessage( $interface );
790 $popts->setTargetLanguage( $language );
791
792 $userlang = $popts->setUserLang( $language );
793 $this->mInParser = true;
794 $message = $parser->transformMsg( $message, $popts, $title );
795 $this->mInParser = false;
796 $popts->setUserLang( $userlang );
797 }
798 return $message;
799 }
800
801 /**
802 * @return Parser
803 */
804 function getParser() {
805 global $wgParser, $wgParserConf;
806 if ( !$this->mParser && isset( $wgParser ) ) {
807 # Do some initialisation so that we don't have to do it twice
808 $wgParser->firstCallInit();
809 # Clone it and store it
810 $class = $wgParserConf['class'];
811 if ( $class == 'Parser_DiffTest' ) {
812 # Uncloneable
813 $this->mParser = new $class( $wgParserConf );
814 } else {
815 $this->mParser = clone $wgParser;
816 }
817 }
818 return $this->mParser;
819 }
820
821 /**
822 * @param $text string
823 * @param $title Title
824 * @param $linestart bool
825 * @param $interface bool
826 * @param $language
827 * @return ParserOutput
828 */
829 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
830 if ( $this->mInParser ) {
831 return htmlspecialchars( $text );
832 }
833
834 $parser = $this->getParser();
835 $popts = $this->getParserOptions();
836
837 if ( $interface ) {
838 $popts->setInterfaceMessage( true );
839 }
840 if ( $language !== null ) {
841 $popts->setTargetLanguage( $language );
842 }
843
844 wfProfileIn( __METHOD__ );
845 if ( !$title || !$title instanceof Title ) {
846 global $wgTitle;
847 $title = $wgTitle;
848 }
849 // Sometimes $wgTitle isn't set either...
850 if ( !$title ) {
851 # It's not uncommon having a null $wgTitle in scripts. See r80898
852 # Create a ghost title in such case
853 $title = Title::newFromText( 'Dwimmerlaik' );
854 }
855
856 $this->mInParser = true;
857 $res = $parser->parse( $text, $title, $popts, $linestart );
858 $this->mInParser = false;
859
860 wfProfileOut( __METHOD__ );
861 return $res;
862 }
863
864 function disable() {
865 $this->mDisable = true;
866 }
867
868 function enable() {
869 $this->mDisable = false;
870 }
871
872 /**
873 * Clear all stored messages. Mainly used after a mass rebuild.
874 */
875 function clear() {
876 $langs = Language::getLanguageNames( false );
877 foreach ( array_keys($langs) as $code ) {
878 # Global cache
879 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
880 # Invalidate all local caches
881 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
882 }
883 $this->mLoadedLanguages = array();
884 }
885
886 /**
887 * @param $key
888 * @return array
889 */
890 public function figureMessage( $key ) {
891 global $wgLanguageCode;
892 $pieces = explode( '/', $key );
893 if( count( $pieces ) < 2 ) {
894 return array( $key, $wgLanguageCode );
895 }
896
897 $lang = array_pop( $pieces );
898 $validCodes = Language::getLanguageNames();
899 if( !array_key_exists( $lang, $validCodes ) ) {
900 return array( $key, $wgLanguageCode );
901 }
902
903 $message = implode( '/', $pieces );
904 return array( $message, $lang );
905 }
906
907 public static function logMessages() {
908 wfProfileIn( __METHOD__ );
909 global $wgAdaptiveMessageCache;
910 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
911 wfProfileOut( __METHOD__ );
912 return;
913 }
914
915 $cachekey = wfMemckey( 'message-profiling' );
916 $cache = wfGetCache( CACHE_DB );
917 $data = $cache->get( $cachekey );
918
919 if ( !$data ) {
920 $data = array();
921 }
922
923 $age = self::$mAdaptiveDataAge;
924 $filterDate = substr( wfTimestamp( TS_MW, time() - $age ), 0, 8 );
925 foreach ( array_keys( $data ) as $key ) {
926 if ( $key < $filterDate ) {
927 unset( $data[$key] );
928 }
929 }
930
931 $index = substr( wfTimestampNow(), 0, 8 );
932 if ( !isset( $data[$index] ) ) {
933 $data[$index] = array();
934 }
935
936 foreach ( self::$instance->mRequestedMessages as $message => $_ ) {
937 if ( !isset( $data[$index][$message] ) ) {
938 $data[$index][$message] = 0;
939 }
940 $data[$index][$message]++;
941 }
942
943 $cache->set( $cachekey, $data );
944 wfProfileOut( __METHOD__ );
945 }
946
947 /**
948 * @return array
949 */
950 public function getMostUsedMessages() {
951 wfProfileIn( __METHOD__ );
952 $cachekey = wfMemcKey( 'message-profiling' );
953 $cache = wfGetCache( CACHE_DB );
954 $data = $cache->get( $cachekey );
955 if ( !$data ) {
956 wfProfileOut( __METHOD__ );
957 return array();
958 }
959
960 $list = array();
961
962 foreach( $data as $messages ) {
963 foreach( $messages as $message => $count ) {
964 $key = $message;
965 if ( !isset( $list[$key] ) ) {
966 $list[$key] = 0;
967 }
968 $list[$key] += $count;
969 }
970 }
971
972 $max = max( $list );
973 foreach ( $list as $message => $count ) {
974 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
975 unset( $list[$message] );
976 }
977 }
978
979 wfProfileOut( __METHOD__ );
980 return array_keys( $list );
981 }
982
983 /**
984 * Get all message keys stored in the message cache for a given language.
985 * If $code is the content language code, this will return all message keys
986 * for which MediaWiki:msgkey exists. If $code is another language code, this
987 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
988 * @param $code string
989 * @return array of message keys (strings)
990 */
991 public function getAllMessageKeys( $code ) {
992 global $wgContLang;
993 $this->load( $code );
994 if ( !isset( $this->mCache[$code] ) ) {
995 // Apparently load() failed
996 return null;
997 }
998 $cache = $this->mCache[$code]; // Copy the cache
999 unset( $cache['VERSION'] ); // Remove the VERSION key
1000 $cache = array_diff( $cache, array( '!NONEXISTENT' ) ); // Remove any !NONEXISTENT keys
1001 // Keys may appear with a capital first letter. lcfirst them.
1002 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
1003 }
1004 }