(bug 24898) MediaWiki uses /tmp even if a vHost-specific tempdir is set, also make...
[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;
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 $messages = $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, $wgContLanguageCode, $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 !== $wgContLanguageCode ) {
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 !== $wgContLanguageCode ) {
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( , $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 wfRunHooks( "MessageCacheReplace", array( $title, $text ) );
456
457 wfProfileOut( __METHOD__ );
458 }
459
460 /**
461 * Shortcut to update caches.
462 *
463 * @param $cache Array: cached messages with a version.
464 * @param $memc Bool: Wether to update or not memcache.
465 * @param $code String: Language code.
466 * @return False on somekind of error.
467 */
468 protected function saveToCaches( $cache, $memc = true, $code = false ) {
469 wfProfileIn( __METHOD__ );
470 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
471
472 $cacheKey = wfMemcKey( 'messages', $code );
473
474 if ( $memc ) {
475 $success = $this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
476 } else {
477 $success = true;
478 }
479
480 # Save to local cache
481 if ( $wgUseLocalMessageCache ) {
482 $serialized = serialize( $cache );
483 $hash = md5( $serialized );
484 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
485 if ($wgLocalMessageCacheSerialized) {
486 $this->saveToLocal( $serialized, $hash, $code );
487 } else {
488 $this->saveToScript( $cache, $hash, $code );
489 }
490 }
491
492 wfProfileOut( __METHOD__ );
493 return $success;
494 }
495
496 /**
497 * Represents a write lock on the messages key
498 *
499 * @return Boolean: success
500 */
501 function lock($key) {
502 $lockKey = $key . ':lock';
503 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
504 sleep(1);
505 }
506
507 return $i >= MSG_WAIT_TIMEOUT;
508 }
509
510 function unlock($key) {
511 $lockKey = $key . ':lock';
512 $this->mMemc->delete( $lockKey );
513 }
514
515 /**
516 * Get a message from either the content language or the user language.
517 *
518 * @param $key String: the message cache key
519 * @param $useDB Boolean: get the message from the DB, false to use only
520 * the localisation
521 * @param $langcode String: code of the language to get the message for, if
522 * it is a valid code create a language for that language,
523 * if it is a string but not a valid code then make a basic
524 * language object, if it is a false boolean then use the
525 * current users language (as a fallback for the old
526 * parameter functionality), or if it is a true boolean
527 * then use the wikis content language (also as a
528 * fallback).
529 * @param $isFullKey Boolean: specifies whether $key is a two part key
530 * "msg/lang".
531 */
532 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
533 global $wgContLanguageCode, $wgContLang;
534
535 if ( !is_string( $key ) ) {
536 throw new MWException( "Non-string key given" );
537 }
538
539 if ( strval( $key ) === '' ) {
540 # Shortcut: the empty key is always missing
541 return false;
542 }
543
544 $lang = wfGetLangObj( $langcode );
545 $langcode = $lang->getCode();
546
547 $message = false;
548
549 # Normalise title-case input (with some inlining)
550 $lckey = str_replace( ' ', '_', $key );
551 if ( ord( $key ) < 128 ) {
552 $lckey[0] = strtolower( $lckey[0] );
553 $uckey = ucfirst( $lckey );
554 } else {
555 $lckey = $wgContLang->lcfirst( $lckey );
556 $uckey = $wgContLang->ucfirst( $lckey );
557 }
558
559 /* Record each message request, but only once per request.
560 * This information is not used unless $wgAdaptiveMessageCache
561 * is enabled. */
562 $this->mRequestedMessages[$uckey] = true;
563
564 # Try the MediaWiki namespace
565 if( !$this->mDisable && $useDB ) {
566 $title = $uckey;
567 if(!$isFullKey && ( $langcode != $wgContLanguageCode ) ) {
568 $title .= '/' . $langcode;
569 }
570 $message = $this->getMsgFromNamespace( $title, $langcode );
571 }
572
573 # Try the array in the language object
574 if ( $message === false ) {
575 $message = $lang->getMessage( $lckey );
576 if ( is_null( $message ) ) {
577 $message = false;
578 }
579 }
580
581 # Try the array of another language
582 if( $message === false ) {
583 $parts = explode( '/', $lckey );
584 # We may get calls for things that are http-urls from sidebar
585 # Let's not load nonexistent languages for those
586 # They usually have more than one slash.
587 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
588 $message = Language::getMessageFor( $parts[0], $parts[1] );
589 if ( is_null( $message ) ) {
590 $message = false;
591 }
592 }
593 }
594
595 # Is this a custom message? Try the default language in the db...
596 if( ($message === false || $message === '-' ) &&
597 !$this->mDisable && $useDB &&
598 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
599 $message = $this->getMsgFromNamespace( $uckey, $wgContLanguageCode );
600 }
601
602 # Final fallback
603 if( $message === false ) {
604 return false;
605 }
606
607 # Fix whitespace
608 $message = strtr( $message,
609 array(
610 # Fix for trailing whitespace, removed by textarea
611 '&#32;' => ' ',
612 # Fix for NBSP, converted to space by firefox
613 '&nbsp;' => "\xc2\xa0",
614 '&#160;' => "\xc2\xa0",
615 ) );
616
617 return $message;
618 }
619
620 /**
621 * Get a message from the MediaWiki namespace, with caching. The key must
622 * first be converted to two-part lang/msg form if necessary.
623 *
624 * @param $title String: Message cache key with initial uppercase letter.
625 * @param $code String: code denoting the language to try.
626 */
627 function getMsgFromNamespace( $title, $code ) {
628 global $wgAdaptiveMessageCache;
629 $big = false;
630
631 $this->load( $code );
632 if ( isset( $this->mCache[$code][$title] ) ) {
633 $entry = $this->mCache[$code][$title];
634 if ( substr( $entry, 0, 1 ) === ' ' ) {
635 return substr( $entry, 1 );
636 } elseif ( $entry === '!NONEXISTENT' ) {
637 return false;
638 } elseif( $entry === '!TOO BIG' ) {
639 // Fall through and try invididual message cache below
640
641 } else {
642 // XXX: This is not cached in process cache, should it?
643 $message = false;
644 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
645 if ( $message !== false ) {
646 return $message;
647 }
648
649 /* If message cache is in normal mode, it is guaranteed
650 * (except bugs) that there is always entry (or placeholder)
651 * in the cache if message exists. Thus we can do minor
652 * performance improvement and return false early.
653 */
654 if ( !$wgAdaptiveMessageCache ) {
655 return false;
656 }
657 }
658 }
659
660 # Try the individual message cache
661 $titleKey = wfMemcKey( 'messages', 'individual', $title );
662 $entry = $this->mMemc->get( $titleKey );
663 if ( $entry ) {
664 if ( substr( $entry, 0, 1 ) === ' ' ) {
665 $this->mCache[$code][$title] = $entry;
666 return substr( $entry, 1 );
667 } elseif ( $entry === '!NONEXISTENT' ) {
668 $this->mCache[$code][$title] = '!NONEXISTENT';
669 return false;
670 } else {
671 # Corrupt/obsolete entry, delete it
672 $this->mMemc->delete( $titleKey );
673 }
674 }
675
676 # Try loading it from the database
677 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
678 if ( $revision ) {
679 $message = $revision->getText();
680 $this->mCache[$code][$title] = ' ' . $message;
681 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
682 } else {
683 $message = false;
684 $this->mCache[$code][$title] = '!NONEXISTENT';
685 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
686 }
687
688 return $message;
689 }
690
691 function transform( $message, $interface = false, $language = null ) {
692 // Avoid creating parser if nothing to transform
693 if( strpos( $message, '{{' ) === false ) {
694 return $message;
695 }
696
697 global $wgParser, $wgParserConf;
698 if ( !$this->mParser && isset( $wgParser ) ) {
699 # Do some initialisation so that we don't have to do it twice
700 $wgParser->firstCallInit();
701 # Clone it and store it
702 $class = $wgParserConf['class'];
703 if ( $class == 'Parser_DiffTest' ) {
704 # Uncloneable
705 $this->mParser = new $class( $wgParserConf );
706 } else {
707 $this->mParser = clone $wgParser;
708 }
709 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
710 }
711 if ( $this->mParser ) {
712 $popts = $this->getParserOptions();
713 $popts->setInterfaceMessage( $interface );
714 $popts->setTargetLanguage( $language );
715 $message = $this->mParser->transformMsg( $message, $popts );
716 }
717 return $message;
718 }
719
720 function disable() { $this->mDisable = true; }
721 function enable() { $this->mDisable = false; }
722
723 /** @deprecated */
724 function disableTransform(){
725 wfDeprecated( __METHOD__ );
726 }
727 function enableTransform() {
728 wfDeprecated( __METHOD__ );
729 }
730 function setTransform( $x ) {
731 wfDeprecated( __METHOD__ );
732 }
733 function getTransform() {
734 wfDeprecated( __METHOD__ );
735 return false;
736 }
737
738 /**
739 * Clear all stored messages. Mainly used after a mass rebuild.
740 */
741 function clear() {
742 $langs = Language::getLanguageNames( false );
743 foreach ( array_keys($langs) as $code ) {
744 # Global cache
745 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
746 # Invalidate all local caches
747 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
748 }
749 }
750
751 /**
752 * Add a message to the cache
753 * @deprecated Use $wgExtensionMessagesFiles
754 *
755 * @param $key Mixed
756 * @param $value Mixed
757 * @param $lang String: the messages language, English by default
758 */
759 function addMessage( $key, $value, $lang = 'en' ) {
760 wfDeprecated( __METHOD__ );
761 $lc = Language::getLocalisationCache();
762 $lc->addLegacyMessages( array( $lang => array( $key => $value ) ) );
763 }
764
765 /**
766 * Add an associative array of message to the cache
767 * @deprecated Use $wgExtensionMessagesFiles
768 *
769 * @param $messages Array: an associative array of key => values to be added
770 * @param $lang String: the messages language, English by default
771 */
772 function addMessages( $messages, $lang = 'en' ) {
773 wfDeprecated( __METHOD__ );
774 $lc = Language::getLocalisationCache();
775 $lc->addLegacyMessages( array( $lang => $messages ) );
776 }
777
778 /**
779 * Add a 2-D array of messages by lang. Useful for extensions.
780 * @deprecated Use $wgExtensionMessagesFiles
781 *
782 * @param $messages Array: the array to be added
783 */
784 function addMessagesByLang( $messages ) {
785 wfDeprecated( __METHOD__ );
786 $lc = Language::getLocalisationCache();
787 $lc->addLegacyMessages( $messages );
788 }
789
790 /**
791 * Set a hook for addMessagesByLang()
792 */
793 function setExtensionMessagesHook( $callback ) {
794 $this->mAddMessagesHook = $callback;
795 }
796
797 /**
798 * @deprecated
799 */
800 function loadAllMessages( $lang = false ) {
801 }
802
803 /**
804 * @deprecated
805 */
806 function loadMessagesFile( $filename, $langcode = false ) {
807 }
808
809 public function figureMessage( $key ) {
810 global $wgContLanguageCode;
811 $pieces = explode( '/', $key );
812 if( count( $pieces ) < 2 )
813 return array( $key, $wgContLanguageCode );
814
815 $lang = array_pop( $pieces );
816 $validCodes = Language::getLanguageNames();
817 if( !array_key_exists( $lang, $validCodes ) )
818 return array( $key, $wgContLanguageCode );
819
820 $message = implode( '/', $pieces );
821 return array( $message, $lang );
822 }
823
824 public static function logMessages() {
825 global $wgMessageCache, $wgAdaptiveMessageCache;
826 if ( !$wgAdaptiveMessageCache || !$wgMessageCache instanceof MessageCache ) {
827 return;
828 }
829
830 $cachekey = wfMemckey( 'message-profiling' );
831 $cache = wfGetCache( CACHE_DB );
832 $data = $cache->get( $cachekey );
833
834 if ( !$data ) $data = array();
835
836 $age = self::$mAdaptiveDataAge;
837 $filterDate = substr( wfTimestamp( TS_MW, time()-$age ), 0, 8 );
838 foreach ( array_keys( $data ) as $key ) {
839 if ( $key < $filterDate ) unset( $data[$key] );
840 }
841
842 $index = substr( wfTimestampNow(), 0, 8 );
843 if ( !isset( $data[$index] ) ) $data[$index] = array();
844
845 foreach ( $wgMessageCache->mRequestedMessages as $message => $_ ) {
846 if ( !isset( $data[$index][$message] ) ) $data[$index][$message] = 0;
847 $data[$index][$message]++;
848 }
849
850 $cache->set( $cachekey, $data );
851 }
852
853 public function getMostUsedMessages() {
854 $cachekey = wfMemckey( 'message-profiling' );
855 $cache = wfGetCache( CACHE_DB );
856 $data = $cache->get( $cachekey );
857 if ( !$data ) return array();
858
859 $list = array();
860
861 foreach( $data as $date => $messages ) {
862 foreach( $messages as $message => $count ) {
863 $key = $message;
864 if ( !isset( $list[$key] ) ) $list[$key] = 0;
865 $list[$key] += $count;
866 }
867 }
868
869 $max = max( $list );
870 foreach ( $list as $message => $count ) {
871 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
872 unset( $list[$message] );
873 }
874 }
875
876 return array_keys( $list );
877 }
878
879 }