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