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