Renamed message 'lastmodified' to 'lastmodifiedat' - see bug 6518 comment #8
[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 list( $wikiUpperChars ) = self::getCaseMaps();
727 return strtr( $matches[1], $wikiUpperChars );
728 }
729
730 function lcCallback($matches){
731 list( , $wikiLowerChars ) = self::getCaseMaps();
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 list( $wikiUpperChars ) = self::getCaseMaps();
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 if ( self::isMultibyte( $str ) ) {
802 $str = self::lc($str);
803
804 // regexp to find first letter in each word (i.e. after each space)
805 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
806
807 // function to use to capitalize a single char
808 if ( function_exists( 'mb_strtoupper' ) )
809 return preg_replace_callback(
810 $replaceRegexp,
811 array($this,"ucwordsCallbackMB"),
812 $str
813 );
814 else
815 return preg_replace_callback(
816 $replaceRegexp,
817 array($this,"ucwordsCallbackWiki"),
818 $str
819 );
820 }
821 else
822 return ucwords( strtolower( $str ) );
823 }
824
825 # capitalize words at word breaks
826 function ucwordbreaks($str){
827 if (self::isMultibyte( $str ) ) {
828 $str = self::lc($str);
829
830 // since \b doesn't work for UTF-8, we explicitely define word break chars
831 $breaks= "[ \-\(\)\}\{\.,\?!]";
832
833 // find first letter after word break
834 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
835
836 if ( function_exists( 'mb_strtoupper' ) )
837 return preg_replace_callback(
838 $replaceRegexp,
839 array($this,"ucwordbreaksCallbackMB"),
840 $str
841 );
842 else
843 return preg_replace_callback(
844 $replaceRegexp,
845 array($this,"ucwordsCallbackWiki"),
846 $str
847 );
848 }
849 else
850 return preg_replace_callback(
851 '/\b([\w\x80-\xff]+)\b/',
852 array($this,"ucwordbreaksCallbackAscii"),
853 $str );
854 }
855
856 function checkTitleEncoding( $s ) {
857 if( is_array( $s ) ) {
858 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
859 }
860 # Check for non-UTF-8 URLs
861 $ishigh = preg_match( '/[\x80-\xff]/', $s);
862 if(!$ishigh) return $s;
863
864 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
865 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
866 if( $isutf8 ) return $s;
867
868 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
869 }
870
871 function fallback8bitEncoding() {
872 $this->load();
873 return $this->fallback8bitEncoding;
874 }
875
876 /**
877 * Some languages have special punctuation to strip out
878 * or characters which need to be converted for MySQL's
879 * indexing to grok it correctly. Make such changes here.
880 *
881 * @param string $in
882 * @return string
883 */
884 function stripForSearch( $string ) {
885 # MySQL fulltext index doesn't grok utf-8, so we
886 # need to fold cases and convert to hex
887
888 wfProfileIn( __METHOD__ );
889 if( function_exists( 'mb_strtolower' ) ) {
890 $out = preg_replace(
891 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
892 "'U8' . bin2hex( \"$1\" )",
893 mb_strtolower( $string ) );
894 } else {
895 list( , $wikiLowerChars ) = self::getCaseMaps();
896 $out = preg_replace(
897 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
898 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
899 $string );
900 }
901 wfProfileOut( __METHOD__ );
902 return $out;
903 }
904
905 function convertForSearchResult( $termsArray ) {
906 # some languages, e.g. Chinese, need to do a conversion
907 # in order for search results to be displayed correctly
908 return $termsArray;
909 }
910
911 /**
912 * Get the first character of a string.
913 *
914 * @param string $s
915 * @return string
916 */
917 function firstChar( $s ) {
918 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
919 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
920
921 return isset( $matches[1] ) ? $matches[1] : "";
922 }
923
924 function initEncoding() {
925 # Some languages may have an alternate char encoding option
926 # (Esperanto X-coding, Japanese furigana conversion, etc)
927 # If this language is used as the primary content language,
928 # an override to the defaults can be set here on startup.
929 }
930
931 function recodeForEdit( $s ) {
932 # For some languages we'll want to explicitly specify
933 # which characters make it into the edit box raw
934 # or are converted in some way or another.
935 # Note that if wgOutputEncoding is different from
936 # wgInputEncoding, this text will be further converted
937 # to wgOutputEncoding.
938 global $wgEditEncoding;
939 if( $wgEditEncoding == '' or
940 $wgEditEncoding == 'UTF-8' ) {
941 return $s;
942 } else {
943 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
944 }
945 }
946
947 function recodeInput( $s ) {
948 # Take the previous into account.
949 global $wgEditEncoding;
950 if($wgEditEncoding != "") {
951 $enc = $wgEditEncoding;
952 } else {
953 $enc = 'UTF-8';
954 }
955 if( $enc == 'UTF-8' ) {
956 return $s;
957 } else {
958 return $this->iconv( $enc, 'UTF-8', $s );
959 }
960 }
961
962 /**
963 * For right-to-left language support
964 *
965 * @return bool
966 */
967 function isRTL() {
968 $this->load();
969 return $this->rtl;
970 }
971
972 /**
973 * A hidden direction mark (LRM or RLM), depending on the language direction
974 *
975 * @return string
976 */
977 function getDirMark() {
978 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
979 }
980
981 /**
982 * An arrow, depending on the language direction
983 *
984 * @return string
985 */
986 function getArrow() {
987 return $this->isRTL() ? '←' : '→';
988 }
989
990 /**
991 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
992 *
993 * @return bool
994 */
995 function linkPrefixExtension() {
996 $this->load();
997 return $this->linkPrefixExtension;
998 }
999
1000 function &getMagicWords() {
1001 $this->load();
1002 return $this->magicWords;
1003 }
1004
1005 # Fill a MagicWord object with data from here
1006 function getMagic( &$mw ) {
1007 if ( !isset( $this->mMagicExtensions ) ) {
1008 $this->mMagicExtensions = array();
1009 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
1010 }
1011 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
1012 $rawEntry = $this->mMagicExtensions[$mw->mId];
1013 } else {
1014 $magicWords =& $this->getMagicWords();
1015 if ( isset( $magicWords[$mw->mId] ) ) {
1016 $rawEntry = $magicWords[$mw->mId];
1017 } else {
1018 # Fall back to English if local list is incomplete
1019 $magicWords =& Language::getMagicWords();
1020 $rawEntry = $magicWords[$mw->mId];
1021 }
1022 }
1023
1024 if( !is_array( $rawEntry ) ) {
1025 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
1026 }
1027 $mw->mCaseSensitive = $rawEntry[0];
1028 $mw->mSynonyms = array_slice( $rawEntry, 1 );
1029 }
1030
1031 /**
1032 * Italic is unsuitable for some languages
1033 *
1034 * @public
1035 *
1036 * @param string $text The text to be emphasized.
1037 * @return string
1038 */
1039 function emphasize( $text ) {
1040 return "<em>$text</em>";
1041 }
1042
1043 /**
1044 * Normally we output all numbers in plain en_US style, that is
1045 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
1046 * point twohundredthirtyfive. However this is not sutable for all
1047 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
1048 * Icelandic just want to use commas instead of dots, and dots instead
1049 * of commas like "293.291,235".
1050 *
1051 * An example of this function being called:
1052 * <code>
1053 * wfMsg( 'message', $wgLang->formatNum( $num ) )
1054 * </code>
1055 *
1056 * See LanguageGu.php for the Gujarati implementation and
1057 * LanguageIs.php for the , => . and . => , implementation.
1058 *
1059 * @todo check if it's viable to use localeconv() for the decimal
1060 * seperator thing.
1061 * @public
1062 * @param mixed $number the string to be formatted, should be an integer or
1063 * a floating point number.
1064 * @param bool $nocommafy Set to true for special numbers like dates
1065 * @return string
1066 */
1067 function formatNum( $number, $nocommafy = false ) {
1068 global $wgTranslateNumerals;
1069 if (!$nocommafy) {
1070 $number = $this->commafy($number);
1071 $s = $this->separatorTransformTable();
1072 if (!is_null($s)) { $number = strtr($number, $s); }
1073 }
1074
1075 if ($wgTranslateNumerals) {
1076 $s = $this->digitTransformTable();
1077 if (!is_null($s)) { $number = strtr($number, $s); }
1078 }
1079
1080 return $number;
1081 }
1082
1083 /**
1084 * Adds commas to a given number
1085 *
1086 * @param mixed $_
1087 * @return string
1088 */
1089 function commafy($_) {
1090 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
1091 }
1092
1093 function digitTransformTable() {
1094 $this->load();
1095 return $this->digitTransformTable;
1096 }
1097
1098 function separatorTransformTable() {
1099 $this->load();
1100 return $this->separatorTransformTable;
1101 }
1102
1103
1104 /**
1105 * For the credit list in includes/Credits.php (action=credits)
1106 *
1107 * @param array $l
1108 * @return string
1109 */
1110 function listToText( $l ) {
1111 $s = '';
1112 $m = count($l) - 1;
1113 for ($i = $m; $i >= 0; $i--) {
1114 if ($i == $m) {
1115 $s = $l[$i];
1116 } else if ($i == $m - 1) {
1117 $s = $l[$i] . ' ' . $this->getMessageFromDB( 'and' ) . ' ' . $s;
1118 } else {
1119 $s = $l[$i] . ', ' . $s;
1120 }
1121 }
1122 return $s;
1123 }
1124
1125 # Crop a string from the beginning or end to a certain number of bytes.
1126 # (Bytes are used because our storage has limited byte lengths for some
1127 # columns in the database.) Multibyte charsets will need to make sure that
1128 # only whole characters are included!
1129 #
1130 # $length does not include the optional ellipsis.
1131 # If $length is negative, snip from the beginning
1132 function truncate( $string, $length, $ellipsis = "" ) {
1133 if( $length == 0 ) {
1134 return $ellipsis;
1135 }
1136 if ( strlen( $string ) <= abs( $length ) ) {
1137 return $string;
1138 }
1139 if( $length > 0 ) {
1140 $string = substr( $string, 0, $length );
1141 $char = ord( $string[strlen( $string ) - 1] );
1142 if ($char >= 0xc0) {
1143 # We got the first byte only of a multibyte char; remove it.
1144 $string = substr( $string, 0, -1 );
1145 } elseif( $char >= 0x80 &&
1146 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
1147 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
1148 # We chopped in the middle of a character; remove it
1149 $string = $m[1];
1150 }
1151 return $string . $ellipsis;
1152 } else {
1153 $string = substr( $string, $length );
1154 $char = ord( $string[0] );
1155 if( $char >= 0x80 && $char < 0xc0 ) {
1156 # We chopped in the middle of a character; remove the whole thing
1157 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
1158 }
1159 return $ellipsis . $string;
1160 }
1161 }
1162
1163 /**
1164 * Grammatical transformations, needed for inflected languages
1165 * Invoked by putting {{grammar:case|word}} in a message
1166 *
1167 * @param string $word
1168 * @param string $case
1169 * @return string
1170 */
1171 function convertGrammar( $word, $case ) {
1172 global $wgGrammarForms;
1173 if ( isset($wgGrammarForms['en'][$case][$word]) ) {
1174 return $wgGrammarForms['en'][$case][$word];
1175 }
1176 return $word;
1177 }
1178
1179 /**
1180 * Plural form transformations, needed for some languages.
1181 * For example, where are 3 form of plural in Russian and Polish,
1182 * depending on "count mod 10". See [[w:Plural]]
1183 * For English it is pretty simple.
1184 *
1185 * Invoked by putting {{plural:count|wordform1|wordform2}}
1186 * or {{plural:count|wordform1|wordform2|wordform3}}
1187 *
1188 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
1189 *
1190 * @param integer $count
1191 * @param string $wordform1
1192 * @param string $wordform2
1193 * @param string $wordform3 (optional)
1194 * @return string
1195 */
1196 function convertPlural( $count, $w1, $w2, $w3) {
1197 return $count == '1' ? $w1 : $w2;
1198 }
1199
1200 /**
1201 * For translaing of expiry times
1202 * @param string The validated block time in English
1203 * @return Somehow translated block time
1204 * @see LanguageFi.php for example implementation
1205 */
1206 function translateBlockExpiry( $str ) {
1207
1208 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
1209
1210 if ( $scBlockExpiryOptions == '-') {
1211 return $str;
1212 }
1213
1214 foreach (explode(',', $scBlockExpiryOptions) as $option) {
1215 if ( strpos($option, ":") === false )
1216 continue;
1217 list($show, $value) = explode(":", $option);
1218 if ( strcmp ( $str, $value) == 0 )
1219 return '<span title="' . htmlspecialchars($str). '">' .
1220 htmlspecialchars( trim( $show ) ) . '</span>';
1221 }
1222
1223 return $str;
1224 }
1225
1226 /**
1227 * languages like Chinese need to be segmented in order for the diff
1228 * to be of any use
1229 *
1230 * @param string $text
1231 * @return string
1232 */
1233 function segmentForDiff( $text ) {
1234 return $text;
1235 }
1236
1237 /**
1238 * and unsegment to show the result
1239 *
1240 * @param string $text
1241 * @return string
1242 */
1243 function unsegmentForDiff( $text ) {
1244 return $text;
1245 }
1246
1247 # convert text to different variants of a language.
1248 function convert( $text, $isTitle = false) {
1249 return $this->mConverter->convert($text, $isTitle);
1250 }
1251
1252 # Convert text from within Parser
1253 function parserConvert( $text, &$parser ) {
1254 return $this->mConverter->parserConvert( $text, $parser );
1255 }
1256
1257 # Tell the converter that it shouldn't convert titles
1258 function setNoTitleConvert(){
1259 $this->mConverter->setNotitleConvert();
1260 }
1261
1262 # Check if this is a language with variants
1263 function hasVariants(){
1264 return sizeof($this->getVariants())>1;
1265 }
1266
1267
1268 /**
1269 * Perform output conversion on a string, and encode for safe HTML output.
1270 * @param string $text
1271 * @param bool $isTitle -- wtf?
1272 * @return string
1273 * @todo this should get integrated somewhere sane
1274 */
1275 function convertHtml( $text, $isTitle = false ) {
1276 return htmlspecialchars( $this->convert( $text, $isTitle ) );
1277 }
1278
1279 function convertCategoryKey( $key ) {
1280 return $this->mConverter->convertCategoryKey( $key );
1281 }
1282
1283 /**
1284 * get the list of variants supported by this langauge
1285 * see sample implementation in LanguageZh.php
1286 *
1287 * @return array an array of language codes
1288 */
1289 function getVariants() {
1290 return $this->mConverter->getVariants();
1291 }
1292
1293
1294 function getPreferredVariant( $fromUser = true ) {
1295 return $this->mConverter->getPreferredVariant( $fromUser );
1296 }
1297
1298 /**
1299 * if a language supports multiple variants, it is
1300 * possible that non-existing link in one variant
1301 * actually exists in another variant. this function
1302 * tries to find it. See e.g. LanguageZh.php
1303 *
1304 * @param string $link the name of the link
1305 * @param mixed $nt the title object of the link
1306 * @return null the input parameters may be modified upon return
1307 */
1308 function findVariantLink( &$link, &$nt ) {
1309 $this->mConverter->findVariantLink($link, $nt);
1310 }
1311
1312 /**
1313 * If a language supports multiple variants, converts text
1314 * into an array of all possible variants of the text:
1315 * 'variant' => text in that variant
1316 */
1317
1318 function convertLinkToAllVariants($text){
1319 return $this->mConverter->convertLinkToAllVariants($text);
1320 }
1321
1322
1323 /**
1324 * returns language specific options used by User::getPageRenderHash()
1325 * for example, the preferred language variant
1326 *
1327 * @return string
1328 * @public
1329 */
1330 function getExtraHashOptions() {
1331 return $this->mConverter->getExtraHashOptions();
1332 }
1333
1334 /**
1335 * for languages that support multiple variants, the title of an
1336 * article may be displayed differently in different variants. this
1337 * function returns the apporiate title defined in the body of the article.
1338 *
1339 * @return string
1340 */
1341 function getParsedTitle() {
1342 return $this->mConverter->getParsedTitle();
1343 }
1344
1345 /**
1346 * Enclose a string with the "no conversion" tag. This is used by
1347 * various functions in the Parser
1348 *
1349 * @param string $text text to be tagged for no conversion
1350 * @return string the tagged text
1351 */
1352 function markNoConversion( $text, $noParse=false ) {
1353 return $this->mConverter->markNoConversion( $text, $noParse );
1354 }
1355
1356 /**
1357 * A regular expression to match legal word-trailing characters
1358 * which should be merged onto a link of the form [[foo]]bar.
1359 *
1360 * @return string
1361 * @public
1362 */
1363 function linkTrail() {
1364 $this->load();
1365 return $this->linkTrail;
1366 }
1367
1368 function getLangObj() {
1369 return $this;
1370 }
1371
1372 /**
1373 * Get the RFC 3066 code for this language object
1374 */
1375 function getCode() {
1376 return $this->mCode;
1377 }
1378
1379 function setCode( $code ) {
1380 $this->mCode = $code;
1381 }
1382
1383 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
1384 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
1385 }
1386
1387 static function getLocalisationArray( $code, $disableCache = false ) {
1388 self::loadLocalisation( $code, $disableCache );
1389 return self::$mLocalisationCache[$code];
1390 }
1391
1392 /**
1393 * Load localisation data for a given code into the static cache
1394 *
1395 * @return array Dependencies, map of filenames to mtimes
1396 */
1397 static function loadLocalisation( $code, $disableCache = false ) {
1398 static $recursionGuard = array();
1399 global $wgMemc, $wgDBname, $IP;
1400
1401 if ( !$code ) {
1402 throw new MWException( "Invalid language code requested" );
1403 }
1404
1405 if ( !$disableCache ) {
1406 # Try the per-process cache
1407 if ( isset( self::$mLocalisationCache[$code] ) ) {
1408 return self::$mLocalisationCache[$code]['deps'];
1409 }
1410
1411 wfProfileIn( __METHOD__ );
1412
1413 # Try the serialized directory
1414 $cache = wfGetPrecompiledData( self::getFileName( "Messages", $code, '.ser' ) );
1415 if ( $cache ) {
1416 self::$mLocalisationCache[$code] = $cache;
1417 wfDebug( "Got localisation for $code from precompiled data file\n" );
1418 wfProfileOut( __METHOD__ );
1419 return self::$mLocalisationCache[$code]['deps'];
1420 }
1421
1422 # Try the global cache
1423 $memcKey = "$wgDBname:localisation:$code";
1424 $cache = $wgMemc->get( $memcKey );
1425 if ( $cache ) {
1426 $expired = false;
1427 # Check file modification times
1428 foreach ( $cache['deps'] as $file => $mtime ) {
1429 if ( filemtime( $file ) > $mtime ) {
1430 $expired = true;
1431 break;
1432 }
1433 }
1434 if ( self::isLocalisationOutOfDate( $cache ) ) {
1435 $wgMemc->delete( $memcKey );
1436 $cache = false;
1437 wfDebug( "Localisation cache for $code had expired due to update of $file\n" );
1438 } else {
1439 self::$mLocalisationCache[$code] = $cache;
1440 wfDebug( "Got localisation for $code from cache\n" );
1441 wfProfileOut( __METHOD__ );
1442 return $cache['deps'];
1443 }
1444 }
1445 } else {
1446 wfProfileIn( __METHOD__ );
1447 }
1448
1449 if ( $code != 'en' ) {
1450 $fallback = 'en';
1451 } else {
1452 $fallback = false;
1453 }
1454
1455 # Load the primary localisation from the source file
1456 global $IP;
1457 $filename = self::getFileName( "$IP/languages/Messages", $code, '.php' );
1458 if ( !file_exists( $filename ) ) {
1459 wfDebug( "No localisation file for $code, using implicit fallback to en\n" );
1460 $cache = array();
1461 $deps = array();
1462 } else {
1463 $deps = array( $filename => filemtime( $filename ) );
1464 require( $filename );
1465 $cache = compact( self::$mLocalisationKeys );
1466 wfDebug( "Got localisation for $code from source\n" );
1467 }
1468
1469 if ( !empty( $fallback ) ) {
1470 # Load the fallback localisation, with a circular reference guard
1471 if ( isset( $recursionGuard[$code] ) ) {
1472 throw new MWException( "Error: Circular fallback reference in language code $code" );
1473 }
1474 $recursionGuard[$code] = true;
1475 $newDeps = self::loadLocalisation( $fallback, $disableCache );
1476 unset( $recursionGuard[$code] );
1477
1478 $secondary = self::$mLocalisationCache[$fallback];
1479 $deps = array_merge( $deps, $newDeps );
1480
1481 # Merge the fallback localisation with the current localisation
1482 foreach ( self::$mLocalisationKeys as $key ) {
1483 if ( isset( $cache[$key] ) ) {
1484 if ( isset( $secondary[$key] ) ) {
1485 if ( in_array( $key, self::$mMergeableMapKeys ) ) {
1486 $cache[$key] = $cache[$key] + $secondary[$key];
1487 } elseif ( in_array( $key, self::$mMergeableListKeys ) ) {
1488 $cache[$key] = array_merge( $secondary[$key], $cache[$key] );
1489 }
1490 }
1491 } else {
1492 $cache[$key] = $secondary[$key];
1493 }
1494 }
1495
1496 # Merge bookstore lists if requested
1497 if ( !empty( $cache['bookstoreList']['inherit'] ) ) {
1498 $cache['bookstoreList'] = array_merge( $cache['bookstoreList'], $secondary['bookstoreList'] );
1499 }
1500 if ( isset( $cache['bookstoreList']['inherit'] ) ) {
1501 unset( $cache['bookstoreList']['inherit'] );
1502 }
1503 }
1504
1505 # Add dependencies to the cache entry
1506 $cache['deps'] = $deps;
1507
1508 # Replace spaces with underscores in namespace names
1509 $cache['namespaceNames'] = str_replace( ' ', '_', $cache['namespaceNames'] );
1510
1511 # Save to both caches
1512 self::$mLocalisationCache[$code] = $cache;
1513 if ( !$disableCache ) {
1514 $wgMemc->set( $memcKey, $cache );
1515 }
1516
1517 wfProfileOut( __METHOD__ );
1518 return $deps;
1519 }
1520
1521 /**
1522 * Test if a given localisation cache is out of date with respect to the
1523 * source Messages files. This is done automatically for the global cache
1524 * in $wgMemc, but is only done on certain occasions for the serialized
1525 * data file.
1526 *
1527 * @param $cache mixed Either a language code or a cache array
1528 */
1529 static function isLocalisationOutOfDate( $cache ) {
1530 if ( !is_array( $cache ) ) {
1531 self::loadLocalisation( $cache );
1532 $cache = self::$mLocalisationCache[$cache];
1533 }
1534 $expired = false;
1535 foreach ( $cache['deps'] as $file => $mtime ) {
1536 if ( filemtime( $file ) > $mtime ) {
1537 $expired = true;
1538 break;
1539 }
1540 }
1541 return $expired;
1542 }
1543
1544 /**
1545 * Get the fallback for a given language
1546 */
1547 static function getFallbackFor( $code ) {
1548 self::loadLocalisation( $code );
1549 return self::$mLocalisationCache[$code]['fallback'];
1550 }
1551
1552 /**
1553 * Get all messages for a given language
1554 */
1555 static function getMessagesFor( $code ) {
1556 self::loadLocalisation( $code );
1557 return self::$mLocalisationCache[$code]['messages'];
1558 }
1559
1560 /**
1561 * Get a message for a given language
1562 */
1563 static function getMessageFor( $key, $code ) {
1564 self::loadLocalisation( $code );
1565 return @self::$mLocalisationCache[$code]['messages'][$key];
1566 }
1567
1568 /**
1569 * Load localisation data for this object
1570 */
1571 function load() {
1572 if ( !$this->mLoaded ) {
1573 self::loadLocalisation( $this->getCode() );
1574 $cache =& self::$mLocalisationCache[$this->getCode()];
1575 foreach ( self::$mLocalisationKeys as $key ) {
1576 $this->$key = $cache[$key];
1577 }
1578 $this->mLoaded = true;
1579
1580 $this->fixUpSettings();
1581 }
1582 }
1583
1584 /**
1585 * Do any necessary post-cache-load settings adjustment
1586 */
1587 function fixUpSettings() {
1588 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk, $wgMessageCache,
1589 $wgNamespaceAliases, $wgAmericanDates;
1590 wfProfileIn( __METHOD__ );
1591 if ( $wgExtraNamespaces ) {
1592 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames;
1593 }
1594
1595 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
1596 if ( $wgMetaNamespaceTalk ) {
1597 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
1598 } else {
1599 $talk = $this->namespaceNames[NS_PROJECT_TALK];
1600 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
1601
1602 # Allow grammar transformations
1603 # Allowing full message-style parsing would make simple requests
1604 # such as action=raw much more expensive than they need to be.
1605 # This will hopefully cover most cases.
1606 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
1607 array( &$this, 'replaceGrammarInNamespace' ), $talk );
1608 $talk = str_replace( ' ', '_', $talk );
1609 $this->namespaceNames[NS_PROJECT_TALK] = $talk;
1610 }
1611
1612 # The above mixing may leave namespaces out of canonical order.
1613 # Re-order by namespace ID number...
1614 ksort( $this->namespaceNames );
1615
1616 # Put namespace names and aliases into a hashtable.
1617 # If this is too slow, then we should arrange it so that it is done
1618 # before caching. The catch is that at pre-cache time, the above
1619 # class-specific fixup hasn't been done.
1620 $this->mNamespaceIds = array();
1621 foreach ( $this->namespaceNames as $index => $name ) {
1622 $this->mNamespaceIds[$this->lc($name)] = $index;
1623 }
1624 if ( $this->namespaceAliases ) {
1625 foreach ( $this->namespaceAliases as $name => $index ) {
1626 $this->mNamespaceIds[$this->lc($name)] = $index;
1627 }
1628 }
1629 if ( $wgNamespaceAliases ) {
1630 foreach ( $wgNamespaceAliases as $name => $index ) {
1631 $this->mNamespaceIds[$this->lc($name)] = $index;
1632 }
1633 }
1634
1635 if ( $this->defaultDateFormat == 'dmy or mdy' ) {
1636 $this->defaultDateFormat = $wgAmericanDates ? 'mdy' : 'dmy';
1637 }
1638 wfProfileOut( __METHOD__ );
1639 }
1640
1641 function replaceGrammarInNamespace( $m ) {
1642 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
1643 }
1644
1645 static function getCaseMaps() {
1646 static $wikiUpperChars, $wikiLowerChars;
1647 global $IP;
1648 if ( isset( $wikiUpperChars ) ) {
1649 return array( $wikiUpperChars, $wikiLowerChars );
1650 }
1651
1652 wfProfileIn( __METHOD__ );
1653 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
1654 if ( $arr === false ) {
1655 throw new MWException(
1656 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
1657 }
1658 extract( $arr );
1659 wfProfileOut( __METHOD__ );
1660 return array( $wikiUpperChars, $wikiLowerChars );
1661 }
1662 }
1663
1664 ?>