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