8c1a06813db1f0baad42fb92a604468016a23456
[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', 30 );
29 define( 'MSG_WAIT_TIMEOUT', 30 );
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 * Singleton instance
64 *
65 * @var MessageCache
66 */
67 private static $instance;
68
69 /**
70 * @var bool
71 */
72 protected $mInParser = false;
73
74 /**
75 * Get the signleton instance of this class
76 *
77 * @since 1.18
78 * @return MessageCache object
79 */
80 public static function singleton() {
81 if ( is_null( self::$instance ) ) {
82 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
83 self::$instance = new self( wfGetMessageCacheStorage(), $wgUseDatabaseMessages, $wgMsgCacheExpiry );
84 }
85 return self::$instance;
86 }
87
88 /**
89 * Destroy the singleton instance
90 *
91 * @since 1.18
92 */
93 public static function destroyInstance() {
94 self::$instance = null;
95 }
96
97 function __construct( $memCached, $useDB, $expiry ) {
98 if ( !$memCached ) {
99 $memCached = wfGetCache( CACHE_NONE );
100 }
101
102 $this->mMemc = $memCached;
103 $this->mDisable = !$useDB;
104 $this->mExpiry = $expiry;
105 }
106
107 /**
108 * ParserOptions is lazy initialised.
109 *
110 * @return ParserOptions
111 */
112 function getParserOptions() {
113 if ( !$this->mParserOptions ) {
114 $this->mParserOptions = new ParserOptions;
115 $this->mParserOptions->setEditSection( false );
116 }
117 return $this->mParserOptions;
118 }
119
120 /**
121 * Try to load the cache from a local file.
122 *
123 * @param string $hash the hash of contents, to check validity.
124 * @param $code Mixed: Optional language code, see documenation of load().
125 * @return The cache array
126 */
127 function getLocalCache( $hash, $code ) {
128 global $wgCacheDirectory;
129
130 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
131
132 # Check file existence
133 wfSuppressWarnings();
134 $file = fopen( $filename, 'r' );
135 wfRestoreWarnings();
136 if ( !$file ) {
137 return false; // No cache file
138 }
139
140 // Check to see if the file has the hash specified
141 $localHash = fread( $file, 32 );
142 if ( $hash === $localHash ) {
143 // All good, get the rest of it
144 $serialized = '';
145 while ( !feof( $file ) ) {
146 $serialized .= fread( $file, 100000 );
147 }
148 fclose( $file );
149 return unserialize( $serialized );
150 } else {
151 fclose( $file );
152 return false; // Wrong hash
153 }
154 }
155
156 /**
157 * Save the cache to a local file.
158 */
159 function saveToLocal( $serialized, $hash, $code ) {
160 global $wgCacheDirectory;
161
162 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
163 wfMkdirParents( $wgCacheDirectory, null, __METHOD__ ); // might fail
164
165 wfSuppressWarnings();
166 $file = fopen( $filename, 'w' );
167 wfRestoreWarnings();
168
169 if ( !$file ) {
170 wfDebug( "Unable to open local cache file for writing\n" );
171 return;
172 }
173
174 fwrite( $file, $hash . $serialized );
175 fclose( $file );
176 wfSuppressWarnings();
177 chmod( $filename, 0666 );
178 wfRestoreWarnings();
179 }
180
181 /**
182 * Loads messages from caches or from database in this order:
183 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
184 * (2) memcached
185 * (3) from the database.
186 *
187 * When succesfully loading from (2) or (3), all higher level caches are
188 * updated for the newest version.
189 *
190 * Nothing is loaded if member variable mDisable is true, either manually
191 * set by calling code or if message loading fails (is this possible?).
192 *
193 * Returns true if cache is already populated or it was succesfully populated,
194 * or false if populating empty cache fails. Also returns true if MessageCache
195 * is disabled.
196 *
197 * @param bool|String $code String: language to which load messages
198 * @throws MWException
199 * @return bool
200 */
201 function load( $code = false ) {
202 global $wgUseLocalMessageCache;
203
204 if( !is_string( $code ) ) {
205 # This isn't really nice, so at least make a note about it and try to
206 # fall back
207 wfDebug( __METHOD__ . " called without providing a language code\n" );
208 $code = 'en';
209 }
210
211 # Don't do double loading...
212 if ( isset( $this->mLoadedLanguages[$code] ) ) {
213 return true;
214 }
215
216 # 8 lines of code just to say (once) that message cache is disabled
217 if ( $this->mDisable ) {
218 static $shownDisabled = false;
219 if ( !$shownDisabled ) {
220 wfDebug( __METHOD__ . ": disabled\n" );
221 $shownDisabled = true;
222 }
223 return true;
224 }
225
226 # Loading code starts
227 wfProfileIn( __METHOD__ );
228 $success = false; # Keep track of success
229 $staleCache = false; # a cache array with expired data, or false if none has been loaded
230 $where = array(); # Debug info, delayed to avoid spamming debug log too much
231 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
232
233 # Local cache
234 # Hash of the contents is stored in memcache, to detect if local cache goes
235 # out of date (e.g. due to replace() on some other server)
236 if ( $wgUseLocalMessageCache ) {
237 wfProfileIn( __METHOD__ . '-fromlocal' );
238
239 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
240 if ( $hash ) {
241 $cache = $this->getLocalCache( $hash, $code );
242 if ( !$cache ) {
243 $where[] = 'local cache is empty or has the wrong hash';
244 } elseif ( $this->isCacheExpired( $cache ) ) {
245 $where[] = 'local cache is expired';
246 $staleCache = $cache;
247 } else {
248 $where[] = 'got from local cache';
249 $success = true;
250 $this->mCache[$code] = $cache;
251 }
252 }
253 wfProfileOut( __METHOD__ . '-fromlocal' );
254 }
255
256 if ( !$success ) {
257 # Try the global cache. If it is empty, try to acquire a lock. If
258 # the lock can't be acquired, wait for the other thread to finish
259 # and then try the global cache a second time.
260 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++ ) {
261 wfProfileIn( __METHOD__ . '-fromcache' );
262 $cache = $this->mMemc->get( $cacheKey );
263 if ( !$cache ) {
264 $where[] = 'global cache is empty';
265 } elseif ( $this->isCacheExpired( $cache ) ) {
266 $where[] = 'global cache is expired';
267 $staleCache = $cache;
268 } else {
269 $where[] = 'got from global cache';
270 $this->mCache[$code] = $cache;
271 $this->saveToCaches( $cache, 'local-only', $code );
272 $success = true;
273 }
274
275 wfProfileOut( __METHOD__ . '-fromcache' );
276
277 if ( $success ) {
278 # Done, no need to retry
279 break;
280 }
281
282 # We need to call loadFromDB. Limit the concurrency to a single
283 # process. This prevents the site from going down when the cache
284 # expires.
285 $statusKey = wfMemcKey( 'messages', $code, 'status' );
286 $acquired = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
287 if ( $acquired ) {
288 # Unlock the status key if there is an exception
289 $that = $this;
290 $statusUnlocker = new ScopedCallback( function() use ( $that, $statusKey ) {
291 $that->mMemc->delete( $statusKey );
292 } );
293
294 # Now let's regenerate
295 $where[] = 'loading from database';
296
297 # Lock the cache to prevent conflicting writes
298 # If this lock fails, it doesn't really matter, it just means the
299 # write is potentially non-atomic, e.g. the results of a replace()
300 # may be discarded.
301 if ( $this->lock( $cacheKey ) ) {
302 $mainUnlocker = new ScopedCallback( function() use ( $that, $cacheKey ) {
303 $that->unlock( $cacheKey );
304 } );
305 } else {
306 $mainUnlocker = null;
307 $where[] = 'could not acquire main lock';
308 }
309
310 $cache = $this->loadFromDB( $code );
311 $this->mCache[$code] = $cache;
312 $success = true;
313 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
314
315 # Unlock
316 ScopedCallback::consume( $mainUnlocker );
317 ScopedCallback::consume( $statusUnlocker );
318
319 if ( !$saveSuccess ) {
320 # Cache save has failed.
321 # There are two main scenarios where this could be a problem:
322 #
323 # - The cache is more than the maximum size (typically
324 # 1MB compressed).
325 #
326 # - Memcached has no space remaining in the relevant slab
327 # class. This is unlikely with recent versions of
328 # memcached.
329 #
330 # Either way, if there is a local cache, nothing bad will
331 # happen. If there is no local cache, disabling the message
332 # cache for all requests avoids incurring a loadFromDB()
333 # overhead on every request, and thus saves the wiki from
334 # complete downtime under moderate traffic conditions.
335 if ( !$wgUseLocalMessageCache ) {
336 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
337 $where[] = 'could not save cache, disabled globally for 5 minutes';
338 } else {
339 $where[] = "could not save global cache";
340 }
341 }
342
343 # Load from DB complete, no need to retry
344 break;
345 } elseif ( $staleCache ) {
346 # Use the stale cache while some other thread constructs the new one
347 $where[] = 'using stale cache';
348 $this->mCache[$code] = $staleCache;
349 $success = true;
350 break;
351 } elseif ( $failedAttempts > 0 ) {
352 # Already retried once, still failed, so don't do another lock/unlock cycle
353 # This case will typically be hit if memcached is down, or if
354 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
355 $where[] = "could not acquire status key.";
356 break;
357 } else {
358 $status = $this->mMemc->get( $statusKey );
359 if ( $status === 'error' ) {
360 # Disable cache
361 break;
362 } else {
363 # Wait for the other thread to finish, then retry
364 $where[] = 'waited for other thread to complete';
365 $this->lock( $cacheKey );
366 $this->unlock( $cacheKey );
367 }
368 }
369 }
370 }
371
372 if ( !$success ) {
373 $where[] = 'loading FAILED - cache is disabled';
374 $this->mDisable = true;
375 $this->mCache = false;
376 # This used to throw an exception, but that led to nasty side effects like
377 # the whole wiki being instantly down if the memcached server died
378 } else {
379 # All good, just record the success
380 $this->mLoadedLanguages[$code] = true;
381 }
382 $info = implode( ', ', $where );
383 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
384 wfProfileOut( __METHOD__ );
385 return $success;
386 }
387
388 /**
389 * Loads cacheable messages from the database. Messages bigger than
390 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
391 * on-demand from the database later.
392 *
393 * @param string $code language code.
394 * @return Array: loaded messages for storing in caches.
395 */
396 function loadFromDB( $code ) {
397 wfProfileIn( __METHOD__ );
398 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
399 $dbr = wfGetDB( DB_SLAVE );
400 $cache = array();
401
402 # Common conditions
403 $conds = array(
404 'page_is_redirect' => 0,
405 'page_namespace' => NS_MEDIAWIKI,
406 );
407
408 $mostused = array();
409 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
410 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
411 $this->load( $wgLanguageCode );
412 }
413 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
414 foreach ( $mostused as $key => $value ) {
415 $mostused[$key] = "$value/$code";
416 }
417 }
418
419 if ( count( $mostused ) ) {
420 $conds['page_title'] = $mostused;
421 } elseif ( $code !== $wgLanguageCode ) {
422 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
423 } else {
424 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
425 # other than language code.
426 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
427 }
428
429 # Conditions to fetch oversized pages to ignore them
430 $bigConds = $conds;
431 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
432
433 # Load titles for all oversized pages in the MediaWiki namespace
434 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
435 foreach ( $res as $row ) {
436 $cache[$row->page_title] = '!TOO BIG';
437 }
438
439 # Conditions to load the remaining pages with their contents
440 $smallConds = $conds;
441 $smallConds[] = 'page_latest=rev_id';
442 $smallConds[] = 'rev_text_id=old_id';
443 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
444
445 $res = $dbr->select(
446 array( 'page', 'revision', 'text' ),
447 array( 'page_title', 'old_text', 'old_flags' ),
448 $smallConds,
449 __METHOD__ . "($code)-small"
450 );
451
452 foreach ( $res as $row ) {
453 $text = Revision::getRevisionText( $row );
454 if( $text === false ) {
455 // Failed to fetch data; possible ES errors?
456 // Store a marker to fetch on-demand as a workaround...
457 $entry = '!TOO BIG';
458 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$row->page_title} ($code)" );
459 } else {
460 $entry = ' ' . $text;
461 }
462 $cache[$row->page_title] = $entry;
463 }
464
465 $cache['VERSION'] = MSG_CACHE_VERSION;
466 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
467 wfProfileOut( __METHOD__ );
468 return $cache;
469 }
470
471 /**
472 * Updates cache as necessary when message page is changed
473 *
474 * @param string $title name of the page changed.
475 * @param $text Mixed: new contents of the page.
476 */
477 public function replace( $title, $text ) {
478 global $wgMaxMsgCacheEntrySize;
479 wfProfileIn( __METHOD__ );
480
481 if ( $this->mDisable ) {
482 wfProfileOut( __METHOD__ );
483 return;
484 }
485
486 list( $msg, $code ) = $this->figureMessage( $title );
487
488 $cacheKey = wfMemcKey( 'messages', $code );
489 $this->load( $code );
490 $this->lock( $cacheKey );
491
492 $titleKey = wfMemcKey( 'messages', 'individual', $title );
493
494 if ( $text === false ) {
495 # Article was deleted
496 $this->mCache[$code][$title] = '!NONEXISTENT';
497 $this->mMemc->delete( $titleKey );
498 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
499 # Check for size
500 $this->mCache[$code][$title] = '!TOO BIG';
501 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
502 } else {
503 $this->mCache[$code][$title] = ' ' . $text;
504 $this->mMemc->delete( $titleKey );
505 }
506
507 # Update caches
508 $this->saveToCaches( $this->mCache[$code], 'all', $code );
509 $this->unlock( $cacheKey );
510
511 // Also delete cached sidebar... just in case it is affected
512 $codes = array( $code );
513 if ( $code === 'en' ) {
514 // Delete all sidebars, like for example on action=purge on the
515 // sidebar messages
516 $codes = array_keys( Language::fetchLanguageNames() );
517 }
518
519 global $wgMemc;
520 foreach ( $codes as $code ) {
521 $sidebarKey = wfMemcKey( 'sidebar', $code );
522 $wgMemc->delete( $sidebarKey );
523 }
524
525 // Update the message in the message blob store
526 global $wgContLang;
527 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
528
529 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
530
531 wfProfileOut( __METHOD__ );
532 }
533
534 /**
535 * Is the given cache array expired due to time passing or a version change?
536 */
537 protected function isCacheExpired( $cache ) {
538 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
539 return true;
540 }
541 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
542 return true;
543 }
544 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
545 return true;
546 }
547 return false;
548 }
549
550
551 /**
552 * Shortcut to update caches.
553 *
554 * @param $cache array: cached messages with a version.
555 * @param $dest string: Either "local-only" to save to local caches only
556 * or "all" to save to all caches.
557 * @param $code string: Language code.
558 * @return bool on somekind of error.
559 */
560 protected function saveToCaches( $cache, $dest, $code = false ) {
561 wfProfileIn( __METHOD__ );
562 global $wgUseLocalMessageCache;
563
564 $cacheKey = wfMemcKey( 'messages', $code );
565
566 if ( $dest === 'all' ) {
567 $success = $this->mMemc->set( $cacheKey, $cache );
568 } else {
569 $success = true;
570 }
571
572 # Save to local cache
573 if ( $wgUseLocalMessageCache ) {
574 $serialized = serialize( $cache );
575 $hash = md5( $serialized );
576 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
577 $this->saveToLocal( $serialized, $hash, $code );
578 }
579
580 wfProfileOut( __METHOD__ );
581 return $success;
582 }
583
584 /**
585 * Represents a write lock on the messages key
586 *
587 * @param $key string
588 *
589 * @return Boolean: success
590 */
591 function lock( $key ) {
592 $lockKey = $key . ':lock';
593 $acquired = false;
594 $testDone = false;
595 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
596 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
597 if ( $acquired ) {
598 break;
599 }
600
601 # Fail fast if memcached is totally down
602 if ( !$testDone ) {
603 $testDone = true;
604 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
605 break;
606 }
607 }
608 sleep( 1 );
609 }
610
611 return $acquired;
612 }
613
614 function unlock( $key ) {
615 $lockKey = $key . ':lock';
616 $this->mMemc->delete( $lockKey );
617 }
618
619 /**
620 * Get a message from either the content language or the user language.
621 *
622 * @param $key String: the message cache key
623 * @param $useDB Boolean: get the message from the DB, false to use only
624 * the localisation
625 * @param bool|string $langcode Code of the language to get the message for, if
626 * it is a valid code create a language for that language,
627 * if it is a string but not a valid code then make a basic
628 * language object, if it is a false boolean then use the
629 * current users language (as a fallback for the old
630 * parameter functionality), or if it is a true boolean
631 * then use the wikis content language (also as a
632 * fallback).
633 * @param $isFullKey Boolean: specifies whether $key is a two part key
634 * "msg/lang".
635 *
636 * @throws MWException
637 * @return string|bool
638 */
639 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
640 global $wgLanguageCode, $wgContLang;
641
642 if ( is_int( $key ) ) {
643 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
644 $key = strval( $key );
645 }
646
647 if ( !is_string( $key ) ) {
648 throw new MWException( 'Non-string key given' );
649 }
650
651 if ( strval( $key ) === '' ) {
652 # Shortcut: the empty key is always missing
653 return false;
654 }
655
656 $lang = wfGetLangObj( $langcode );
657 if ( !$lang ) {
658 throw new MWException( "Bad lang code $langcode given" );
659 }
660
661 $langcode = $lang->getCode();
662
663 $message = false;
664
665 # Normalise title-case input (with some inlining)
666 $lckey = str_replace( ' ', '_', $key );
667 if ( ord( $key ) < 128 ) {
668 $lckey[0] = strtolower( $lckey[0] );
669 $uckey = ucfirst( $lckey );
670 } else {
671 $lckey = $wgContLang->lcfirst( $lckey );
672 $uckey = $wgContLang->ucfirst( $lckey );
673 }
674
675 # Try the MediaWiki namespace
676 if( !$this->mDisable && $useDB ) {
677 $title = $uckey;
678 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
679 $title .= '/' . $langcode;
680 }
681 $message = $this->getMsgFromNamespace( $title, $langcode );
682 }
683
684 # Try the array in the language object
685 if ( $message === false ) {
686 $message = $lang->getMessage( $lckey );
687 if ( is_null( $message ) ) {
688 $message = false;
689 }
690 }
691
692 # Try the array of another language
693 if( $message === false ) {
694 $parts = explode( '/', $lckey );
695 # We may get calls for things that are http-urls from sidebar
696 # Let's not load nonexistent languages for those
697 # They usually have more than one slash.
698 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
699 $message = Language::getMessageFor( $parts[0], $parts[1] );
700 if ( is_null( $message ) ) {
701 $message = false;
702 }
703 }
704 }
705
706 # Is this a custom message? Try the default language in the db...
707 if( ( $message === false || $message === '-' ) &&
708 !$this->mDisable && $useDB &&
709 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
710 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
711 }
712
713 # Final fallback
714 if( $message === false ) {
715 return false;
716 }
717
718 # Fix whitespace
719 $message = strtr( $message,
720 array(
721 # Fix for trailing whitespace, removed by textarea
722 '&#32;' => ' ',
723 # Fix for NBSP, converted to space by firefox
724 '&nbsp;' => "\xc2\xa0",
725 '&#160;' => "\xc2\xa0",
726 ) );
727
728 return $message;
729 }
730
731 /**
732 * Get a message from the MediaWiki namespace, with caching. The key must
733 * first be converted to two-part lang/msg form if necessary.
734 *
735 * Unlike self::get(), this function doesn't resolve fallback chains, and
736 * some callers require this behavior. LanguageConverter::parseCachedTable()
737 * and self::get() are some examples in core.
738 *
739 * @param string $title Message cache key with initial uppercase letter.
740 * @param string $code code denoting the language to try.
741 *
742 * @return string|bool False on failure
743 */
744 function getMsgFromNamespace( $title, $code ) {
745 $this->load( $code );
746 if ( isset( $this->mCache[$code][$title] ) ) {
747 $entry = $this->mCache[$code][$title];
748 if ( substr( $entry, 0, 1 ) === ' ' ) {
749 return substr( $entry, 1 );
750 } elseif ( $entry === '!NONEXISTENT' ) {
751 return false;
752 } elseif( $entry === '!TOO BIG' ) {
753 // Fall through and try invididual message cache below
754 }
755 } else {
756 // XXX: This is not cached in process cache, should it?
757 $message = false;
758 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
759 if ( $message !== false ) {
760 return $message;
761 }
762
763 return false;
764 }
765
766 # Try the individual message cache
767 $titleKey = wfMemcKey( 'messages', 'individual', $title );
768 $entry = $this->mMemc->get( $titleKey );
769 if ( $entry ) {
770 if ( substr( $entry, 0, 1 ) === ' ' ) {
771 $this->mCache[$code][$title] = $entry;
772 return substr( $entry, 1 );
773 } elseif ( $entry === '!NONEXISTENT' ) {
774 $this->mCache[$code][$title] = '!NONEXISTENT';
775 return false;
776 } else {
777 # Corrupt/obsolete entry, delete it
778 $this->mMemc->delete( $titleKey );
779 }
780 }
781
782 # Try loading it from the database
783 $revision = Revision::newFromTitle(
784 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
785 );
786 if ( $revision ) {
787 $content = $revision->getContent();
788 if ( !$content ) {
789 // A possibly temporary loading failure.
790 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$title} ($code)" );
791 $message = null; // no negative caching
792 } else {
793 // XXX: Is this the right way to turn a Content object into a message?
794 // NOTE: $content is typically either WikitextContent, JavaScriptContent or CssContent.
795 // MessageContent is *not* used for storing messages, it's only used for wrapping them when needed.
796 $message = $content->getWikitextForTransclusion();
797
798 if ( $message === false || $message === null ) {
799 wfDebugLog( 'MessageCache', __METHOD__ . ": message content doesn't provide wikitext "
800 . "(content model: " . $content->getContentHandler() . ")" );
801
802 $message = false; // negative caching
803 } else {
804 $this->mCache[$code][$title] = ' ' . $message;
805 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
806 }
807 }
808 } else {
809 $message = false; // negative caching
810 }
811
812 if ( $message === false ) { // negative caching
813 $this->mCache[$code][$title] = '!NONEXISTENT';
814 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
815 }
816
817 return $message;
818 }
819
820 /**
821 * @param $message string
822 * @param $interface bool
823 * @param $language
824 * @param $title Title
825 * @return string
826 */
827 function transform( $message, $interface = false, $language = null, $title = null ) {
828 // Avoid creating parser if nothing to transform
829 if( strpos( $message, '{{' ) === false ) {
830 return $message;
831 }
832
833 if ( $this->mInParser ) {
834 return $message;
835 }
836
837 $parser = $this->getParser();
838 if ( $parser ) {
839 $popts = $this->getParserOptions();
840 $popts->setInterfaceMessage( $interface );
841 $popts->setTargetLanguage( $language );
842
843 $userlang = $popts->setUserLang( $language );
844 $this->mInParser = true;
845 $message = $parser->transformMsg( $message, $popts, $title );
846 $this->mInParser = false;
847 $popts->setUserLang( $userlang );
848 }
849 return $message;
850 }
851
852 /**
853 * @return Parser
854 */
855 function getParser() {
856 global $wgParser, $wgParserConf;
857 if ( !$this->mParser && isset( $wgParser ) ) {
858 # Do some initialisation so that we don't have to do it twice
859 $wgParser->firstCallInit();
860 # Clone it and store it
861 $class = $wgParserConf['class'];
862 if ( $class == 'Parser_DiffTest' ) {
863 # Uncloneable
864 $this->mParser = new $class( $wgParserConf );
865 } else {
866 $this->mParser = clone $wgParser;
867 }
868 }
869 return $this->mParser;
870 }
871
872 /**
873 * @param $text string
874 * @param $title Title
875 * @param $linestart bool
876 * @param $interface bool
877 * @param $language
878 * @return ParserOutput|string
879 */
880 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
881 if ( $this->mInParser ) {
882 return htmlspecialchars( $text );
883 }
884
885 $parser = $this->getParser();
886 $popts = $this->getParserOptions();
887 $popts->setInterfaceMessage( $interface );
888 $popts->setTargetLanguage( $language );
889
890 wfProfileIn( __METHOD__ );
891 if ( !$title || !$title instanceof Title ) {
892 global $wgTitle;
893 $title = $wgTitle;
894 }
895 // Sometimes $wgTitle isn't set either...
896 if ( !$title ) {
897 # It's not uncommon having a null $wgTitle in scripts. See r80898
898 # Create a ghost title in such case
899 $title = Title::newFromText( 'Dwimmerlaik' );
900 }
901
902 $this->mInParser = true;
903 $res = $parser->parse( $text, $title, $popts, $linestart );
904 $this->mInParser = false;
905
906 wfProfileOut( __METHOD__ );
907 return $res;
908 }
909
910 function disable() {
911 $this->mDisable = true;
912 }
913
914 function enable() {
915 $this->mDisable = false;
916 }
917
918 /**
919 * Clear all stored messages. Mainly used after a mass rebuild.
920 */
921 function clear() {
922 $langs = Language::fetchLanguageNames( null, 'mw' );
923 foreach ( array_keys( $langs ) as $code ) {
924 # Global cache
925 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
926 # Invalidate all local caches
927 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
928 }
929 $this->mLoadedLanguages = array();
930 }
931
932 /**
933 * @param $key
934 * @return array
935 */
936 public function figureMessage( $key ) {
937 global $wgLanguageCode;
938 $pieces = explode( '/', $key );
939 if( count( $pieces ) < 2 ) {
940 return array( $key, $wgLanguageCode );
941 }
942
943 $lang = array_pop( $pieces );
944 if( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
945 return array( $key, $wgLanguageCode );
946 }
947
948 $message = implode( '/', $pieces );
949 return array( $message, $lang );
950 }
951
952 /**
953 * Get all message keys stored in the message cache for a given language.
954 * If $code is the content language code, this will return all message keys
955 * for which MediaWiki:msgkey exists. If $code is another language code, this
956 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
957 * @param $code string
958 * @return array of message keys (strings)
959 */
960 public function getAllMessageKeys( $code ) {
961 global $wgContLang;
962 $this->load( $code );
963 if ( !isset( $this->mCache[$code] ) ) {
964 // Apparently load() failed
965 return null;
966 }
967 // Remove administrative keys
968 $cache = $this->mCache[$code];
969 unset( $cache['VERSION'] );
970 unset( $cache['EXPIRY'] );
971 // Remove any !NONEXISTENT keys
972 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
973 // Keys may appear with a capital first letter. lcfirst them.
974 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );
975 }
976 }