Merge "Replace deprecated call."
[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 bool|string $langcode 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 * @throws MWException
611 * @return string|bool
612 */
613 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
614 global $wgLanguageCode, $wgContLang;
615
616 if ( is_int( $key ) ) {
617 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
618 $key = strval( $key );
619 }
620
621 if ( !is_string( $key ) ) {
622 throw new MWException( 'Non-string key given' );
623 }
624
625 if ( strval( $key ) === '' ) {
626 # Shortcut: the empty key is always missing
627 return false;
628 }
629
630 $lang = wfGetLangObj( $langcode );
631 if ( !$lang ) {
632 throw new MWException( "Bad lang code $langcode given" );
633 }
634
635 $langcode = $lang->getCode();
636
637 $message = false;
638
639 # Normalise title-case input (with some inlining)
640 $lckey = str_replace( ' ', '_', $key );
641 if ( ord( $key ) < 128 ) {
642 $lckey[0] = strtolower( $lckey[0] );
643 $uckey = ucfirst( $lckey );
644 } else {
645 $lckey = $wgContLang->lcfirst( $lckey );
646 $uckey = $wgContLang->ucfirst( $lckey );
647 }
648
649 /**
650 * Record each message request, but only once per request.
651 * This information is not used unless $wgAdaptiveMessageCache
652 * is enabled.
653 */
654 $this->mRequestedMessages[$uckey] = true;
655
656 # Try the MediaWiki namespace
657 if( !$this->mDisable && $useDB ) {
658 $title = $uckey;
659 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
660 $title .= '/' . $langcode;
661 }
662 $message = $this->getMsgFromNamespace( $title, $langcode );
663 }
664
665 # Try the array in the language object
666 if ( $message === false ) {
667 $message = $lang->getMessage( $lckey );
668 if ( is_null( $message ) ) {
669 $message = false;
670 }
671 }
672
673 # Try the array of another language
674 if( $message === false ) {
675 $parts = explode( '/', $lckey );
676 # We may get calls for things that are http-urls from sidebar
677 # Let's not load nonexistent languages for those
678 # They usually have more than one slash.
679 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
680 $message = Language::getMessageFor( $parts[0], $parts[1] );
681 if ( is_null( $message ) ) {
682 $message = false;
683 }
684 }
685 }
686
687 # Is this a custom message? Try the default language in the db...
688 if( ( $message === false || $message === '-' ) &&
689 !$this->mDisable && $useDB &&
690 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
691 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
692 }
693
694 # Final fallback
695 if( $message === false ) {
696 return false;
697 }
698
699 # Fix whitespace
700 $message = strtr( $message,
701 array(
702 # Fix for trailing whitespace, removed by textarea
703 '&#32;' => ' ',
704 # Fix for NBSP, converted to space by firefox
705 '&nbsp;' => "\xc2\xa0",
706 '&#160;' => "\xc2\xa0",
707 ) );
708
709 return $message;
710 }
711
712 /**
713 * Get a message from the MediaWiki namespace, with caching. The key must
714 * first be converted to two-part lang/msg form if necessary.
715 *
716 * @param $title String: Message cache key with initial uppercase letter.
717 * @param $code String: code denoting the language to try.
718 *
719 * @return string|bool False on failure
720 */
721 function getMsgFromNamespace( $title, $code ) {
722 global $wgAdaptiveMessageCache;
723
724 $this->load( $code );
725 if ( isset( $this->mCache[$code][$title] ) ) {
726 $entry = $this->mCache[$code][$title];
727 if ( substr( $entry, 0, 1 ) === ' ' ) {
728 return substr( $entry, 1 );
729 } elseif ( $entry === '!NONEXISTENT' ) {
730 return false;
731 } elseif( $entry === '!TOO BIG' ) {
732 // Fall through and try invididual message cache below
733 }
734 } else {
735 // XXX: This is not cached in process cache, should it?
736 $message = false;
737 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
738 if ( $message !== false ) {
739 return $message;
740 }
741
742 /**
743 * If message cache is in normal mode, it is guaranteed
744 * (except bugs) that there is always entry (or placeholder)
745 * in the cache if message exists. Thus we can do minor
746 * performance improvement and return false early.
747 */
748 if ( !$wgAdaptiveMessageCache ) {
749 return false;
750 }
751 }
752
753 # Try the individual message cache
754 $titleKey = wfMemcKey( 'messages', 'individual', $title );
755 $entry = $this->mMemc->get( $titleKey );
756 if ( $entry ) {
757 if ( substr( $entry, 0, 1 ) === ' ' ) {
758 $this->mCache[$code][$title] = $entry;
759 return substr( $entry, 1 );
760 } elseif ( $entry === '!NONEXISTENT' ) {
761 $this->mCache[$code][$title] = '!NONEXISTENT';
762 return false;
763 } else {
764 # Corrupt/obsolete entry, delete it
765 $this->mMemc->delete( $titleKey );
766 }
767 }
768
769 # Try loading it from the database
770 $revision = Revision::newFromTitle(
771 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
772 );
773 if ( $revision ) {
774 $content = $revision->getContent();
775 if ( !$content ) {
776 // A possibly temporary loading failure.
777 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$title} ($code)" );
778 $message = null; // no negative caching
779 } else {
780 // XXX: Is this the right way to turn a Content object into a message?
781 // NOTE: $content is typically either WikitextContent, JavaScriptContent or CssContent.
782 // MessageContent is *not* used for storing messages, it's only used for wrapping them when needed.
783 $message = $content->getWikitextForTransclusion();
784
785 if ( $message === false || $message === null ) {
786 wfDebugLog( 'MessageCache', __METHOD__ . ": message content doesn't provide wikitext "
787 . "(content model: " . $content->getContentHandler() . ")" );
788
789 $message = false; // negative caching
790 } else {
791 $this->mCache[$code][$title] = ' ' . $message;
792 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
793 }
794 }
795 } else {
796 $message = false; // negative caching
797 }
798
799 if ( $message === false ) { // negative caching
800 $this->mCache[$code][$title] = '!NONEXISTENT';
801 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
802 }
803
804 return $message;
805 }
806
807 /**
808 * @param $message string
809 * @param $interface bool
810 * @param $language
811 * @param $title Title
812 * @return string
813 */
814 function transform( $message, $interface = false, $language = null, $title = null ) {
815 // Avoid creating parser if nothing to transform
816 if( strpos( $message, '{{' ) === false ) {
817 return $message;
818 }
819
820 if ( $this->mInParser ) {
821 return $message;
822 }
823
824 $parser = $this->getParser();
825 if ( $parser ) {
826 $popts = $this->getParserOptions();
827 $popts->setInterfaceMessage( $interface );
828 $popts->setTargetLanguage( $language );
829
830 $userlang = $popts->setUserLang( $language );
831 $this->mInParser = true;
832 $message = $parser->transformMsg( $message, $popts, $title );
833 $this->mInParser = false;
834 $popts->setUserLang( $userlang );
835 }
836 return $message;
837 }
838
839 /**
840 * @return Parser
841 */
842 function getParser() {
843 global $wgParser, $wgParserConf;
844 if ( !$this->mParser && isset( $wgParser ) ) {
845 # Do some initialisation so that we don't have to do it twice
846 $wgParser->firstCallInit();
847 # Clone it and store it
848 $class = $wgParserConf['class'];
849 if ( $class == 'Parser_DiffTest' ) {
850 # Uncloneable
851 $this->mParser = new $class( $wgParserConf );
852 } else {
853 $this->mParser = clone $wgParser;
854 }
855 }
856 return $this->mParser;
857 }
858
859 /**
860 * @param $text string
861 * @param $title Title
862 * @param $linestart bool
863 * @param $interface bool
864 * @param $language
865 * @return ParserOutput
866 */
867 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
868 if ( $this->mInParser ) {
869 return htmlspecialchars( $text );
870 }
871
872 $parser = $this->getParser();
873 $popts = $this->getParserOptions();
874 $popts->setInterfaceMessage( $interface );
875 $popts->setTargetLanguage( $language );
876
877 wfProfileIn( __METHOD__ );
878 if ( !$title || !$title instanceof Title ) {
879 global $wgTitle;
880 $title = $wgTitle;
881 }
882 // Sometimes $wgTitle isn't set either...
883 if ( !$title ) {
884 # It's not uncommon having a null $wgTitle in scripts. See r80898
885 # Create a ghost title in such case
886 $title = Title::newFromText( 'Dwimmerlaik' );
887 }
888
889 $this->mInParser = true;
890 $res = $parser->parse( $text, $title, $popts, $linestart );
891 $this->mInParser = false;
892
893 wfProfileOut( __METHOD__ );
894 return $res;
895 }
896
897 function disable() {
898 $this->mDisable = true;
899 }
900
901 function enable() {
902 $this->mDisable = false;
903 }
904
905 /**
906 * Clear all stored messages. Mainly used after a mass rebuild.
907 */
908 function clear() {
909 $langs = Language::fetchLanguageNames( null, 'mw' );
910 foreach ( array_keys($langs) as $code ) {
911 # Global cache
912 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
913 # Invalidate all local caches
914 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
915 }
916 $this->mLoadedLanguages = array();
917 }
918
919 /**
920 * @param $key
921 * @return array
922 */
923 public function figureMessage( $key ) {
924 global $wgLanguageCode;
925 $pieces = explode( '/', $key );
926 if( count( $pieces ) < 2 ) {
927 return array( $key, $wgLanguageCode );
928 }
929
930 $lang = array_pop( $pieces );
931 if( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
932 return array( $key, $wgLanguageCode );
933 }
934
935 $message = implode( '/', $pieces );
936 return array( $message, $lang );
937 }
938
939 public static function logMessages() {
940 wfProfileIn( __METHOD__ );
941 global $wgAdaptiveMessageCache;
942 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
943 wfProfileOut( __METHOD__ );
944 return;
945 }
946
947 $cachekey = wfMemckey( 'message-profiling' );
948 $cache = wfGetCache( CACHE_DB );
949 $data = $cache->get( $cachekey );
950
951 if ( !$data ) {
952 $data = array();
953 }
954
955 $age = self::$mAdaptiveDataAge;
956 $filterDate = substr( wfTimestamp( TS_MW, time() - $age ), 0, 8 );
957 foreach ( array_keys( $data ) as $key ) {
958 if ( $key < $filterDate ) {
959 unset( $data[$key] );
960 }
961 }
962
963 $index = substr( wfTimestampNow(), 0, 8 );
964 if ( !isset( $data[$index] ) ) {
965 $data[$index] = array();
966 }
967
968 foreach ( self::$instance->mRequestedMessages as $message => $_ ) {
969 if ( !isset( $data[$index][$message] ) ) {
970 $data[$index][$message] = 0;
971 }
972 $data[$index][$message]++;
973 }
974
975 $cache->set( $cachekey, $data );
976 wfProfileOut( __METHOD__ );
977 }
978
979 /**
980 * @return array
981 */
982 public function getMostUsedMessages() {
983 wfProfileIn( __METHOD__ );
984 $cachekey = wfMemcKey( 'message-profiling' );
985 $cache = wfGetCache( CACHE_DB );
986 $data = $cache->get( $cachekey );
987 if ( !$data ) {
988 wfProfileOut( __METHOD__ );
989 return array();
990 }
991
992 $list = array();
993
994 foreach( $data as $messages ) {
995 foreach( $messages as $message => $count ) {
996 $key = $message;
997 if ( !isset( $list[$key] ) ) {
998 $list[$key] = 0;
999 }
1000 $list[$key] += $count;
1001 }
1002 }
1003
1004 $max = max( $list );
1005 foreach ( $list as $message => $count ) {
1006 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
1007 unset( $list[$message] );
1008 }
1009 }
1010
1011 wfProfileOut( __METHOD__ );
1012 return array_keys( $list );
1013 }
1014
1015 /**
1016 * Get all message keys stored in the message cache for a given language.
1017 * If $code is the content language code, this will return all message keys
1018 * for which MediaWiki:msgkey exists. If $code is another language code, this
1019 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1020 * @param $code string
1021 * @return array of message keys (strings)
1022 */
1023 public function getAllMessageKeys( $code ) {
1024 global $wgContLang;
1025 $this->load( $code );
1026 if ( !isset( $this->mCache[$code] ) ) {
1027 // Apparently load() failed
1028 return null;
1029 }
1030 $cache = $this->mCache[$code]; // Copy the cache
1031 unset( $cache['VERSION'] ); // Remove the VERSION key
1032 $cache = array_diff( $cache, array( '!NONEXISTENT' ) ); // Remove any !NONEXISTENT keys
1033 // Keys may appear with a capital first letter. lcfirst them.
1034 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
1035 }
1036 }