Localisation updates Cantonese, Chinese and Old/Late Time Chinese
[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 );
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 );
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 );
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 * @return False on somekind of error.
434 */
435 protected function saveToCaches( $cache, $cacheKey, $memc = true ) {
436 wfProfileIn( __METHOD__ );
437 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
438
439 $success = $this->mMemc->add( $cacheKey.'-status', "loading", MSG_LOAD_TIMEOUT );
440 if ( !$success ) return true; # Other process should be updating them now
441
442 $i = 0;
443 if ( $memc ) {
444 # Save in memcached
445 # Keep trying if it fails, this is kind of important
446
447 for ($i=0; $i<20 &&
448 !$this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
449 $i++ ) {
450 usleep(mt_rand(500000,1500000));
451 }
452 }
453
454 # Save to local cache
455 if ( $wgLocalMessageCache !== false ) {
456 $serialized = serialize( $cache );
457 $hash = md5( $serialized );
458 $this->mMemc->set( "$cacheKey-hash", $hash, $this->mExpiry );
459 if ($wgLocalMessageCacheSerialized) {
460 $this->saveToLocal( $serialized, $hash, $code );
461 } else {
462 $this->saveToScript( $cache, $hash, $code );
463 }
464 }
465
466 if ( $i == 20 ) {
467 $this->mMemc->set( $cacheKey.'-status', 'error', 60*5 );
468 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
469 $success = false;
470 } else {
471 $this->mMemc->delete( $cacheKey.'-status' );
472 $success = true;
473 }
474 wfProfileOut( __METHOD__ );
475 return $success;
476 }
477
478 /**
479 * Returns success
480 * Represents a write lock on the messages key
481 */
482 function lock($key) {
483 if ( !$this->mUseCache ) {
484 return true;
485 }
486
487 $lockKey = $key . 'lock';
488 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
489 sleep(1);
490 }
491
492 return $i >= MSG_WAIT_TIMEOUT;
493 }
494
495 function unlock($key) {
496 if ( !$this->mUseCache ) {
497 return;
498 }
499
500 $lockKey = $key . 'lock';
501 $this->mMemc->delete( $lockKey );
502 }
503
504 /**
505 * Get a message from either the content language or the user language.
506 *
507 * @param string $key The message cache key
508 * @param bool $useDB Get the message from the DB, false to use only the localisation
509 * @param string $langcode Code of the language to get the message for, if
510 * it is a valid code create a language for that
511 * language, if it is a string but not a valid code
512 * then make a basic language object, if it is a
513 * false boolean then use the current users
514 * language (as a fallback for the old parameter
515 * functionality), or if it is a true boolean then
516 * use the wikis content language (also as a
517 * fallback).
518 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
519 */
520 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
521 global $wgContLanguageCode, $wgContLang, $wgLang;
522
523 # Identify which language to get or create a language object for.
524 if( $langcode === $wgContLang->getCode() || $langcode === true ) {
525 # $langcode is the language code of the wikis content language object.
526 # or it is a boolean and value is true
527 $lang =& $wgContLang;
528 } elseif( $langcode === $wgLang->getCode() || $langcode === false ) {
529 # $langcode is the language code of user language object.
530 # or it was a boolean and value is false
531 $lang =& $wgLang;
532 } else {
533 $validCodes = array_keys( Language::getLanguageNames() );
534 if( in_array( $langcode, $validCodes ) ) {
535 # $langcode corresponds to a valid language.
536 $lang = Language::factory( $langcode );
537 } else {
538 # $langcode is a string, but not a valid language code; use content language.
539 $lang =& $wgContLang;
540 wfDebug( 'Invalid language code passed to MessageCache::get, falling back to content language.' );
541 }
542 }
543
544 $langcode = $lang->getCode();
545
546 # If uninitialised, someone is trying to call this halfway through Setup.php
547 if( !$this->mInitialised ) {
548 return '&lt;' . htmlspecialchars($key) . '&gt;';
549 }
550
551 $message = false;
552
553 # Normalise title-case input
554 $lckey = $wgContLang->lcfirst( $key );
555 $lckey = str_replace( ' ', '_', $lckey );
556
557 # Try the MediaWiki namespace
558 if( !$this->mDisable && $useDB ) {
559 $title = $wgContLang->ucfirst( $lckey );
560 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
561 $title .= '/' . $langcode;
562 }
563 $message = $this->getMsgFromNamespace( $title, $langcode );
564 }
565
566 # Try the extension array
567 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
568 $message = $this->mExtensionMessages[$langcode][$lckey];
569 }
570 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
571 $message = $this->mExtensionMessages['en'][$lckey];
572 }
573
574 # Try the array in the language object
575 if ( $message === false ) {
576 $message = $lang->getMessage( $lckey );
577 if ( is_null( $message ) ) {
578 $message = false;
579 }
580 }
581
582 # Try the array of another language
583 $pos = strrpos( $lckey, '/' );
584 if( $message === false && $pos !== false) {
585 $mkey = substr( $lckey, 0, $pos );
586 $code = substr( $lckey, $pos+1 );
587 if ( $code ) {
588 $validCodes = array_keys( Language::getLanguageNames() );
589 if ( in_array( $code, $validCodes ) ) {
590 $message = Language::getMessageFor( $mkey, $code );
591 if ( is_null( $message ) ) {
592 $message = false;
593 }
594 } else {
595 wfDebug( __METHOD__ . ": Invalid code $code for $mkey/$code, not trying messages array\n" );
596 }
597 }
598 }
599
600 # Is this a custom message? Try the default language in the db...
601 if( ($message === false || $message === '-' ) &&
602 !$this->mDisable && $useDB &&
603 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
604 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
605 }
606
607 # Final fallback
608 if( $message === false ) {
609 return '&lt;' . htmlspecialchars($key) . '&gt;';
610 }
611 return $message;
612 }
613
614 /**
615 * Get a message from the MediaWiki namespace, with caching. The key must
616 * first be converted to two-part lang/msg form if necessary.
617 *
618 * @param $title String: Message cache key with initial uppercase letter.
619 * @param $code String: code denoting the language to try.
620 */
621 function getMsgFromNamespace( $title, $code ) {
622 $message = false;
623 $type = false;
624
625 if ( $this->mUseCache ) {
626 if ( !isset($this->mCache[$title]) ) {
627 # Delay loading as far as possible, and only load messages for requested
628 # language.
629 $this->load( $code );
630 }
631 if (isset( $this->mCache[$title] ) ) {
632 $entry = $this->mCache[$title];
633 $type = substr( $entry, 0, 1 );
634 if ( $type == ' ' ) {
635 return substr( $entry, 1 );
636 }
637 }
638 }
639
640 # Call message hooks, in case they are defined
641 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
642 if ( $message !== false ) {
643 return $message;
644 }
645
646 # If there is no cache entry and no placeholder, it doesn't exist
647 if ( $type != '!' && $message === false ) {
648 return false;
649 }
650
651 $memcKey = $this->mMemcKey . ':' . $title;
652
653 # Try the individual message cache
654 if ( $this->mUseCache ) {
655 $entry = $this->mMemc->get( $memcKey );
656 if ( $entry ) {
657 $type = substr( $entry, 0, 1 );
658
659 if ( $type == ' ' ) {
660 # Ok!
661 $message = substr( $entry, 1 );
662 $this->mCache[$title] = $entry;
663 return $message;
664 } elseif ( $entry == '!NONEXISTENT' ) {
665 return false;
666 } else {
667 # Corrupt/obsolete entry, delete it
668 $this->mMemc->delete( $memcKey );
669 }
670
671 }
672 }
673
674 # Try loading it from the DB
675 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
676 if( $revision ) {
677 $message = $revision->getText();
678 if ($this->mUseCache) {
679 $this->mCache[$title] = ' ' . $message;
680 $this->mMemc->set( $memcKey, $message, $this->mExpiry );
681 }
682 } else {
683 # Negative caching
684 # Use some special text instead of false, because false gets converted to '' somewhere
685 $this->mMemc->set( $memcKey, '!NONEXISTENT', $this->mExpiry );
686 $this->mCache[$title] = false;
687 }
688 return $message;
689 }
690
691 function transform( $message, $interface = false ) {
692 global $wgParser;
693 if ( !$this->mParser && isset( $wgParser ) ) {
694 # Do some initialisation so that we don't have to do it twice
695 $wgParser->firstCallInit();
696 # Clone it and store it
697 $this->mParser = clone $wgParser;
698 }
699 if ( $this->mParser ) {
700 if( strpos( $message, '{{' ) !== false ) {
701 $popts = $this->getParserOptions();
702 $popts->setInterfaceMessage( $interface );
703 $message = $this->mParser->transformMsg( $message, $popts );
704 }
705 }
706 return $message;
707 }
708
709 function disable() { $this->mDisable = true; }
710 function enable() { $this->mDisable = false; }
711
712 /** @deprecated */
713 function disableTransform(){
714 wfDeprecated( __METHOD__ );
715 }
716 function enableTransform() {
717 wfDeprecated( __METHOD__ );
718 }
719 function setTransform( $x ) {
720 wfDeprecated( __METHOD__ );
721 }
722 function getTransform() {
723 wfDeprecated( __METHOD__ );
724 return false;
725 }
726
727 /**
728 * Add a message to the cache
729 *
730 * @param mixed $key
731 * @param mixed $value
732 * @param string $lang The messages language, English by default
733 */
734 function addMessage( $key, $value, $lang = 'en' ) {
735 $this->mExtensionMessages[$lang][$key] = $value;
736 }
737
738 /**
739 * Add an associative array of message to the cache
740 *
741 * @param array $messages An associative array of key => values to be added
742 * @param string $lang The messages language, English by default
743 */
744 function addMessages( $messages, $lang = 'en' ) {
745 wfProfileIn( __METHOD__ );
746 if ( !is_array( $messages ) ) {
747 throw new MWException( __METHOD__.': Invalid message array' );
748 }
749 if ( isset( $this->mExtensionMessages[$lang] ) ) {
750 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
751 } else {
752 $this->mExtensionMessages[$lang] = $messages;
753 }
754 wfProfileOut( __METHOD__ );
755 }
756
757 /**
758 * Add a 2-D array of messages by lang. Useful for extensions.
759 *
760 * @param array $messages The array to be added
761 */
762 function addMessagesByLang( $messages ) {
763 wfProfileIn( __METHOD__ );
764 foreach ( $messages as $key => $value ) {
765 $this->addMessages( $value, $key );
766 }
767 wfProfileOut( __METHOD__ );
768 }
769
770 /**
771 * Get the extension messages for a specific language. Only English, interface
772 * and content language are guaranteed to be loaded.
773 *
774 * @param string $lang The messages language, English by default
775 */
776 function getExtensionMessagesFor( $lang = 'en' ) {
777 wfProfileIn( __METHOD__ );
778 $messages = array();
779 if ( isset( $this->mExtensionMessages[$lang] ) ) {
780 $messages = $this->mExtensionMessages[$lang];
781 }
782 if ( $lang != 'en' ) {
783 $messages = $messages + $this->mExtensionMessages['en'];
784 }
785 wfProfileOut( __METHOD__ );
786 return $messages;
787 }
788
789 /**
790 * Clear all stored messages. Mainly used after a mass rebuild.
791 */
792 function clear() {
793 global $wgLocalMessageCache;
794 if( $this->mUseCache ) {
795 # Global cache
796 $this->mMemc->delete( $this->mMemcKey );
797 # Invalidate all local caches
798 $this->mMemc->delete( "{$this->mMemcKey}-hash" );
799 }
800 }
801
802 function loadAllMessages() {
803 global $wgExtensionMessagesFiles;
804 if ( $this->mAllMessagesLoaded ) {
805 return;
806 }
807 $this->mAllMessagesLoaded = true;
808
809 # Some extensions will load their messages when you load their class file
810 wfLoadAllExtensions();
811 # Others will respond to this hook
812 wfRunHooks( 'LoadAllMessages' );
813 # Some register their messages in $wgExtensionMessagesFiles
814 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
815 wfLoadExtensionMessages( $name );
816 }
817 # Still others will respond to neither, they are EVIL. We sometimes need to know!
818 }
819
820 /**
821 * Load messages from a given file
822 *
823 * @param string $filename Filename of file to load.
824 * @param string $langcode Language to load messages for, or false for
825 * default behvaiour (en, content language and user
826 * language).
827 */
828 function loadMessagesFile( $filename, $langcode = false ) {
829 global $wgLang, $wgContLang;
830 $messages = $magicWords = false;
831 require( $filename );
832
833 $validCodes = Language::getLanguageNames();
834 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
835 # Load messages for given language code.
836 $this->processMessagesArray( $messages, $langcode );
837 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
838 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
839 } else {
840 # Load only languages that are usually used, and merge all
841 # fallbacks, except English.
842 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
843 foreach( $langs as $code ) {
844 $this->processMessagesArray( $messages, $code );
845 }
846 }
847
848 if ( $magicWords !== false ) {
849 global $wgContLang;
850 $wgContLang->addMagicWordsByLang( $magicWords );
851 }
852 }
853
854 /**
855 * Process an array of messages, loading it into the message cache.
856 *
857 * @param array $messages Messages array.
858 * @param string $langcode Language code to process.
859 */
860 function processMessagesArray( $messages, $langcode ) {
861 $fallbackCode = $langcode;
862 $mergedMessages = array();
863 do {
864 if ( isset($messages[$fallbackCode]) ) {
865 $mergedMessages += $messages[$fallbackCode];
866 }
867 $fallbackCode = Language::getFallbackfor( $fallbackCode );
868 } while( $fallbackCode && $fallbackCode !== 'en' );
869
870 if ( !empty($mergedMessages) )
871 $this->addMessages( $mergedMessages, $langcode );
872 }
873
874 public function figureMessage( $key ) {
875 global $wgContLanguageCode;
876 $pieces = explode('/', $key, 2);
877
878 $key = $pieces[0];
879
880 # Language the user is translating to
881 $langCode = isset($pieces[1]) ? $pieces[1] : $wgContLanguageCode;
882 return array( $key, $langCode );
883 }
884
885 }