* Updates to language variant code for Serbian et al
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * @package MediaWiki
4 * @subpackage Language
5 */
6
7 if( !defined( 'MEDIAWIKI' ) ) {
8 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
9 exit( 1 );
10 }
11
12 #
13 # In general you should not make customizations in these language files
14 # directly, but should use the MediaWiki: special namespace to customize
15 # user interface messages through the wiki.
16 # See http://meta.wikipedia.org/wiki/MediaWiki_namespace
17 #
18 # NOTE TO TRANSLATORS: Do not copy this whole file when making translations!
19 # A lot of common constants and a base class with inheritable methods are
20 # defined here, which should not be redefined. See the other LanguageXx.php
21 # files for examples.
22 #
23
24 # Read language names
25 global $wgLanguageNames;
26 require_once( 'Names.php' );
27
28 global $wgInputEncoding, $wgOutputEncoding;
29 global $wgDBname, $wgMemc;
30
31 /**
32 * These are always UTF-8, they exist only for backwards compatibility
33 */
34 $wgInputEncoding = "UTF-8";
35 $wgOutputEncoding = "UTF-8";
36
37 if( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding('UTF-8');
39 }
40
41 /* a fake language converter */
42 class FakeConverter {
43 var $mLang;
44 function FakeConverter($langobj) {$this->mLang = $langobj;}
45 function convert($t, $i) {return $t;}
46 function parserConvert($t, $p) {return $t;}
47 function getVariants() { return array( $this->mLang->getCode() ); }
48 function getPreferredVariant() {return $this->mLang->getCode(); }
49 function findVariantLink(&$l, &$n) {}
50 function getExtraHashOptions() {return '';}
51 function getParsedTitle() {return '';}
52 function markNoConversion($text, $noParse=false) {return $text;}
53 function convertCategoryKey( $key ) {return $key; }
54 function convertLinkToAllVariants($text){ return array( $this->mLang->getCode() => $text); }
55 function setNoTitleConvert(){}
56 }
57
58 #--------------------------------------------------------------------------
59 # Internationalisation code
60 #--------------------------------------------------------------------------
61
62 class Language {
63 var $mConverter, $mVariants, $mCode, $mLoaded = false;
64
65 static public $mLocalisationKeys = array( 'fallback', 'namespaceNames',
66 'quickbarSettings', 'skinNames', 'mathNames',
67 'bookstoreList', 'magicWords', 'messages', 'rtl', 'digitTransformTable',
68 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
69 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
70 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
71 'defaultDateFormat', 'extraUserToggles' );
72
73 static public $mMergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
74 'dateFormats', 'defaultUserOptionOverrides', 'magicWords' );
75
76 static public $mMergeableListKeys = array( 'extraUserToggles' );
77
78 static public $mLocalisationCache = array();
79
80 static public $mWeekdayMsgs = array(
81 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
82 'friday', 'saturday'
83 );
84
85 static public $mWeekdayAbbrevMsgs = array(
86 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
87 );
88
89 static public $mMonthMsgs = array(
90 'january', 'february', 'march', 'april', 'may_long', 'june',
91 'july', 'august', 'september', 'october', 'november',
92 'december'
93 );
94 static public $mMonthGenMsgs = array(
95 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
96 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
97 'december-gen'
98 );
99 static public $mMonthAbbrevMsgs = array(
100 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
101 'sep', 'oct', 'nov', 'dec'
102 );
103
104 /**
105 * Create a language object for a given language code
106 */
107 static function factory( $code ) {
108 global $IP;
109 static $recursionLevel = 0;
110
111 if ( $code == 'en' ) {
112 $class = 'Language';
113 } else {
114 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
115 // Preload base classes to work around APC/PHP5 bug
116 if ( file_exists( "$IP/languages/$class.deps.php" ) ) {
117 include_once("$IP/languages/$class.deps.php");
118 }
119 if ( file_exists( "$IP/languages/$class.php" ) ) {
120 include_once("$IP/languages/$class.php");
121 }
122 }
123
124 if ( $recursionLevel > 5 ) {
125 throw new MWException( "Language fallback loop detected when creating class $class\n" );
126 }
127
128 if( ! class_exists( $class ) ) {
129 $fallback = Language::getFallbackFor( $code );
130 ++$recursionLevel;
131 $lang = Language::factory( $fallback );
132 --$recursionLevel;
133 $lang->setCode( $code );
134 } else {
135 $lang = new $class;
136 }
137
138 return $lang;
139 }
140
141 function __construct() {
142 $this->mConverter = new FakeConverter($this);
143 // Set the code to the name of the descendant
144 if ( get_class( $this ) == 'Language' ) {
145 $this->mCode = 'en';
146 } else {
147 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
148 }
149 }
150
151 /**
152 * Hook which will be called if this is the content language.
153 * Descendants can use this to register hook functions or modify globals
154 */
155 function initContLang() {}
156
157 /**
158 * @deprecated
159 * @return array
160 */
161 function getDefaultUserOptions() {
162 return User::getDefaultOptions();
163 }
164
165 /**
166 * Exports $wgBookstoreListEn
167 * @return array
168 */
169 function getBookstoreList() {
170 $this->load();
171 return $this->bookstoreList;
172 }
173
174 /**
175 * @return array
176 */
177 function getNamespaces() {
178 $this->load();
179 return $this->namespaceNames;
180 }
181
182 /**
183 * A convenience function that returns the same thing as
184 * getNamespaces() except with the array values changed to ' '
185 * where it found '_', useful for producing output to be displayed
186 * e.g. in <select> forms.
187 *
188 * @return array
189 */
190 function getFormattedNamespaces() {
191 $ns = $this->getNamespaces();
192 foreach($ns as $k => $v) {
193 $ns[$k] = strtr($v, '_', ' ');
194 }
195 return $ns;
196 }
197
198 /**
199 * Get a namespace value by key
200 * <code>
201 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
202 * echo $mw_ns; // prints 'MediaWiki'
203 * </code>
204 *
205 * @param int $index the array key of the namespace to return
206 * @return mixed, string if the namespace value exists, otherwise false
207 */
208 function getNsText( $index ) {
209 $ns = $this->getNamespaces();
210 return isset( $ns[$index] ) ? $ns[$index] : false;
211 }
212
213 /**
214 * A convenience function that returns the same thing as
215 * getNsText() except with '_' changed to ' ', useful for
216 * producing output.
217 *
218 * @return array
219 */
220 function getFormattedNsText( $index ) {
221 $ns = $this->getNsText( $index );
222 return strtr($ns, '_', ' ');
223 }
224
225 /**
226 * Get a namespace key by value, case insensetive.
227 *
228 * @param string $text
229 * @return mixed An integer if $text is a valid value otherwise false
230 */
231 function getNsIndex( $text ) {
232 $this->load();
233 $index = @$this->mNamespaceIds[$this->lc($text)];
234 if ( is_null( $index ) ) {
235 return false;
236 } else {
237 return $index;
238 }
239 }
240
241 /**
242 * short names for language variants used for language conversion links.
243 *
244 * @param string $code
245 * @return string
246 */
247 function getVariantname( $code ) {
248 return $this->getMessageFromDB( "variantname-$code" );
249 }
250
251 function specialPage( $name ) {
252 return $this->getNsText(NS_SPECIAL) . ':' . $name;
253 }
254
255 function getQuickbarSettings() {
256 $this->load();
257 return $this->quickbarSettings;
258 }
259
260 function getSkinNames() {
261 $this->load();
262 return $this->skinNames;
263 }
264
265 function getMathNames() {
266 $this->load();
267 return $this->mathNames;
268 }
269
270 function getDatePreferences() {
271 $this->load();
272 return $this->datePreferences;
273 }
274
275 function getDateFormats() {
276 $this->load();
277 return $this->dateFormats;
278 }
279
280 function getDefaultDateFormat() {
281 $this->load();
282 return $this->defaultDateFormat;
283 }
284
285 function getDatePreferenceMigrationMap() {
286 $this->load();
287 return $this->datePreferenceMigrationMap;
288 }
289
290 function getDefaultUserOptionOverrides() {
291 $this->load();
292 return $this->defaultUserOptionOverrides;
293 }
294
295 function getExtraUserToggles() {
296 $this->load();
297 return $this->extraUserToggles;
298 }
299
300 function getUserToggle( $tog ) {
301 return $this->getMessageFromDB( "tog-$tog" );
302 }
303
304 /**
305 * Get language names, indexed by code.
306 * If $customisedOnly is true, only returns codes with a messages file
307 */
308 function getLanguageNames( $customisedOnly = false ) {
309 global $wgLanguageNames;
310 if ( !$customisedOnly ) {
311 return $wgLanguageNames;
312 }
313
314 global $IP;
315 $messageFiles = glob( "$IP/languages/Messages*.php" );
316 $names = array();
317 foreach ( $messageFiles as $file ) {
318 if( preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $file, $m ) ) {
319 $code = str_replace( '_', '-', strtolower( $m[1] ) );
320 if ( isset( $wgLanguageNames[$code] ) ) {
321 $names[$code] = $wgLanguageNames[$code];
322 }
323 }
324 }
325 return $names;
326 }
327
328 /**
329 * Ugly hack to get a message maybe from the MediaWiki namespace, if this
330 * language object is the content or user language.
331 */
332 function getMessageFromDB( $msg ) {
333 global $wgContLang, $wgLang;
334 if ( $wgContLang->getCode() == $this->getCode() ) {
335 # Content language
336 return wfMsgForContent( $msg );
337 } elseif ( $wgLang->getCode() == $this->getCode() ) {
338 # User language
339 return wfMsg( $msg );
340 } else {
341 # Neither, get from localisation
342 return $this->getMessage( $msg );
343 }
344 }
345
346 function getLanguageName( $code ) {
347 global $wgLanguageNames;
348 if ( ! array_key_exists( $code, $wgLanguageNames ) ) {
349 return '';
350 }
351 return $wgLanguageNames[$code];
352 }
353
354 function getMonthName( $key ) {
355 return $this->getMessageFromDB( self::$mMonthMsgs[$key-1] );
356 }
357
358 function getMonthNameGen( $key ) {
359 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key-1] );
360 }
361
362 function getMonthAbbreviation( $key ) {
363 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key-1] );
364 }
365
366 function getWeekdayName( $key ) {
367 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key-1] );
368 }
369
370 function getWeekdayAbbreviation( $key ) {
371 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key-1] );
372 }
373
374 /**
375 * Used by date() and time() to adjust the time output.
376 * @public
377 * @param int $ts the time in date('YmdHis') format
378 * @param mixed $tz adjust the time by this amount (default false,
379 * mean we get user timecorrection setting)
380 * @return int
381 */
382 function userAdjust( $ts, $tz = false ) {
383 global $wgUser, $wgLocalTZoffset;
384
385 if (!$tz) {
386 $tz = $wgUser->getOption( 'timecorrection' );
387 }
388
389 # minutes and hours differences:
390 $minDiff = 0;
391 $hrDiff = 0;
392
393 if ( $tz === '' ) {
394 # Global offset in minutes.
395 if( isset($wgLocalTZoffset) ) {
396 $hrDiff = $wgLocalTZoffset % 60;
397 $minDiff = $wgLocalTZoffset - ($hrDiff * 60);
398 }
399 } elseif ( strpos( $tz, ':' ) !== false ) {
400 $tzArray = explode( ':', $tz );
401 $hrDiff = intval($tzArray[0]);
402 $minDiff = intval($hrDiff < 0 ? -$tzArray[1] : $tzArray[1]);
403 } else {
404 $hrDiff = intval( $tz );
405 }
406
407 # No difference ? Return time unchanged
408 if ( 0 == $hrDiff && 0 == $minDiff ) { return $ts; }
409
410 # Generate an adjusted date
411 $t = mktime( (
412 (int)substr( $ts, 8, 2) ) + $hrDiff, # Hours
413 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
414 (int)substr( $ts, 12, 2 ), # Seconds
415 (int)substr( $ts, 4, 2 ), # Month
416 (int)substr( $ts, 6, 2 ), # Day
417 (int)substr( $ts, 0, 4 ) ); #Year
418 return date( 'YmdHis', $t );
419 }
420
421 /**
422 * This is a workalike of PHP's date() function, but with better
423 * internationalisation, a reduced set of format characters, and a better
424 * escaping format.
425 *
426 * Supported format characters are dDjlFmMnYyHis. See the PHP manual for
427 * definitions. There are a number of extensions, which start with "x":
428 *
429 * xn Do not translate digits of the next numeric format character
430 * xr Use roman numerals for the next numeric format character
431 * xx Literal x
432 * xg Genitive month name
433 *
434 * Characters enclosed in double quotes will be considered literal (with
435 * the quotes themselves removed). Unmatched quotes will be considered
436 * literal quotes. Example:
437 *
438 * "The month is" F => The month is January
439 * i's" => 20'11"
440 *
441 * Backslash escaping is also supported.
442 *
443 * @param string $format
444 * @param string $ts 14-character timestamp
445 * YYYYMMDDHHMMSS
446 * 01234567890123
447 */
448 function sprintfDate( $format, $ts ) {
449 $s = '';
450 $raw = false;
451 $roman = false;
452 for ( $p = 0; $p < strlen( $format ); $p++ ) {
453 $num = false;
454 $code = $format[$p];
455 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
456 $code .= $format[++$p];
457 }
458
459 switch ( $code ) {
460 case 'xx':
461 $s .= 'x';
462 break;
463 case 'xn':
464 $raw = true;
465 break;
466 case 'xr':
467 $roman = true;
468 break;
469 case 'xg':
470 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
471 break;
472 case 'd':
473 $num = substr( $ts, 6, 2 );
474 break;
475 case 'D':
476 $s .= $this->getWeekdayAbbreviation( self::calculateWeekday( $ts ) );
477 break;
478 case 'j':
479 $num = intval( substr( $ts, 6, 2 ) );
480 break;
481 case 'l':
482 $s .= $this->getWeekdayName( self::calculateWeekday( $ts ) );
483 break;
484 case 'F':
485 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
486 break;
487 case 'm':
488 $num = substr( $ts, 4, 2 );
489 break;
490 case 'M':
491 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
492 break;
493 case 'n':
494 $num = intval( substr( $ts, 4, 2 ) );
495 break;
496 case 'Y':
497 $num = substr( $ts, 0, 4 );
498 break;
499 case 'y':
500 $num = substr( $ts, 2, 2 );
501 break;
502 case 'H':
503 $num = substr( $ts, 8, 2 );
504 break;
505 case 'G':
506 $num = intval( substr( $ts, 8, 2 ) );
507 break;
508 case 'i':
509 $num = substr( $ts, 10, 2 );
510 break;
511 case 's':
512 $num = substr( $ts, 12, 2 );
513 break;
514 case '\\':
515 # Backslash escaping
516 if ( $p < strlen( $format ) - 1 ) {
517 $s .= $format[++$p];
518 } else {
519 $s .= '\\';
520 }
521 break;
522 case '"':
523 # Quoted literal
524 if ( $p < strlen( $format ) - 1 ) {
525 $endQuote = strpos( $format, '"', $p + 1 );
526 if ( $endQuote === false ) {
527 # No terminating quote, assume literal "
528 $s .= '"';
529 } else {
530 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
531 $p = $endQuote;
532 }
533 } else {
534 # Quote at end of string, assume literal "
535 $s .= '"';
536 }
537 break;
538 default:
539 $s .= $format[$p];
540 }
541 if ( $num !== false ) {
542 if ( $raw ) {
543 $s .= $num;
544 $raw = false;
545 } elseif ( $roman ) {
546 $s .= Language::romanNumeral( $num );
547 $roman = false;
548 } else {
549 $s .= $this->formatNum( $num, true );
550 }
551 $num = false;
552 }
553 }
554 return $s;
555 }
556
557 /**
558 * Roman number formatting up to 100
559 */
560 static function romanNumeral( $num ) {
561 static $units = array( 0, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' );
562 static $decades = array( 0, 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' );
563 $num = intval( $num );
564 if ( $num > 100 || $num <= 0 ) {
565 return $num;
566 }
567 $s = '';
568 if ( $num >= 10 ) {
569 $s .= $decades[floor( $num / 10 )];
570 $num = $num % 10;
571 }
572 if ( $num >= 1 ) {
573 $s .= $units[$num];
574 }
575 return $s;
576 }
577
578 /**
579 * Calculate the day of the week for a 14-character timestamp
580 * 1 for Sunday through to 7 for Saturday
581 * This takes about 100us on a slow computer
582 */
583 static function calculateWeekday( $ts ) {
584 return date( 'w', wfTimestamp( TS_UNIX, $ts ) ) + 1;
585 }
586
587 /**
588 * This is meant to be used by time(), date(), and timeanddate() to get
589 * the date preference they're supposed to use, it should be used in
590 * all children.
591 *
592 *<code>
593 * function timeanddate([...], $format = true) {
594 * $datePreference = $this->dateFormat($format);
595 * [...]
596 * }
597 *</code>
598 *
599 * @param mixed $usePrefs: if true, the user's preference is used
600 * if false, the site/language default is used
601 * if int/string, assumed to be a format.
602 * @return string
603 */
604 function dateFormat( $usePrefs = true ) {
605 global $wgUser;
606
607 if( is_bool( $usePrefs ) ) {
608 if( $usePrefs ) {
609 $datePreference = $wgUser->getDatePreference();
610 } else {
611 $options = User::getDefaultOptions();
612 $datePreference = (string)$options['date'];
613 }
614 } else {
615 $datePreference = (string)$usePrefs;
616 }
617
618 // return int
619 if( $datePreference == '' ) {
620 return 'default';
621 }
622
623 return $datePreference;
624 }
625
626 /**
627 * @public
628 * @param mixed $ts the time format which needs to be turned into a
629 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
630 * @param bool $adj whether to adjust the time output according to the
631 * user configured offset ($timecorrection)
632 * @param mixed $format true to use user's date format preference
633 * @param string $timecorrection the time offset as returned by
634 * validateTimeZone() in Special:Preferences
635 * @return string
636 */
637 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
638 $this->load();
639 if ( $adj ) {
640 $ts = $this->userAdjust( $ts, $timecorrection );
641 }
642
643 $pref = $this->dateFormat( $format );
644 if( $pref == 'default' || !isset( $this->dateFormats["$pref date"] ) ) {
645 $pref = $this->defaultDateFormat;
646 }
647 return $this->sprintfDate( $this->dateFormats["$pref date"], $ts );
648 }
649
650 /**
651 * @public
652 * @param mixed $ts the time format which needs to be turned into a
653 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
654 * @param bool $adj whether to adjust the time output according to the
655 * user configured offset ($timecorrection)
656 * @param mixed $format true to use user's date format preference
657 * @param string $timecorrection the time offset as returned by
658 * validateTimeZone() in Special:Preferences
659 * @return string
660 */
661 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
662 $this->load();
663 if ( $adj ) {
664 $ts = $this->userAdjust( $ts, $timecorrection );
665 }
666
667 $pref = $this->dateFormat( $format );
668 if( $pref == 'default' || !isset( $this->dateFormats["$pref time"] ) ) {
669 $pref = $this->defaultDateFormat;
670 }
671 return $this->sprintfDate( $this->dateFormats["$pref time"], $ts );
672 }
673
674 /**
675 * @public
676 * @param mixed $ts the time format which needs to be turned into a
677 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
678 * @param bool $adj whether to adjust the time output according to the
679 * user configured offset ($timecorrection)
680
681 * @param mixed $format what format to return, if it's false output the
682 * default one (default true)
683 * @param string $timecorrection the time offset as returned by
684 * validateTimeZone() in Special:Preferences
685 * @return string
686 */
687 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
688 $this->load();
689 if ( $adj ) {
690 $ts = $this->userAdjust( $ts, $timecorrection );
691 }
692
693 $pref = $this->dateFormat( $format );
694 if( $pref == 'default' || !isset( $this->dateFormats["$pref both"] ) ) {
695 $pref = $this->defaultDateFormat;
696 }
697
698 return $this->sprintfDate( $this->dateFormats["$pref both"], $ts );
699 }
700
701 function getMessage( $key ) {
702 $this->load();
703 return @$this->messages[$key];
704 }
705
706 function getAllMessages() {
707 $this->load();
708 return $this->messages;
709 }
710
711 function iconv( $in, $out, $string ) {
712 # For most languages, this is a wrapper for iconv
713 return iconv( $in, $out, $string );
714 }
715
716 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
717 function ucwordbreaksCallbackAscii($matches){
718 return $this->ucfirst($matches[1]);
719 }
720
721 function ucwordbreaksCallbackMB($matches){
722 return mb_strtoupper($matches[0]);
723 }
724
725 function ucCallback($matches){
726 global $wikiUpperChars;
727 return strtr( $matches[1] , $wikiUpperChars );
728 }
729
730 function lcCallback($matches){
731 global $wikiLowerChars;
732 return strtr( $matches[1] , $wikiLowerChars );
733 }
734
735 function ucwordsCallbackMB($matches){
736 return mb_strtoupper($matches[0]);
737 }
738
739 function ucwordsCallbackWiki($matches){
740 global $wikiUpperChars;
741 return strtr( $matches[0] , $wikiUpperChars );
742 }
743
744 function ucfirst( $str ) {
745 return self::uc( $str, true );
746 }
747
748 function uc( $str, $first = false ) {
749 if ( function_exists( 'mb_strtoupper' ) )
750 if ( $first )
751 if ( self::isMultibyte( $str ) )
752 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
753 else
754 return ucfirst( $str );
755 else
756 return self::isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
757 else
758 if ( self::isMultibyte( $str ) ) {
759 list( $wikiUpperChars ) = $this->getCaseMaps();
760 $x = $first ? '^' : '';
761 return preg_replace_callback(
762 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
763 array($this,"ucCallback"),
764 $str
765 );
766 } else
767 return $first ? ucfirst( $str ) : strtoupper( $str );
768 }
769
770 function lcfirst( $str ) {
771 return self::lc( $str, true );
772 }
773
774 function lc( $str, $first = false ) {
775 if ( function_exists( 'mb_strtolower' ) )
776 if ( $first )
777 if ( self::isMultibyte( $str ) )
778 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
779 else
780 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
781 else
782 return self::isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
783 else
784 if ( self::isMultibyte( $str ) ) {
785 list( , $wikiLowerChars ) = self::getCaseMaps();
786 $x = $first ? '^' : '';
787 return preg_replace_callback(
788 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
789 array($this,"lcCallback"),
790 $str
791 );
792 } else
793 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
794 }
795
796 function isMultibyte( $str ) {
797 return (bool)preg_match( '/[\x80-\xff]/', $str );
798 }
799
800 function ucwords($str) {
801 global $wikiUpperChars;
802
803 if ( self::isMultibyte( $str ) ) {
804 $str = self::lc($str);
805
806 // regexp to find first letter in each word (i.e. after each space)
807 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
808
809 // function to use to capitalize a single char
810 if ( function_exists( 'mb_strtoupper' ) )
811 return preg_replace_callback(
812 $replaceRegexp,
813 array($this,"ucwordsCallbackMB"),
814 $str
815 );
816 else
817 return preg_replace_callback(
818 $replaceRegexp,
819 array($this,"ucwordsCallbackWiki"),
820 $str
821 );
822 }
823 else
824 return ucwords( strtolower( $str ) );
825 }
826
827 # capitalize words at word breaks
828 function ucwordbreaks($str){
829 global $wikiUpperChars;
830
831 if (self::isMultibyte( $str ) ) {
832 $str = self::lc($str);
833
834 // since \b doesn't work for UTF-8, we explicitely define word break chars
835 $breaks= "[ \-\(\)\}\{\.,\?!]";
836
837 // find first letter after word break
838 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
839
840 if ( function_exists( 'mb_strtoupper' ) )
841 return preg_replace_callback(
842 $replaceRegexp,
843 array($this,"ucwordbreaksCallbackMB"),
844 $str
845 );
846 else
847 return preg_replace_callback(
848 $replaceRegexp,
849 array($this,"ucwordsCallbackWiki"),
850 $str
851 );
852 }
853 else
854 return preg_replace_callback(
855 '/\b([\w\x80-\xff]+)\b/',
856 array($this,"ucwordbreaksCallbackAscii"),
857 $str );
858 }
859
860 function checkTitleEncoding( $s ) {
861 if( is_array( $s ) ) {
862 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
863 }
864 # Check for non-UTF-8 URLs
865 $ishigh = preg_match( '/[\x80-\xff]/', $s);
866 if(!$ishigh) return $s;
867
868 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
869 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
870 if( $isutf8 ) return $s;
871
872 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
873 }
874
875 function fallback8bitEncoding() {
876 $this->load();
877 return $this->fallback8bitEncoding;
878 }
879
880 /**
881 * Some languages have special punctuation to strip out
882 * or characters which need to be converted for MySQL's
883 * indexing to grok it correctly. Make such changes here.
884 *
885 * @param string $in
886 * @return string
887 */
888 function stripForSearch( $string ) {
889 # MySQL fulltext index doesn't grok utf-8, so we
890 # need to fold cases and convert to hex
891
892 wfProfileIn( __METHOD__ );
893 if( function_exists( 'mb_strtolower' ) ) {
894 $out = preg_replace(
895 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
896 "'U8' . bin2hex( \"$1\" )",
897 mb_strtolower( $string ) );
898 } else {
899 list( , $wikiLowerChars ) = self::getCaseMaps();
900 $out = preg_replace(
901 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
902 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
903 $string );
904 }
905 wfProfileOut( __METHOD__ );
906 return $out;
907 }
908
909 function convertForSearchResult( $termsArray ) {
910 # some languages, e.g. Chinese, need to do a conversion
911 # in order for search results to be displayed correctly
912 return $termsArray;
913 }
914
915 /**
916 * Get the first character of a string.
917 *
918 * @param string $s
919 * @return string
920 */
921 function firstChar( $s ) {
922 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
923 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
924
925 return isset( $matches[1] ) ? $matches[1] : "";
926 }
927
928 function initEncoding() {
929 # Some languages may have an alternate char encoding option
930 # (Esperanto X-coding, Japanese furigana conversion, etc)
931 # If this language is used as the primary content language,
932 # an override to the defaults can be set here on startup.
933 }
934
935 function recodeForEdit( $s ) {
936 # For some languages we'll want to explicitly specify
937 # which characters make it into the edit box raw
938 # or are converted in some way or another.
939 # Note that if wgOutputEncoding is different from
940 # wgInputEncoding, this text will be further converted
941 # to wgOutputEncoding.
942 global $wgEditEncoding;
943 if( $wgEditEncoding == '' or
944 $wgEditEncoding == 'UTF-8' ) {
945 return $s;
946 } else {
947 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
948 }
949 }
950
951 function recodeInput( $s ) {
952 # Take the previous into account.
953 global $wgEditEncoding;
954 if($wgEditEncoding != "") {
955 $enc = $wgEditEncoding;
956 } else {
957 $enc = 'UTF-8';
958 }
959 if( $enc == 'UTF-8' ) {
960 return $s;
961 } else {
962 return $this->iconv( $enc, 'UTF-8', $s );
963 }
964 }
965
966 /**
967 * For right-to-left language support
968 *
969 * @return bool
970 */
971 function isRTL() {
972 $this->load();
973 return $this->rtl;
974 }
975
976 /**
977 * A hidden direction mark (LRM or RLM), depending on the language direction
978 *
979 * @return string
980 */
981 function getDirMark() {
982 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
983 }
984
985 /**
986 * An arrow, depending on the language direction
987 *
988 * @return string
989 */
990 function getArrow() {
991 return $this->isRTL() ? '←' : '→';
992 }
993
994 /**
995 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
996 *
997 * @return bool
998 */
999 function linkPrefixExtension() {
1000 $this->load();
1001 return $this->linkPrefixExtension;
1002 }
1003
1004 function &getMagicWords() {
1005 $this->load();
1006 return $this->magicWords;
1007 }
1008
1009 # Fill a MagicWord object with data from here
1010 function getMagic( &$mw ) {
1011 if ( !isset( $this->mMagicExtensions ) ) {
1012 $this->mMagicExtensions = array();
1013 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
1014 }
1015 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
1016 $rawEntry = $this->mMagicExtensions[$mw->mId];
1017 } else {
1018 $magicWords =& $this->getMagicWords();
1019 if ( isset( $magicWords[$mw->mId] ) ) {
1020 $rawEntry = $magicWords[$mw->mId];
1021 } else {
1022 # Fall back to English if local list is incomplete
1023 $magicWords =& Language::getMagicWords();
1024 $rawEntry = $magicWords[$mw->mId];
1025 }
1026 }
1027
1028 if( !is_array( $rawEntry ) ) {
1029 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
1030 }
1031 $mw->mCaseSensitive = $rawEntry[0];
1032 $mw->mSynonyms = array_slice( $rawEntry, 1 );
1033 }
1034
1035 /**
1036 * Italic is unsuitable for some languages
1037 *
1038 * @public
1039 *
1040 * @param string $text The text to be emphasized.
1041 * @return string
1042 */
1043 function emphasize( $text ) {
1044 return "<em>$text</em>";
1045 }
1046
1047 /**
1048 * Normally we output all numbers in plain en_US style, that is
1049 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
1050 * point twohundredthirtyfive. However this is not sutable for all
1051 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
1052 * Icelandic just want to use commas instead of dots, and dots instead
1053 * of commas like "293.291,235".
1054 *
1055 * An example of this function being called:
1056 * <code>
1057 * wfMsg( 'message', $wgLang->formatNum( $num ) )
1058 * </code>
1059 *
1060 * See LanguageGu.php for the Gujarati implementation and
1061 * LanguageIs.php for the , => . and . => , implementation.
1062 *
1063 * @todo check if it's viable to use localeconv() for the decimal
1064 * seperator thing.
1065 * @public
1066 * @param mixed $number the string to be formatted, should be an integer or
1067 * a floating point number.
1068 * @param bool $nocommafy Set to true for special numbers like dates
1069 * @return string
1070 */
1071 function formatNum( $number, $nocommafy = false ) {
1072 global $wgTranslateNumerals;
1073 if (!$nocommafy) {
1074 $number = $this->commafy($number);
1075 $s = $this->separatorTransformTable();
1076 if (!is_null($s)) { $number = strtr($number, $s); }
1077 }
1078
1079 if ($wgTranslateNumerals) {
1080 $s = $this->digitTransformTable();
1081 if (!is_null($s)) { $number = strtr($number, $s); }
1082 }
1083
1084 return $number;
1085 }
1086
1087 /**
1088 * Adds commas to a given number
1089 *
1090 * @param mixed $_
1091 * @return string
1092 */
1093 function commafy($_) {
1094 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
1095 }
1096
1097 function digitTransformTable() {
1098 $this->load();
1099 return $this->digitTransformTable;
1100 }
1101
1102 function separatorTransformTable() {
1103 $this->load();
1104 return $this->separatorTransformTable;
1105 }
1106
1107
1108 /**
1109 * For the credit list in includes/Credits.php (action=credits)
1110 *
1111 * @param array $l
1112 * @return string
1113 */
1114 function listToText( $l ) {
1115 $s = '';
1116 $m = count($l) - 1;
1117 for ($i = $m; $i >= 0; $i--) {
1118 if ($i == $m) {
1119 $s = $l[$i];
1120 } else if ($i == $m - 1) {
1121 $s = $l[$i] . ' ' . $this->getMessageFromDB( 'and' ) . ' ' . $s;
1122 } else {
1123 $s = $l[$i] . ', ' . $s;
1124 }
1125 }
1126 return $s;
1127 }
1128
1129 # Crop a string from the beginning or end to a certain number of bytes.
1130 # (Bytes are used because our storage has limited byte lengths for some
1131 # columns in the database.) Multibyte charsets will need to make sure that
1132 # only whole characters are included!
1133 #
1134 # $length does not include the optional ellipsis.
1135 # If $length is negative, snip from the beginning
1136 function truncate( $string, $length, $ellipsis = "" ) {
1137 if( $length == 0 ) {
1138 return $ellipsis;
1139 }
1140 if ( strlen( $string ) <= abs( $length ) ) {
1141 return $string;
1142 }
1143 if( $length > 0 ) {
1144 $string = substr( $string, 0, $length );
1145 $char = ord( $string[strlen( $string ) - 1] );
1146 if ($char >= 0xc0) {
1147 # We got the first byte only of a multibyte char; remove it.
1148 $string = substr( $string, 0, -1 );
1149 } elseif( $char >= 0x80 &&
1150 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
1151 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
1152 # We chopped in the middle of a character; remove it
1153 $string = $m[1];
1154 }
1155 return $string . $ellipsis;
1156 } else {
1157 $string = substr( $string, $length );
1158 $char = ord( $string[0] );
1159 if( $char >= 0x80 && $char < 0xc0 ) {
1160 # We chopped in the middle of a character; remove the whole thing
1161 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
1162 }
1163 return $ellipsis . $string;
1164 }
1165 }
1166
1167 /**
1168 * Grammatical transformations, needed for inflected languages
1169 * Invoked by putting {{grammar:case|word}} in a message
1170 *
1171 * @param string $word
1172 * @param string $case
1173 * @return string
1174 */
1175 function convertGrammar( $word, $case ) {
1176 global $wgGrammarForms;
1177 if ( isset($wgGrammarForms['en'][$case][$word]) ) {
1178 return $wgGrammarForms['en'][$case][$word];
1179 }
1180 return $word;
1181 }
1182
1183 /**
1184 * Plural form transformations, needed for some languages.
1185 * For example, where are 3 form of plural in Russian and Polish,
1186 * depending on "count mod 10". See [[w:Plural]]
1187 * For English it is pretty simple.
1188 *
1189 * Invoked by putting {{plural:count|wordform1|wordform2}}
1190 * or {{plural:count|wordform1|wordform2|wordform3}}
1191 *
1192 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
1193 *
1194 * @param integer $count
1195 * @param string $wordform1
1196 * @param string $wordform2
1197 * @param string $wordform3 (optional)
1198 * @return string
1199 */
1200 function convertPlural( $count, $w1, $w2, $w3) {
1201 return $count == '1' ? $w1 : $w2;
1202 }
1203
1204 /**
1205 * For translaing of expiry times
1206 * @param string The validated block time in English
1207 * @return Somehow translated block time
1208 * @see LanguageFi.php for example implementation
1209 */
1210 function translateBlockExpiry( $str ) {
1211
1212 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
1213
1214 if ( $scBlockExpiryOptions == '-') {
1215 return $str;
1216 }
1217
1218 foreach (explode(',', $scBlockExpiryOptions) as $option) {
1219 if ( strpos($option, ":") === false )
1220 continue;
1221 list($show, $value) = explode(":", $option);
1222 if ( strcmp ( $str, $value) == 0 )
1223 return '<span title="' . htmlspecialchars($str). '">' .
1224 htmlspecialchars( trim( $show ) ) . '</span>';
1225 }
1226
1227 return $str;
1228 }
1229
1230 /**
1231 * languages like Chinese need to be segmented in order for the diff
1232 * to be of any use
1233 *
1234 * @param string $text
1235 * @return string
1236 */
1237 function segmentForDiff( $text ) {
1238 return $text;
1239 }
1240
1241 /**
1242 * and unsegment to show the result
1243 *
1244 * @param string $text
1245 * @return string
1246 */
1247 function unsegmentForDiff( $text ) {
1248 return $text;
1249 }
1250
1251 # convert text to different variants of a language.
1252 function convert( $text, $isTitle = false) {
1253 return $this->mConverter->convert($text, $isTitle);
1254 }
1255
1256 # Convert text from within Parser
1257 function parserConvert( $text, &$parser ) {
1258 return $this->mConverter->parserConvert( $text, $parser );
1259 }
1260
1261 # Tell the converter that it shouldn't convert titles
1262 function setNoTitleConvert(){
1263 $this->mConverter->setNotitleConvert();
1264 }
1265
1266 # Check if this is a language with variants
1267 function hasVariants(){
1268 return sizeof($this->getVariants())>1;
1269 }
1270
1271
1272 /**
1273 * Perform output conversion on a string, and encode for safe HTML output.
1274 * @param string $text
1275 * @param bool $isTitle -- wtf?
1276 * @return string
1277 * @todo this should get integrated somewhere sane
1278 */
1279 function convertHtml( $text, $isTitle = false ) {
1280 return htmlspecialchars( $this->convert( $text, $isTitle ) );
1281 }
1282
1283 function convertCategoryKey( $key ) {
1284 return $this->mConverter->convertCategoryKey( $key );
1285 }
1286
1287 /**
1288 * get the list of variants supported by this langauge
1289 * see sample implementation in LanguageZh.php
1290 *
1291 * @return array an array of language codes
1292 */
1293 function getVariants() {
1294 return $this->mConverter->getVariants();
1295 }
1296
1297
1298 function getPreferredVariant( $fromUser = true ) {
1299 return $this->mConverter->getPreferredVariant( $fromUser );
1300 }
1301
1302 /**
1303 * if a language supports multiple variants, it is
1304 * possible that non-existing link in one variant
1305 * actually exists in another variant. this function
1306 * tries to find it. See e.g. LanguageZh.php
1307 *
1308 * @param string $link the name of the link
1309 * @param mixed $nt the title object of the link
1310 * @return null the input parameters may be modified upon return
1311 */
1312 function findVariantLink( &$link, &$nt ) {
1313 $this->mConverter->findVariantLink($link, $nt);
1314 }
1315
1316 /**
1317 * If a language supports multiple variants, converts text
1318 * into an array of all possible variants of the text:
1319 * 'variant' => text in that variant
1320 */
1321
1322 function convertLinkToAllVariants($text){
1323 return $this->mConverter->convertLinkToAllVariants($text);
1324 }
1325
1326
1327 /**
1328 * returns language specific options used by User::getPageRenderHash()
1329 * for example, the preferred language variant
1330 *
1331 * @return string
1332 * @public
1333 */
1334 function getExtraHashOptions() {
1335 return $this->mConverter->getExtraHashOptions();
1336 }
1337
1338 /**
1339 * for languages that support multiple variants, the title of an
1340 * article may be displayed differently in different variants. this
1341 * function returns the apporiate title defined in the body of the article.
1342 *
1343 * @return string
1344 */
1345 function getParsedTitle() {
1346 return $this->mConverter->getParsedTitle();
1347 }
1348
1349 /**
1350 * Enclose a string with the "no conversion" tag. This is used by
1351 * various functions in the Parser
1352 *
1353 * @param string $text text to be tagged for no conversion
1354 * @return string the tagged text
1355 */
1356 function markNoConversion( $text, $noParse=false ) {
1357 return $this->mConverter->markNoConversion( $text, $noParse );
1358 }
1359
1360 /**
1361 * A regular expression to match legal word-trailing characters
1362 * which should be merged onto a link of the form [[foo]]bar.
1363 *
1364 * @return string
1365 * @public
1366 */
1367 function linkTrail() {
1368 $this->load();
1369 return $this->linkTrail;
1370 }
1371
1372 function getLangObj() {
1373 return $this;
1374 }
1375
1376 /**
1377 * Get the RFC 3066 code for this language object
1378 */
1379 function getCode() {
1380 return $this->mCode;
1381 }
1382
1383 function setCode( $code ) {
1384 $this->mCode = $code;
1385 }
1386
1387 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
1388 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
1389 }
1390
1391 static function getLocalisationArray( $code, $disableCache = false ) {
1392 self::loadLocalisation( $code, $disableCache );
1393 return self::$mLocalisationCache[$code];
1394 }
1395
1396 /**
1397 * Load localisation data for a given code into the static cache
1398 *
1399 * @return array Dependencies, map of filenames to mtimes
1400 */
1401 static function loadLocalisation( $code, $disableCache = false ) {
1402 static $recursionGuard = array();
1403 global $wgMemc, $wgDBname, $IP;
1404
1405 if ( !$code ) {
1406 throw new MWException( "Invalid language code requested" );
1407 }
1408
1409 if ( !$disableCache ) {
1410 # Try the per-process cache
1411 if ( isset( self::$mLocalisationCache[$code] ) ) {
1412 return self::$mLocalisationCache[$code]['deps'];
1413 }
1414
1415 wfProfileIn( __METHOD__ );
1416
1417 # Try the serialized directory
1418 $cache = wfGetPrecompiledData( self::getFileName( "Messages", $code, '.ser' ) );
1419 if ( $cache ) {
1420 self::$mLocalisationCache[$code] = $cache;
1421 wfDebug( "Got localisation for $code from precompiled data file\n" );
1422 wfProfileOut( __METHOD__ );
1423 return self::$mLocalisationCache[$code]['deps'];
1424 }
1425
1426 # Try the global cache
1427 $memcKey = "$wgDBname:localisation:$code";
1428 $cache = $wgMemc->get( $memcKey );
1429 if ( $cache ) {
1430 $expired = false;
1431 # Check file modification times
1432 foreach ( $cache['deps'] as $file => $mtime ) {
1433 if ( filemtime( $file ) > $mtime ) {
1434 $expired = true;
1435 break;
1436 }
1437 }
1438 if ( self::isLocalisationOutOfDate( $cache ) ) {
1439 $wgMemc->delete( $memcKey );
1440 $cache = false;
1441 wfDebug( "Localisation cache for $code had expired due to update of $file\n" );
1442 } else {
1443 self::$mLocalisationCache[$code] = $cache;
1444 wfDebug( "Got localisation for $code from cache\n" );
1445 wfProfileOut( __METHOD__ );
1446 return $cache['deps'];
1447 }
1448 }
1449 } else {
1450 wfProfileIn( __METHOD__ );
1451 }
1452
1453 if ( $code != 'en' ) {
1454 $fallback = 'en';
1455 } else {
1456 $fallback = false;
1457 }
1458
1459 # Load the primary localisation from the source file
1460 global $IP;
1461 $filename = self::getFileName( "$IP/languages/Messages", $code, '.php' );
1462 if ( !file_exists( $filename ) ) {
1463 wfDebug( "No localisation file for $code, using implicit fallback to en\n" );
1464 $cache = array();
1465 $deps = array();
1466 } else {
1467 $deps = array( $filename => filemtime( $filename ) );
1468 require( $filename );
1469 $cache = compact( self::$mLocalisationKeys );
1470 wfDebug( "Got localisation for $code from source\n" );
1471 }
1472
1473 if ( !empty( $fallback ) ) {
1474 # Load the fallback localisation, with a circular reference guard
1475 if ( isset( $recursionGuard[$code] ) ) {
1476 throw new MWException( "Error: Circular fallback reference in language code $code" );
1477 }
1478 $recursionGuard[$code] = true;
1479 $newDeps = self::loadLocalisation( $fallback, $disableCache );
1480 unset( $recursionGuard[$code] );
1481
1482 $secondary = self::$mLocalisationCache[$fallback];
1483 $deps = array_merge( $deps, $newDeps );
1484
1485 # Merge the fallback localisation with the current localisation
1486 foreach ( self::$mLocalisationKeys as $key ) {
1487 if ( isset( $cache[$key] ) ) {
1488 if ( isset( $secondary[$key] ) ) {
1489 if ( in_array( $key, self::$mMergeableMapKeys ) ) {
1490 $cache[$key] = $cache[$key] + $secondary[$key];
1491 } elseif ( in_array( $key, self::$mMergeableListKeys ) ) {
1492 $cache[$key] = array_merge( $secondary[$key], $cache[$key] );
1493 }
1494 }
1495 } else {
1496 $cache[$key] = $secondary[$key];
1497 }
1498 }
1499
1500 # Merge bookstore lists if requested
1501 if ( !empty( $cache['bookstoreList']['inherit'] ) ) {
1502 $cache['bookstoreList'] = array_merge( $cache['bookstoreList'], $secondary['bookstoreList'] );
1503 }
1504 if ( isset( $cache['bookstoreList']['inherit'] ) ) {
1505 unset( $cache['bookstoreList']['inherit'] );
1506 }
1507 }
1508
1509 # Add dependencies to the cache entry
1510 $cache['deps'] = $deps;
1511
1512 # Replace spaces with underscores in namespace names
1513 $cache['namespaceNames'] = str_replace( ' ', '_', $cache['namespaceNames'] );
1514
1515 # Save to both caches
1516 self::$mLocalisationCache[$code] = $cache;
1517 if ( !$disableCache ) {
1518 $wgMemc->set( $memcKey, $cache );
1519 }
1520
1521 wfProfileOut( __METHOD__ );
1522 return $deps;
1523 }
1524
1525 /**
1526 * Test if a given localisation cache is out of date with respect to the
1527 * source Messages files. This is done automatically for the global cache
1528 * in $wgMemc, but is only done on certain occasions for the serialized
1529 * data file.
1530 *
1531 * @param $cache mixed Either a language code or a cache array
1532 */
1533 static function isLocalisationOutOfDate( $cache ) {
1534 if ( !is_array( $cache ) ) {
1535 self::loadLocalisation( $cache );
1536 $cache = self::$mLocalisationCache[$cache];
1537 }
1538 $expired = false;
1539 foreach ( $cache['deps'] as $file => $mtime ) {
1540 if ( filemtime( $file ) > $mtime ) {
1541 $expired = true;
1542 break;
1543 }
1544 }
1545 return $expired;
1546 }
1547
1548 /**
1549 * Get the fallback for a given language
1550 */
1551 static function getFallbackFor( $code ) {
1552 self::loadLocalisation( $code );
1553 return self::$mLocalisationCache[$code]['fallback'];
1554 }
1555
1556 /**
1557 * Get all messages for a given language
1558 */
1559 static function getMessagesFor( $code ) {
1560 self::loadLocalisation( $code );
1561 return self::$mLocalisationCache[$code]['messages'];
1562 }
1563
1564 /**
1565 * Get a message for a given language
1566 */
1567 static function getMessageFor( $key, $code ) {
1568 self::loadLocalisation( $code );
1569 return @self::$mLocalisationCache[$code]['messages'][$key];
1570 }
1571
1572 /**
1573 * Load localisation data for this object
1574 */
1575 function load() {
1576 if ( !$this->mLoaded ) {
1577 self::loadLocalisation( $this->getCode() );
1578 $cache =& self::$mLocalisationCache[$this->getCode()];
1579 foreach ( self::$mLocalisationKeys as $key ) {
1580 $this->$key = $cache[$key];
1581 }
1582 $this->mLoaded = true;
1583
1584 $this->fixUpSettings();
1585 }
1586 }
1587
1588 /**
1589 * Do any necessary post-cache-load settings adjustment
1590 */
1591 function fixUpSettings() {
1592 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk, $wgMessageCache,
1593 $wgNamespaceAliases, $wgAmericanDates;
1594 wfProfileIn( __METHOD__ );
1595 if ( $wgExtraNamespaces ) {
1596 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames;
1597 }
1598
1599 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
1600 if ( $wgMetaNamespaceTalk ) {
1601 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
1602 } else {
1603 $talk = $this->namespaceNames[NS_PROJECT_TALK];
1604 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
1605
1606 # Allow grammar transformations
1607 # Allowing full message-style parsing would make simple requests
1608 # such as action=raw much more expensive than they need to be.
1609 # This will hopefully cover most cases.
1610 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
1611 array( &$this, 'replaceGrammarInNamespace' ), $talk );
1612 $talk = str_replace( ' ', '_', $talk );
1613 $this->namespaceNames[NS_PROJECT_TALK] = $talk;
1614 }
1615
1616 # The above mixing may leave namespaces out of canonical order.
1617 # Re-order by namespace ID number...
1618 ksort( $this->namespaceNames );
1619
1620 # Put namespace names and aliases into a hashtable.
1621 # If this is too slow, then we should arrange it so that it is done
1622 # before caching. The catch is that at pre-cache time, the above
1623 # class-specific fixup hasn't been done.
1624 $this->mNamespaceIds = array();
1625 foreach ( $this->namespaceNames as $index => $name ) {
1626 $this->mNamespaceIds[$this->lc($name)] = $index;
1627 }
1628 if ( $this->namespaceAliases ) {
1629 foreach ( $this->namespaceAliases as $name => $index ) {
1630 $this->mNamespaceIds[$this->lc($name)] = $index;
1631 }
1632 }
1633 if ( $wgNamespaceAliases ) {
1634 foreach ( $wgNamespaceAliases as $name => $index ) {
1635 $this->mNamespaceIds[$this->lc($name)] = $index;
1636 }
1637 }
1638
1639 if ( $this->defaultDateFormat == 'dmy or mdy' ) {
1640 $this->defaultDateFormat = $wgAmericanDates ? 'mdy' : 'dmy';
1641 }
1642 wfProfileOut( __METHOD__ );
1643 }
1644
1645 function replaceGrammarInNamespace( $m ) {
1646 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
1647 }
1648
1649 static function getCaseMaps() {
1650 static $wikiUpperChars, $wikiLowerChars;
1651 global $IP;
1652 if ( isset( $wikiUpperChars ) ) {
1653 return array( $wikiUpperChars, $wikiLowerChars );
1654 }
1655
1656 wfProfileIn( __METHOD__ );
1657 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
1658 if ( $arr === false ) {
1659 throw new MWException(
1660 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
1661 }
1662 extract( $arr );
1663 wfProfileOut( __METHOD__ );
1664 return array( $wikiUpperChars, $wikiLowerChars );
1665 }
1666 }
1667
1668 ?>