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