Change message 'copyrightpage' to use {{ns:project}} per r27918
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * @addtogroup Language
4 */
5
6 if( !defined( 'MEDIAWIKI' ) ) {
7 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
8 exit( 1 );
9 }
10
11 # Read language names
12 global $wgLanguageNames;
13 require_once( dirname(__FILE__) . '/Names.php' ) ;
14
15 global $wgInputEncoding, $wgOutputEncoding;
16
17 /**
18 * These are always UTF-8, they exist only for backwards compatibility
19 */
20 $wgInputEncoding = "UTF-8";
21 $wgOutputEncoding = "UTF-8";
22
23 if( function_exists( 'mb_strtoupper' ) ) {
24 mb_internal_encoding('UTF-8');
25 }
26
27 /* a fake language converter */
28 class FakeConverter {
29 var $mLang;
30 function FakeConverter($langobj) {$this->mLang = $langobj;}
31 function convert($t, $i) {return $t;}
32 function parserConvert($t, $p) {return $t;}
33 function getVariants() { return array( $this->mLang->getCode() ); }
34 function getPreferredVariant() {return $this->mLang->getCode(); }
35 function findVariantLink(&$l, &$n) {}
36 function getExtraHashOptions() {return '';}
37 function getParsedTitle() {return '';}
38 function markNoConversion($text, $noParse=false) {return $text;}
39 function convertCategoryKey( $key ) {return $key; }
40 function convertLinkToAllVariants($text){ return array( $this->mLang->getCode() => $text); }
41 function armourMath($text){ return $text; }
42 }
43
44 #--------------------------------------------------------------------------
45 # Internationalisation code
46 #--------------------------------------------------------------------------
47
48 class Language {
49 var $mConverter, $mVariants, $mCode, $mLoaded = false;
50 var $mMagicExtensions = array(), $mMagicHookDone = false;
51
52 static public $mLocalisationKeys = array( 'fallback', 'namespaceNames',
53 'skinNames', 'mathNames',
54 'bookstoreList', 'magicWords', 'messages', 'rtl', 'digitTransformTable',
55 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
56 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
57 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
58 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases' );
59
60 static public $mMergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
61 'dateFormats', 'defaultUserOptionOverrides', 'magicWords' );
62
63 static public $mMergeableListKeys = array( 'extraUserToggles' );
64
65 static public $mMergeableAliasListKeys = array( 'specialPageAliases' );
66
67 static public $mLocalisationCache = array();
68
69 static public $mWeekdayMsgs = array(
70 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
71 'friday', 'saturday'
72 );
73
74 static public $mWeekdayAbbrevMsgs = array(
75 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
76 );
77
78 static public $mMonthMsgs = array(
79 'january', 'february', 'march', 'april', 'may_long', 'june',
80 'july', 'august', 'september', 'october', 'november',
81 'december'
82 );
83 static public $mMonthGenMsgs = array(
84 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
85 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
86 'december-gen'
87 );
88 static public $mMonthAbbrevMsgs = array(
89 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
90 'sep', 'oct', 'nov', 'dec'
91 );
92
93 static public $mIranianCalendarMonthMsgs = array(
94 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
95 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
96 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
97 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
98 );
99
100 static public $mHebrewCalendarMonthMsgs = array(
101 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
102 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
103 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
104 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
105 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
106 );
107
108 static public $mHebrewCalendarMonthGenMsgs = array(
109 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
110 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
111 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
112 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
113 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
114 );
115
116 /**
117 * Create a language object for a given language code
118 */
119 static function factory( $code ) {
120 global $IP;
121 static $recursionLevel = 0;
122
123 if ( $code == 'en' ) {
124 $class = 'Language';
125 } else {
126 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
127 // Preload base classes to work around APC/PHP5 bug
128 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
129 include_once("$IP/languages/classes/$class.deps.php");
130 }
131 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
132 include_once("$IP/languages/classes/$class.php");
133 }
134 }
135
136 if ( $recursionLevel > 5 ) {
137 throw new MWException( "Language fallback loop detected when creating class $class\n" );
138 }
139
140 if( ! class_exists( $class ) ) {
141 $fallback = Language::getFallbackFor( $code );
142 ++$recursionLevel;
143 $lang = Language::factory( $fallback );
144 --$recursionLevel;
145 $lang->setCode( $code );
146 } else {
147 $lang = new $class;
148 }
149
150 return $lang;
151 }
152
153 function __construct() {
154 $this->mConverter = new FakeConverter($this);
155 // Set the code to the name of the descendant
156 if ( get_class( $this ) == 'Language' ) {
157 $this->mCode = 'en';
158 } else {
159 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
160 }
161 }
162
163 /**
164 * Hook which will be called if this is the content language.
165 * Descendants can use this to register hook functions or modify globals
166 */
167 function initContLang() {}
168
169 /**
170 * @deprecated
171 * @return array
172 */
173 function getDefaultUserOptions() {
174 return User::getDefaultOptions();
175 }
176
177 function getFallbackLanguageCode() {
178 $this->load();
179 return $this->fallback;
180 }
181
182 /**
183 * Exports $wgBookstoreListEn
184 * @return array
185 */
186 function getBookstoreList() {
187 $this->load();
188 return $this->bookstoreList;
189 }
190
191 /**
192 * @return array
193 */
194 function getNamespaces() {
195 $this->load();
196 return $this->namespaceNames;
197 }
198
199 /**
200 * A convenience function that returns the same thing as
201 * getNamespaces() except with the array values changed to ' '
202 * where it found '_', useful for producing output to be displayed
203 * e.g. in <select> forms.
204 *
205 * @return array
206 */
207 function getFormattedNamespaces() {
208 $ns = $this->getNamespaces();
209 foreach($ns as $k => $v) {
210 $ns[$k] = strtr($v, '_', ' ');
211 }
212 return $ns;
213 }
214
215 /**
216 * Get a namespace value by key
217 * <code>
218 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
219 * echo $mw_ns; // prints 'MediaWiki'
220 * </code>
221 *
222 * @param int $index the array key of the namespace to return
223 * @return mixed, string if the namespace value exists, otherwise false
224 */
225 function getNsText( $index ) {
226 $ns = $this->getNamespaces();
227 return isset( $ns[$index] ) ? $ns[$index] : false;
228 }
229
230 /**
231 * A convenience function that returns the same thing as
232 * getNsText() except with '_' changed to ' ', useful for
233 * producing output.
234 *
235 * @return array
236 */
237 function getFormattedNsText( $index ) {
238 $ns = $this->getNsText( $index );
239 return strtr($ns, '_', ' ');
240 }
241
242 /**
243 * Get a namespace key by value, case insensitive.
244 * Only matches namespace names for the current language, not the
245 * canonical ones defined in Namespace.php.
246 *
247 * @param string $text
248 * @return mixed An integer if $text is a valid value otherwise false
249 */
250 function getLocalNsIndex( $text ) {
251 $this->load();
252 $lctext = $this->lc($text);
253 return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
254 }
255
256 /**
257 * Get a namespace key by value, case insensitive. Canonical namespace
258 * names override custom ones defined for the current language.
259 *
260 * @param string $text
261 * @return mixed An integer if $text is a valid value otherwise false
262 */
263 function getNsIndex( $text ) {
264 $this->load();
265 $lctext = $this->lc($text);
266 if( ( $ns = Namespace::getCanonicalIndex( $lctext ) ) !== null ) return $ns;
267 return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
268 }
269
270 /**
271 * short names for language variants used for language conversion links.
272 *
273 * @param string $code
274 * @return string
275 */
276 function getVariantname( $code ) {
277 return $this->getMessageFromDB( "variantname-$code" );
278 }
279
280 function specialPage( $name ) {
281 $aliases = $this->getSpecialPageAliases();
282 if ( isset( $aliases[$name][0] ) ) {
283 $name = $aliases[$name][0];
284 }
285 return $this->getNsText(NS_SPECIAL) . ':' . $name;
286 }
287
288 function getQuickbarSettings() {
289 return array(
290 $this->getMessage( 'qbsettings-none' ),
291 $this->getMessage( 'qbsettings-fixedleft' ),
292 $this->getMessage( 'qbsettings-fixedright' ),
293 $this->getMessage( 'qbsettings-floatingleft' ),
294 $this->getMessage( 'qbsettings-floatingright' )
295 );
296 }
297
298 function getSkinNames() {
299 $this->load();
300 return $this->skinNames;
301 }
302
303 function getMathNames() {
304 $this->load();
305 return $this->mathNames;
306 }
307
308 function getDatePreferences() {
309 $this->load();
310 return $this->datePreferences;
311 }
312
313 function getDateFormats() {
314 $this->load();
315 return $this->dateFormats;
316 }
317
318 function getDefaultDateFormat() {
319 $this->load();
320 return $this->defaultDateFormat;
321 }
322
323 function getDatePreferenceMigrationMap() {
324 $this->load();
325 return $this->datePreferenceMigrationMap;
326 }
327
328 function getDefaultUserOptionOverrides() {
329 $this->load();
330 # XXX - apparently some languageas get empty arrays, didn't get to it yet -- midom
331 if (is_array($this->defaultUserOptionOverrides)) {
332 return $this->defaultUserOptionOverrides;
333 } else {
334 return array();
335 }
336 }
337
338 function getExtraUserToggles() {
339 $this->load();
340 return $this->extraUserToggles;
341 }
342
343 function getUserToggle( $tog ) {
344 return $this->getMessageFromDB( "tog-$tog" );
345 }
346
347 /**
348 * Get language names, indexed by code.
349 * If $customisedOnly is true, only returns codes with a messages file
350 */
351 public static function getLanguageNames( $customisedOnly = false ) {
352 global $wgLanguageNames;
353 if ( !$customisedOnly ) {
354 return $wgLanguageNames;
355 }
356
357 global $IP;
358 $names = array();
359 $dir = opendir( "$IP/languages/messages" );
360 while( false !== ( $file = readdir( $dir ) ) ) {
361 $m = array();
362 if( preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $file, $m ) ) {
363 $code = str_replace( '_', '-', strtolower( $m[1] ) );
364 if ( isset( $wgLanguageNames[$code] ) ) {
365 $names[$code] = $wgLanguageNames[$code];
366 }
367 }
368 }
369 closedir( $dir );
370 return $names;
371 }
372
373 /**
374 * Ugly hack to get a message maybe from the MediaWiki namespace, if this
375 * language object is the content or user language.
376 */
377 function getMessageFromDB( $msg ) {
378 global $wgContLang, $wgLang;
379 if ( $wgContLang->getCode() == $this->getCode() ) {
380 # Content language
381 return wfMsgForContent( $msg );
382 } elseif ( $wgLang->getCode() == $this->getCode() ) {
383 # User language
384 return wfMsg( $msg );
385 } else {
386 # Neither, get from localisation
387 return $this->getMessage( $msg );
388 }
389 }
390
391 function getLanguageName( $code ) {
392 global $wgLanguageNames;
393 if ( ! array_key_exists( $code, $wgLanguageNames ) ) {
394 return '';
395 }
396 return $wgLanguageNames[$code];
397 }
398
399 function getMonthName( $key ) {
400 return $this->getMessageFromDB( self::$mMonthMsgs[$key-1] );
401 }
402
403 function getMonthNameGen( $key ) {
404 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key-1] );
405 }
406
407 function getMonthAbbreviation( $key ) {
408 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key-1] );
409 }
410
411 function getWeekdayName( $key ) {
412 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key-1] );
413 }
414
415 function getWeekdayAbbreviation( $key ) {
416 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key-1] );
417 }
418
419 function getIranianCalendarMonthName( $key ) {
420 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key-1] );
421 }
422
423 function getHebrewCalendarMonthName( $key ) {
424 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key-1] );
425 }
426
427 function getHebrewCalendarMonthNameGen( $key ) {
428 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key-1] );
429 }
430
431
432 /**
433 * Used by date() and time() to adjust the time output.
434 * @public
435 * @param int $ts the time in date('YmdHis') format
436 * @param mixed $tz adjust the time by this amount (default false,
437 * mean we get user timecorrection setting)
438 * @return int
439 */
440 function userAdjust( $ts, $tz = false ) {
441 global $wgUser, $wgLocalTZoffset;
442
443 if (!$tz) {
444 $tz = $wgUser->getOption( 'timecorrection' );
445 }
446
447 # minutes and hours differences:
448 $minDiff = 0;
449 $hrDiff = 0;
450
451 if ( $tz === '' ) {
452 # Global offset in minutes.
453 if( isset($wgLocalTZoffset) ) {
454 if( $wgLocalTZoffset >= 0 ) {
455 $hrDiff = floor($wgLocalTZoffset / 60);
456 } else {
457 $hrDiff = ceil($wgLocalTZoffset / 60);
458 }
459 $minDiff = $wgLocalTZoffset % 60;
460 }
461 } elseif ( strpos( $tz, ':' ) !== false ) {
462 $tzArray = explode( ':', $tz );
463 $hrDiff = intval($tzArray[0]);
464 $minDiff = intval($hrDiff < 0 ? -$tzArray[1] : $tzArray[1]);
465 } else {
466 $hrDiff = intval( $tz );
467 }
468
469 # No difference ? Return time unchanged
470 if ( 0 == $hrDiff && 0 == $minDiff ) { return $ts; }
471
472 wfSuppressWarnings(); // E_STRICT system time bitching
473 # Generate an adjusted date
474 $t = mktime( (
475 (int)substr( $ts, 8, 2) ) + $hrDiff, # Hours
476 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
477 (int)substr( $ts, 12, 2 ), # Seconds
478 (int)substr( $ts, 4, 2 ), # Month
479 (int)substr( $ts, 6, 2 ), # Day
480 (int)substr( $ts, 0, 4 ) ); #Year
481
482 $date = date( 'YmdHis', $t );
483 wfRestoreWarnings();
484
485 return $date;
486 }
487
488 /**
489 * This is a workalike of PHP's date() function, but with better
490 * internationalisation, a reduced set of format characters, and a better
491 * escaping format.
492 *
493 * Supported format characters are dDjlNwzWFmMntLYyaAgGhHiscrU. See the
494 * PHP manual for definitions. There are a number of extensions, which
495 * start with "x":
496 *
497 * xn Do not translate digits of the next numeric format character
498 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
499 * xr Use roman numerals for the next numeric format character
500 * xh Use hebrew numerals for the next numeric format character
501 * xx Literal x
502 * xg Genitive month name
503 *
504 * xij j (day number) in Iranian calendar
505 * xiF F (month name) in Iranian calendar
506 * xin n (month number) in Iranian calendar
507 * xiY Y (full year) in Iranian calendar
508 *
509 * xjj j (day number) in Hebrew calendar
510 * xjF F (month name) in Hebrew calendar
511 * xjx xg (genitive month name) in Hebrew calendar
512 * xjn n (month number) in Hebrew calendar
513 * xjY Y (full year) in Hebrew calendar
514 *
515 * Characters enclosed in double quotes will be considered literal (with
516 * the quotes themselves removed). Unmatched quotes will be considered
517 * literal quotes. Example:
518 *
519 * "The month is" F => The month is January
520 * i's" => 20'11"
521 *
522 * Backslash escaping is also supported.
523 *
524 * Input timestamp is assumed to be pre-normalized to the desired local
525 * time zone, if any.
526 *
527 * @param string $format
528 * @param string $ts 14-character timestamp
529 * YYYYMMDDHHMMSS
530 * 01234567890123
531 */
532 function sprintfDate( $format, $ts ) {
533 $s = '';
534 $raw = false;
535 $roman = false;
536 $hebrewNum = false;
537 $unix = false;
538 $rawToggle = false;
539 $iranian = false;
540 $hebrew = false;
541 for ( $p = 0; $p < strlen( $format ); $p++ ) {
542 $num = false;
543 $code = $format[$p];
544 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
545 $code .= $format[++$p];
546 }
547
548 if ( ( $code === 'xi' || $code == 'xj' ) && $p < strlen( $format ) - 1 ) {
549 $code .= $format[++$p];
550 }
551
552 switch ( $code ) {
553 case 'xx':
554 $s .= 'x';
555 break;
556 case 'xn':
557 $raw = true;
558 break;
559 case 'xN':
560 $rawToggle = !$rawToggle;
561 break;
562 case 'xr':
563 $roman = true;
564 break;
565 case 'xh':
566 $hebrewNum = true;
567 break;
568 case 'xg':
569 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
570 break;
571 case 'xjx':
572 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
573 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
574 break;
575 case 'd':
576 $num = substr( $ts, 6, 2 );
577 break;
578 case 'D':
579 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
580 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
581 break;
582 case 'j':
583 $num = intval( substr( $ts, 6, 2 ) );
584 break;
585 case 'xij':
586 if ( !$iranian ) $iranian = self::tsToIranian( $ts );
587 $num = $iranian[2];
588 break;
589 case 'xjj':
590 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
591 $num = $hebrew[2];
592 break;
593 case 'l':
594 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
595 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
596 break;
597 case 'N':
598 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
599 $w = gmdate( 'w', $unix );
600 $num = $w ? $w : 7;
601 break;
602 case 'w':
603 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
604 $num = gmdate( 'w', $unix );
605 break;
606 case 'z':
607 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
608 $num = gmdate( 'z', $unix );
609 break;
610 case 'W':
611 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
612 $num = gmdate( 'W', $unix );
613 break;
614 case 'F':
615 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
616 break;
617 case 'xiF':
618 if ( !$iranian ) $iranian = self::tsToIranian( $ts );
619 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
620 break;
621 case 'xjF':
622 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
623 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
624 break;
625 case 'm':
626 $num = substr( $ts, 4, 2 );
627 break;
628 case 'M':
629 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
630 break;
631 case 'n':
632 $num = intval( substr( $ts, 4, 2 ) );
633 break;
634 case 'xin':
635 if ( !$iranian ) $iranian = self::tsToIranian( $ts );
636 $num = $iranian[1];
637 break;
638 case 'xjn':
639 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
640 $num = $hebrew[1];
641 break;
642 case 't':
643 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
644 $num = gmdate( 't', $unix );
645 break;
646 case 'L':
647 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
648 $num = gmdate( 'L', $unix );
649 break;
650 case 'Y':
651 $num = substr( $ts, 0, 4 );
652 break;
653 case 'xiY':
654 if ( !$iranian ) $iranian = self::tsToIranian( $ts );
655 $num = $iranian[0];
656 break;
657 case 'xjY':
658 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
659 $num = $hebrew[0];
660 break;
661 case 'y':
662 $num = substr( $ts, 2, 2 );
663 break;
664 case 'a':
665 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
666 break;
667 case 'A':
668 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
669 break;
670 case 'g':
671 $h = substr( $ts, 8, 2 );
672 $num = $h % 12 ? $h % 12 : 12;
673 break;
674 case 'G':
675 $num = intval( substr( $ts, 8, 2 ) );
676 break;
677 case 'h':
678 $h = substr( $ts, 8, 2 );
679 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
680 break;
681 case 'H':
682 $num = substr( $ts, 8, 2 );
683 break;
684 case 'i':
685 $num = substr( $ts, 10, 2 );
686 break;
687 case 's':
688 $num = substr( $ts, 12, 2 );
689 break;
690 case 'c':
691 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
692 $s .= gmdate( 'c', $unix );
693 break;
694 case 'r':
695 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
696 $s .= gmdate( 'r', $unix );
697 break;
698 case 'U':
699 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
700 $num = $unix;
701 break;
702 case '\\':
703 # Backslash escaping
704 if ( $p < strlen( $format ) - 1 ) {
705 $s .= $format[++$p];
706 } else {
707 $s .= '\\';
708 }
709 break;
710 case '"':
711 # Quoted literal
712 if ( $p < strlen( $format ) - 1 ) {
713 $endQuote = strpos( $format, '"', $p + 1 );
714 if ( $endQuote === false ) {
715 # No terminating quote, assume literal "
716 $s .= '"';
717 } else {
718 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
719 $p = $endQuote;
720 }
721 } else {
722 # Quote at end of string, assume literal "
723 $s .= '"';
724 }
725 break;
726 default:
727 $s .= $format[$p];
728 }
729 if ( $num !== false ) {
730 if ( $rawToggle || $raw ) {
731 $s .= $num;
732 $raw = false;
733 } elseif ( $roman ) {
734 $s .= self::romanNumeral( $num );
735 $roman = false;
736 } elseif( $hebrewNum ) {
737 $s .= self::hebrewNumeral( $num );
738 $hebrewNum = false;
739 } else {
740 $s .= $this->formatNum( $num, true );
741 }
742 $num = false;
743 }
744 }
745 return $s;
746 }
747
748 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
749 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
750 /**
751 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
752 * Gregorian dates to Iranian dates. Originally written in C, it
753 * is released under the terms of GNU Lesser General Public
754 * License. Conversion to PHP was performed by Niklas Laxström.
755 *
756 * Link: http://www.farsiweb.info/jalali/jalali.c
757 */
758 private static function tsToIranian( $ts ) {
759 $gy = substr( $ts, 0, 4 ) -1600;
760 $gm = substr( $ts, 4, 2 ) -1;
761 $gd = substr( $ts, 6, 2 ) -1;
762
763 # Days passed from the beginning (including leap years)
764 $gDayNo = 365*$gy
765 + floor(($gy+3) / 4)
766 - floor(($gy+99) / 100)
767 + floor(($gy+399) / 400);
768
769
770 // Add days of the past months of this year
771 for( $i = 0; $i < $gm; $i++ ) {
772 $gDayNo += self::$GREG_DAYS[$i];
773 }
774
775 // Leap years
776 if ( $gm > 1 && (($gy%4===0 && $gy%100!==0 || ($gy%400==0)))) {
777 $gDayNo++;
778 }
779
780 // Days passed in current month
781 $gDayNo += $gd;
782
783 $jDayNo = $gDayNo - 79;
784
785 $jNp = floor($jDayNo / 12053);
786 $jDayNo %= 12053;
787
788 $jy = 979 + 33*$jNp + 4*floor($jDayNo/1461);
789 $jDayNo %= 1461;
790
791 if ( $jDayNo >= 366 ) {
792 $jy += floor(($jDayNo-1)/365);
793 $jDayNo = floor(($jDayNo-1)%365);
794 }
795
796 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
797 $jDayNo -= self::$IRANIAN_DAYS[$i];
798 }
799
800 $jm= $i+1;
801 $jd= $jDayNo+1;
802
803 return array($jy, $jm, $jd);
804 }
805
806 /**
807 * Converting Gregorian dates to Hebrew dates.
808 *
809 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
810 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
811 * to translate the relevant functions into PHP and release them under
812 * GNU GPL.
813 */
814 private static function tsToHebrew( $ts ) {
815 # Parse date
816 $year = substr( $ts, 0, 4 );
817 $month = substr( $ts, 4, 2 );
818 $day = substr( $ts, 6, 2 );
819
820 # Month number when March = 1, February = 12
821 $month -= 2;
822 if( $month <= 0 ) {
823 # January of February
824 $month += 12;
825 $year--;
826 }
827
828 # Days since 1 March - calculating 30 days a month,
829 # and then adding the missing number of days
830 $day += intval( 7 * $month / 12 + 30 * ( $month - 1 ) );
831 # Calculate Hebrew year for days after 1 Nisan
832 $hebrewYear = $year + 3760;
833 # Passover date for this year (as days since 1 March)
834 $passover = self::passoverDate( $hebrewYear );
835 if( $day <= $passover - 15 ) {
836 # Day is before 1 Nisan (passover is 15 Nisan) - it is the previous year
837 # Next year's passover (as days since 1 March)
838 $anchor = $passover;
839 # Add days since previous year's 1 March
840 $day += 365;
841 if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
842 # Leap year
843 $day++;
844 }
845 # Previous year
846 $year--;
847 $hebrewYear--;
848 # Passover date for the new year (as days since 1 March)
849 $passover = self::passoverDate( $hebrewYear );
850 } else {
851 # Next year's passover (as days since 1 March)
852 $anchor = self::passoverDate( $hebrewYear + 1 );
853 }
854
855 # Days since 1 Nisan
856 $day -= $passover - 15;
857 # Difference between this year's passover date by gregorian calendar,
858 # and the next year's one + 12 days. This should be 1 days for a regular year,
859 # but 0 for incomplete one, 2 for complete, and those + 30 days of Adar I
860 # for a leap year.
861 $anchor -= $passover - 12;
862 $nextYear = $year + 1;
863 if( ( $nextYear % 400 == 0 ) || ( $nextYear % 100 != 0 && $nextYear % 4 == 0 ) ) {
864 # Next year is a leap year - difference is growing
865 $anchor++;
866 }
867
868 # Calculate day in the month from number of days sine 1 Nisan
869 # Don't check Adar - if the day is not in adar, we will stop before;
870 # if it is in adar, we will use it to check if it is Adar I or Adar II
871 for( $month = 0; $month < 11; $month++ ) {
872 # Calculate days in this month
873 if( $month == 7 && $anchor % 30 == 2 ) {
874 # Cheshvan in a complete year (otherwise as the rule below)
875 $days = 30;
876 } else if( $month == 8 && $anchor % 30 == 0 ) {
877 # Kislev in an incomplete year (otherwise as the rule below)
878 $days = 29;
879 } else {
880 # Even months have 30 days, odd have 29
881 $days = 30 - $month % 2;
882 }
883 if( $day <= $days ) {
884 # In this month
885 break;
886 }
887 # Try in next months
888 $day -= $days;
889 }
890
891 # Now we move to a year from Tishrei
892 if( $month >= 6 ) {
893 # After Tishrei, use next year
894 $hebrewYear++;
895 }
896 # Recalculate month number so that we start from Tishrei
897 $month = ( $month + 6 ) % 12 + 1;
898
899 # Fix Adar
900 if( $month == 6 && $anchor >= 30 ) {
901 # This *is* adar, and this year is leap
902 if( $day > 30 ) {
903 # Adar II
904 $month = 14;
905 $day -= 30;
906 } else {
907 # Adar I
908 $month = 13;
909 }
910 }
911
912 return array( $hebrewYear, $month, $day );
913 }
914
915 /**
916 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
917 * Used for Hebrew date.
918 */
919 private static function passoverDate( $year ) {
920 $a = intval( ( 12 * $year + 17 ) % 19 );
921 $b = intval( $year % 4 );
922 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * $year;
923 if( $m < 0 ) {
924 $m--;
925 }
926 $Mar = intval( $m );
927 if( $m < 0 ) {
928 $m++;
929 }
930 $m -= $Mar;
931
932 $c = intval( ( $Mar + 3 * $year + 5 * $b + 5 ) % 7);
933 if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
934 $Mar++;
935 } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
936 $Mar += 2;
937 } else if( $c == 2 || $c == 4 || $c == 6 ) {
938 $Mar++;
939 }
940
941 $Mar += intval( ( $year - 3760 ) / 100 ) - intval( ( $year - 3760 ) / 400 ) - 2;
942 return $Mar;
943 }
944
945 /**
946 * Roman number formatting up to 3000
947 */
948 static function romanNumeral( $num ) {
949 static $table = array(
950 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
951 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
952 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
953 array( '', 'M', 'MM', 'MMM' )
954 );
955
956 $num = intval( $num );
957 if ( $num > 3000 || $num <= 0 ) {
958 return $num;
959 }
960
961 $s = '';
962 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
963 if ( $num >= $pow10 ) {
964 $s .= $table[$i][floor($num / $pow10)];
965 }
966 $num = $num % $pow10;
967 }
968 return $s;
969 }
970
971 /**
972 * Hebrew Gematria number formatting up to 9999
973 */
974 static function hebrewNumeral( $num ) {
975 static $table = array(
976 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
977 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
978 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
979 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
980 );
981
982 $num = intval( $num );
983 if ( $num > 9999 || $num <= 0 ) {
984 return $num;
985 }
986
987 $s = '';
988 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
989 if ( $num >= $pow10 ) {
990 if ( $num == 15 || $num == 16 ) {
991 $s .= $table[0][9] . $table[0][$num - 9];
992 $num = 0;
993 } else {
994 $s .= $table[$i][intval( ( $num / $pow10 ) )];
995 if( $pow10 == 1000 ) {
996 $s .= "'";
997 }
998 }
999 }
1000 $num = $num % $pow10;
1001 }
1002 if( strlen( $s ) == 2 ) {
1003 $str = $s . "'";
1004 } else {
1005 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1006 $str .= substr( $s, strlen( $s ) - 2, 2 );
1007 }
1008 $start = substr( $str, 0, strlen( $str ) - 2 );
1009 $end = substr( $str, strlen( $str ) - 2 );
1010 switch( $end ) {
1011 case 'כ':
1012 $str = $start . 'ך';
1013 break;
1014 case 'מ':
1015 $str = $start . 'ם';
1016 break;
1017 case 'נ':
1018 $str = $start . 'ן';
1019 break;
1020 case 'פ':
1021 $str = $start . 'ף';
1022 break;
1023 case 'צ':
1024 $str = $start . 'ץ';
1025 break;
1026 }
1027 return $str;
1028 }
1029
1030 /**
1031 * This is meant to be used by time(), date(), and timeanddate() to get
1032 * the date preference they're supposed to use, it should be used in
1033 * all children.
1034 *
1035 *<code>
1036 * function timeanddate([...], $format = true) {
1037 * $datePreference = $this->dateFormat($format);
1038 * [...]
1039 * }
1040 *</code>
1041 *
1042 * @param mixed $usePrefs: if true, the user's preference is used
1043 * if false, the site/language default is used
1044 * if int/string, assumed to be a format.
1045 * @return string
1046 */
1047 function dateFormat( $usePrefs = true ) {
1048 global $wgUser;
1049
1050 if( is_bool( $usePrefs ) ) {
1051 if( $usePrefs ) {
1052 $datePreference = $wgUser->getDatePreference();
1053 } else {
1054 $options = User::getDefaultOptions();
1055 $datePreference = (string)$options['date'];
1056 }
1057 } else {
1058 $datePreference = (string)$usePrefs;
1059 }
1060
1061 // return int
1062 if( $datePreference == '' ) {
1063 return 'default';
1064 }
1065
1066 return $datePreference;
1067 }
1068
1069 /**
1070 * @public
1071 * @param mixed $ts the time format which needs to be turned into a
1072 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1073 * @param bool $adj whether to adjust the time output according to the
1074 * user configured offset ($timecorrection)
1075 * @param mixed $format true to use user's date format preference
1076 * @param string $timecorrection the time offset as returned by
1077 * validateTimeZone() in Special:Preferences
1078 * @return string
1079 */
1080 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1081 $this->load();
1082 if ( $adj ) {
1083 $ts = $this->userAdjust( $ts, $timecorrection );
1084 }
1085
1086 $pref = $this->dateFormat( $format );
1087 if( $pref == 'default' || !isset( $this->dateFormats["$pref date"] ) ) {
1088 $pref = $this->defaultDateFormat;
1089 }
1090 return $this->sprintfDate( $this->dateFormats["$pref date"], $ts );
1091 }
1092
1093 /**
1094 * @public
1095 * @param mixed $ts the time format which needs to be turned into a
1096 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1097 * @param bool $adj whether to adjust the time output according to the
1098 * user configured offset ($timecorrection)
1099 * @param mixed $format true to use user's date format preference
1100 * @param string $timecorrection the time offset as returned by
1101 * validateTimeZone() in Special:Preferences
1102 * @return string
1103 */
1104 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1105 $this->load();
1106 if ( $adj ) {
1107 $ts = $this->userAdjust( $ts, $timecorrection );
1108 }
1109
1110 $pref = $this->dateFormat( $format );
1111 if( $pref == 'default' || !isset( $this->dateFormats["$pref time"] ) ) {
1112 $pref = $this->defaultDateFormat;
1113 }
1114 return $this->sprintfDate( $this->dateFormats["$pref time"], $ts );
1115 }
1116
1117 /**
1118 * @public
1119 * @param mixed $ts the time format which needs to be turned into a
1120 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1121 * @param bool $adj whether to adjust the time output according to the
1122 * user configured offset ($timecorrection)
1123
1124 * @param mixed $format what format to return, if it's false output the
1125 * default one (default true)
1126 * @param string $timecorrection the time offset as returned by
1127 * validateTimeZone() in Special:Preferences
1128 * @return string
1129 */
1130 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
1131 $this->load();
1132
1133 $ts = wfTimestamp( TS_MW, $ts );
1134
1135 if ( $adj ) {
1136 $ts = $this->userAdjust( $ts, $timecorrection );
1137 }
1138
1139 $pref = $this->dateFormat( $format );
1140 if( $pref == 'default' || !isset( $this->dateFormats["$pref both"] ) ) {
1141 $pref = $this->defaultDateFormat;
1142 }
1143
1144 return $this->sprintfDate( $this->dateFormats["$pref both"], $ts );
1145 }
1146
1147 function getMessage( $key ) {
1148 $this->load();
1149 return isset( $this->messages[$key] ) ? $this->messages[$key] : null;
1150 }
1151
1152 function getAllMessages() {
1153 $this->load();
1154 return $this->messages;
1155 }
1156
1157 function iconv( $in, $out, $string ) {
1158 # For most languages, this is a wrapper for iconv
1159 return iconv( $in, $out . '//IGNORE', $string );
1160 }
1161
1162 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1163 function ucwordbreaksCallbackAscii($matches){
1164 return $this->ucfirst($matches[1]);
1165 }
1166
1167 function ucwordbreaksCallbackMB($matches){
1168 return mb_strtoupper($matches[0]);
1169 }
1170
1171 function ucCallback($matches){
1172 list( $wikiUpperChars ) = self::getCaseMaps();
1173 return strtr( $matches[1], $wikiUpperChars );
1174 }
1175
1176 function lcCallback($matches){
1177 list( , $wikiLowerChars ) = self::getCaseMaps();
1178 return strtr( $matches[1], $wikiLowerChars );
1179 }
1180
1181 function ucwordsCallbackMB($matches){
1182 return mb_strtoupper($matches[0]);
1183 }
1184
1185 function ucwordsCallbackWiki($matches){
1186 list( $wikiUpperChars ) = self::getCaseMaps();
1187 return strtr( $matches[0], $wikiUpperChars );
1188 }
1189
1190 function ucfirst( $str ) {
1191 if ( empty($str) ) return $str;
1192 if ( ord($str[0]) < 128 ) return ucfirst($str);
1193 else return self::uc($str,true); // fall back to more complex logic in case of multibyte strings
1194 }
1195
1196 function uc( $str, $first = false ) {
1197 if ( function_exists( 'mb_strtoupper' ) ) {
1198 if ( $first ) {
1199 if ( self::isMultibyte( $str ) ) {
1200 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1201 } else {
1202 return ucfirst( $str );
1203 }
1204 } else {
1205 return self::isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1206 }
1207 } else {
1208 if ( self::isMultibyte( $str ) ) {
1209 list( $wikiUpperChars ) = $this->getCaseMaps();
1210 $x = $first ? '^' : '';
1211 return preg_replace_callback(
1212 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1213 array($this,"ucCallback"),
1214 $str
1215 );
1216 } else {
1217 return $first ? ucfirst( $str ) : strtoupper( $str );
1218 }
1219 }
1220 }
1221
1222 function lcfirst( $str ) {
1223 if ( empty($str) ) return $str;
1224 if ( is_string( $str ) && ord($str[0]) < 128 ) {
1225 // editing string in place = cool
1226 $str[0]=strtolower($str[0]);
1227 return $str;
1228 }
1229 else return self::lc( $str, true );
1230 }
1231
1232 function lc( $str, $first = false ) {
1233 if ( function_exists( 'mb_strtolower' ) )
1234 if ( $first )
1235 if ( self::isMultibyte( $str ) )
1236 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1237 else
1238 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1239 else
1240 return self::isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1241 else
1242 if ( self::isMultibyte( $str ) ) {
1243 list( , $wikiLowerChars ) = self::getCaseMaps();
1244 $x = $first ? '^' : '';
1245 return preg_replace_callback(
1246 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1247 array($this,"lcCallback"),
1248 $str
1249 );
1250 } else
1251 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1252 }
1253
1254 function isMultibyte( $str ) {
1255 return (bool)preg_match( '/[\x80-\xff]/', $str );
1256 }
1257
1258 function ucwords($str) {
1259 if ( self::isMultibyte( $str ) ) {
1260 $str = self::lc($str);
1261
1262 // regexp to find first letter in each word (i.e. after each space)
1263 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1264
1265 // function to use to capitalize a single char
1266 if ( function_exists( 'mb_strtoupper' ) )
1267 return preg_replace_callback(
1268 $replaceRegexp,
1269 array($this,"ucwordsCallbackMB"),
1270 $str
1271 );
1272 else
1273 return preg_replace_callback(
1274 $replaceRegexp,
1275 array($this,"ucwordsCallbackWiki"),
1276 $str
1277 );
1278 }
1279 else
1280 return ucwords( strtolower( $str ) );
1281 }
1282
1283 # capitalize words at word breaks
1284 function ucwordbreaks($str){
1285 if (self::isMultibyte( $str ) ) {
1286 $str = self::lc($str);
1287
1288 // since \b doesn't work for UTF-8, we explicitely define word break chars
1289 $breaks= "[ \-\(\)\}\{\.,\?!]";
1290
1291 // find first letter after word break
1292 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1293
1294 if ( function_exists( 'mb_strtoupper' ) )
1295 return preg_replace_callback(
1296 $replaceRegexp,
1297 array($this,"ucwordbreaksCallbackMB"),
1298 $str
1299 );
1300 else
1301 return preg_replace_callback(
1302 $replaceRegexp,
1303 array($this,"ucwordsCallbackWiki"),
1304 $str
1305 );
1306 }
1307 else
1308 return preg_replace_callback(
1309 '/\b([\w\x80-\xff]+)\b/',
1310 array($this,"ucwordbreaksCallbackAscii"),
1311 $str );
1312 }
1313
1314 /**
1315 * Return a case-folded representation of $s
1316 *
1317 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1318 * and $s2 are the same except for the case of their characters. It is not
1319 * necessary for the value returned to make sense when displayed.
1320 *
1321 * Do *not* perform any other normalisation in this function. If a caller
1322 * uses this function when it should be using a more general normalisation
1323 * function, then fix the caller.
1324 */
1325 function caseFold( $s ) {
1326 return $this->uc( $s );
1327 }
1328
1329 function checkTitleEncoding( $s ) {
1330 if( is_array( $s ) ) {
1331 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1332 }
1333 # Check for non-UTF-8 URLs
1334 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1335 if(!$ishigh) return $s;
1336
1337 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1338 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1339 if( $isutf8 ) return $s;
1340
1341 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
1342 }
1343
1344 function fallback8bitEncoding() {
1345 $this->load();
1346 return $this->fallback8bitEncoding;
1347 }
1348
1349 /**
1350 * Some languages have special punctuation to strip out
1351 * or characters which need to be converted for MySQL's
1352 * indexing to grok it correctly. Make such changes here.
1353 *
1354 * @param string $in
1355 * @return string
1356 */
1357 function stripForSearch( $string ) {
1358 global $wgDBtype;
1359 if ( $wgDBtype != 'mysql' ) {
1360 return $string;
1361 }
1362
1363 # MySQL fulltext index doesn't grok utf-8, so we
1364 # need to fold cases and convert to hex
1365
1366 wfProfileIn( __METHOD__ );
1367 if( function_exists( 'mb_strtolower' ) ) {
1368 $out = preg_replace(
1369 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1370 "'U8' . bin2hex( \"$1\" )",
1371 mb_strtolower( $string ) );
1372 } else {
1373 list( , $wikiLowerChars ) = self::getCaseMaps();
1374 $out = preg_replace(
1375 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1376 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1377 $string );
1378 }
1379 wfProfileOut( __METHOD__ );
1380 return $out;
1381 }
1382
1383 function convertForSearchResult( $termsArray ) {
1384 # some languages, e.g. Chinese, need to do a conversion
1385 # in order for search results to be displayed correctly
1386 return $termsArray;
1387 }
1388
1389 /**
1390 * Get the first character of a string.
1391 *
1392 * @param string $s
1393 * @return string
1394 */
1395 function firstChar( $s ) {
1396 $matches = array();
1397 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1398 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
1399
1400 return isset( $matches[1] ) ? $matches[1] : "";
1401 }
1402
1403 function initEncoding() {
1404 # Some languages may have an alternate char encoding option
1405 # (Esperanto X-coding, Japanese furigana conversion, etc)
1406 # If this language is used as the primary content language,
1407 # an override to the defaults can be set here on startup.
1408 }
1409
1410 function recodeForEdit( $s ) {
1411 # For some languages we'll want to explicitly specify
1412 # which characters make it into the edit box raw
1413 # or are converted in some way or another.
1414 # Note that if wgOutputEncoding is different from
1415 # wgInputEncoding, this text will be further converted
1416 # to wgOutputEncoding.
1417 global $wgEditEncoding;
1418 if( $wgEditEncoding == '' or
1419 $wgEditEncoding == 'UTF-8' ) {
1420 return $s;
1421 } else {
1422 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1423 }
1424 }
1425
1426 function recodeInput( $s ) {
1427 # Take the previous into account.
1428 global $wgEditEncoding;
1429 if($wgEditEncoding != "") {
1430 $enc = $wgEditEncoding;
1431 } else {
1432 $enc = 'UTF-8';
1433 }
1434 if( $enc == 'UTF-8' ) {
1435 return $s;
1436 } else {
1437 return $this->iconv( $enc, 'UTF-8', $s );
1438 }
1439 }
1440
1441 /**
1442 * For right-to-left language support
1443 *
1444 * @return bool
1445 */
1446 function isRTL() {
1447 $this->load();
1448 return $this->rtl;
1449 }
1450
1451 /**
1452 * A hidden direction mark (LRM or RLM), depending on the language direction
1453 *
1454 * @return string
1455 */
1456 function getDirMark() {
1457 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
1458 }
1459
1460 /**
1461 * An arrow, depending on the language direction
1462 *
1463 * @return string
1464 */
1465 function getArrow() {
1466 return $this->isRTL() ? '←' : '→';
1467 }
1468
1469 /**
1470 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
1471 *
1472 * @return bool
1473 */
1474 function linkPrefixExtension() {
1475 $this->load();
1476 return $this->linkPrefixExtension;
1477 }
1478
1479 function &getMagicWords() {
1480 $this->load();
1481 return $this->magicWords;
1482 }
1483
1484 # Fill a MagicWord object with data from here
1485 function getMagic( &$mw ) {
1486 if ( !$this->mMagicHookDone ) {
1487 $this->mMagicHookDone = true;
1488 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
1489 }
1490 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
1491 $rawEntry = $this->mMagicExtensions[$mw->mId];
1492 } else {
1493 $magicWords =& $this->getMagicWords();
1494 if ( isset( $magicWords[$mw->mId] ) ) {
1495 $rawEntry = $magicWords[$mw->mId];
1496 } else {
1497 # Fall back to English if local list is incomplete
1498 $magicWords =& Language::getMagicWords();
1499 $rawEntry = $magicWords[$mw->mId];
1500 }
1501 }
1502
1503 if( !is_array( $rawEntry ) ) {
1504 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
1505 }
1506 $mw->mCaseSensitive = $rawEntry[0];
1507 $mw->mSynonyms = array_slice( $rawEntry, 1 );
1508 }
1509
1510 /**
1511 * Add magic words to the extension array
1512 */
1513 function addMagicWordsByLang( $newWords ) {
1514 $code = $this->getCode();
1515 $fallbackChain = array();
1516 while ( $code && !in_array( $code, $fallbackChain ) ) {
1517 $fallbackChain[] = $code;
1518 $code = self::getFallbackFor( $code );
1519 }
1520 if ( !in_array( 'en', $fallbackChain ) ) {
1521 $fallbackChain[] = 'en';
1522 }
1523 $fallbackChain = array_reverse( $fallbackChain );
1524 foreach ( $fallbackChain as $code ) {
1525 if ( isset( $newWords[$code] ) ) {
1526 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
1527 }
1528 }
1529 }
1530
1531 /**
1532 * Get special page names, as an associative array
1533 * case folded alias => real name
1534 */
1535 function getSpecialPageAliases() {
1536 $this->load();
1537 if ( !isset( $this->mExtendedSpecialPageAliases ) ) {
1538 $this->mExtendedSpecialPageAliases = $this->specialPageAliases;
1539 wfRunHooks( 'LanguageGetSpecialPageAliases',
1540 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
1541 }
1542 return $this->mExtendedSpecialPageAliases;
1543 }
1544
1545 /**
1546 * Italic is unsuitable for some languages
1547 *
1548 * @public
1549 *
1550 * @param string $text The text to be emphasized.
1551 * @return string
1552 */
1553 function emphasize( $text ) {
1554 return "<em>$text</em>";
1555 }
1556
1557 /**
1558 * Normally we output all numbers in plain en_US style, that is
1559 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
1560 * point twohundredthirtyfive. However this is not sutable for all
1561 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
1562 * Icelandic just want to use commas instead of dots, and dots instead
1563 * of commas like "293.291,235".
1564 *
1565 * An example of this function being called:
1566 * <code>
1567 * wfMsg( 'message', $wgLang->formatNum( $num ) )
1568 * </code>
1569 *
1570 * See LanguageGu.php for the Gujarati implementation and
1571 * LanguageIs.php for the , => . and . => , implementation.
1572 *
1573 * @todo check if it's viable to use localeconv() for the decimal
1574 * seperator thing.
1575 * @public
1576 * @param mixed $number the string to be formatted, should be an integer or
1577 * a floating point number.
1578 * @param bool $nocommafy Set to true for special numbers like dates
1579 * @return string
1580 */
1581 function formatNum( $number, $nocommafy = false ) {
1582 global $wgTranslateNumerals;
1583 if (!$nocommafy) {
1584 $number = $this->commafy($number);
1585 $s = $this->separatorTransformTable();
1586 if (!is_null($s)) { $number = strtr($number, $s); }
1587 }
1588
1589 if ($wgTranslateNumerals) {
1590 $s = $this->digitTransformTable();
1591 if (!is_null($s)) { $number = strtr($number, $s); }
1592 }
1593
1594 return $number;
1595 }
1596
1597 function parseFormattedNumber( $number ) {
1598 $s = $this->digitTransformTable();
1599 if (!is_null($s)) { $number = strtr($number, array_flip($s)); }
1600
1601 $s = $this->separatorTransformTable();
1602 if (!is_null($s)) { $number = strtr($number, array_flip($s)); }
1603
1604 $number = strtr( $number, array (',' => '') );
1605 return $number;
1606 }
1607
1608 /**
1609 * Adds commas to a given number
1610 *
1611 * @param mixed $_
1612 * @return string
1613 */
1614 function commafy($_) {
1615 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
1616 }
1617
1618 function digitTransformTable() {
1619 $this->load();
1620 return $this->digitTransformTable;
1621 }
1622
1623 function separatorTransformTable() {
1624 $this->load();
1625 return $this->separatorTransformTable;
1626 }
1627
1628
1629 /**
1630 * For the credit list in includes/Credits.php (action=credits)
1631 *
1632 * @param array $l
1633 * @return string
1634 */
1635 function listToText( $l ) {
1636 $s = '';
1637 $m = count($l) - 1;
1638 for ($i = $m; $i >= 0; $i--) {
1639 if ($i == $m) {
1640 $s = $l[$i];
1641 } else if ($i == $m - 1) {
1642 $s = $l[$i] . ' ' . $this->getMessageFromDB( 'and' ) . ' ' . $s;
1643 } else {
1644 $s = $l[$i] . ', ' . $s;
1645 }
1646 }
1647 return $s;
1648 }
1649
1650 /**
1651 * Truncate a string to a specified length in bytes, appending an optional
1652 * string (e.g. for ellipses)
1653 *
1654 * The database offers limited byte lengths for some columns in the database;
1655 * multi-byte character sets mean we need to ensure that only whole characters
1656 * are included, otherwise broken characters can be passed to the user
1657 *
1658 * If $length is negative, the string will be truncated from the beginning
1659 *
1660 * @param string $string String to truncate
1661 * @param int $length Maximum length (excluding ellipses)
1662 * @param string $ellipses String to append to the truncated text
1663 * @return string
1664 */
1665 function truncate( $string, $length, $ellipsis = "" ) {
1666 if( $length == 0 ) {
1667 return $ellipsis;
1668 }
1669 if ( strlen( $string ) <= abs( $length ) ) {
1670 return $string;
1671 }
1672 if( $length > 0 ) {
1673 $string = substr( $string, 0, $length );
1674 $char = ord( $string[strlen( $string ) - 1] );
1675 $m = array();
1676 if ($char >= 0xc0) {
1677 # We got the first byte only of a multibyte char; remove it.
1678 $string = substr( $string, 0, -1 );
1679 } elseif( $char >= 0x80 &&
1680 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
1681 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
1682 # We chopped in the middle of a character; remove it
1683 $string = $m[1];
1684 }
1685 return $string . $ellipsis;
1686 } else {
1687 $string = substr( $string, $length );
1688 $char = ord( $string[0] );
1689 if( $char >= 0x80 && $char < 0xc0 ) {
1690 # We chopped in the middle of a character; remove the whole thing
1691 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
1692 }
1693 return $ellipsis . $string;
1694 }
1695 }
1696
1697 /**
1698 * Grammatical transformations, needed for inflected languages
1699 * Invoked by putting {{grammar:case|word}} in a message
1700 *
1701 * @param string $word
1702 * @param string $case
1703 * @return string
1704 */
1705 function convertGrammar( $word, $case ) {
1706 global $wgGrammarForms;
1707 if ( isset($wgGrammarForms['en'][$case][$word]) ) {
1708 return $wgGrammarForms['en'][$case][$word];
1709 }
1710 return $word;
1711 }
1712
1713 /**
1714 * Plural form transformations, needed for some languages.
1715 * For example, there are 3 form of plural in Russian and Polish,
1716 * depending on "count mod 10". See [[w:Plural]]
1717 * For English it is pretty simple.
1718 *
1719 * Invoked by putting {{plural:count|wordform1|wordform2}}
1720 * or {{plural:count|wordform1|wordform2|wordform3}}
1721 *
1722 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
1723 *
1724 * @param integer $count Non-localized number
1725 * @param array $forms Different plural forms
1726 * @return string Correct form of plural for $count in this language
1727 */
1728 function convertPlural( $count, $forms ) {
1729 if ( !count($forms) ) { return ''; }
1730 $forms = $this->preConvertPlural( $forms, 2 );
1731
1732 return ( abs($count) == 1 ) ? $forms[0] : $forms[1];
1733 }
1734
1735 /**
1736 * Checks that convertPlural was given an array and pads it to requested
1737 * amound of forms by copying the last one.
1738 *
1739 * @param integer $count How many forms should there be at least
1740 * @param array $forms Array of forms given to convertPlural
1741 * @return array Padded array of forms or an exception if not an array
1742 */
1743 protected function preConvertPlural( Array $forms, $count ) {
1744 while ( count($forms) < $count ) {
1745 $forms[] = $forms[count($forms)-1];
1746 }
1747 return $forms;
1748 }
1749
1750 /**
1751 * For translaing of expiry times
1752 * @param string The validated block time in English
1753 * @return Somehow translated block time
1754 * @see LanguageFi.php for example implementation
1755 */
1756 function translateBlockExpiry( $str ) {
1757
1758 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
1759
1760 if ( $scBlockExpiryOptions == '-') {
1761 return $str;
1762 }
1763
1764 foreach (explode(',', $scBlockExpiryOptions) as $option) {
1765 if ( strpos($option, ":") === false )
1766 continue;
1767 list($show, $value) = explode(":", $option);
1768 if ( strcmp ( $str, $value) == 0 ) {
1769 return htmlspecialchars( trim( $show ) );
1770 }
1771 }
1772
1773 return $str;
1774 }
1775
1776 /**
1777 * languages like Chinese need to be segmented in order for the diff
1778 * to be of any use
1779 *
1780 * @param string $text
1781 * @return string
1782 */
1783 function segmentForDiff( $text ) {
1784 return $text;
1785 }
1786
1787 /**
1788 * and unsegment to show the result
1789 *
1790 * @param string $text
1791 * @return string
1792 */
1793 function unsegmentForDiff( $text ) {
1794 return $text;
1795 }
1796
1797 # convert text to different variants of a language.
1798 function convert( $text, $isTitle = false) {
1799 return $this->mConverter->convert($text, $isTitle);
1800 }
1801
1802 # Convert text from within Parser
1803 function parserConvert( $text, &$parser ) {
1804 return $this->mConverter->parserConvert( $text, $parser );
1805 }
1806
1807 # Check if this is a language with variants
1808 function hasVariants(){
1809 return sizeof($this->getVariants())>1;
1810 }
1811
1812 # Put custom tags (e.g. -{ }-) around math to prevent conversion
1813 function armourMath($text){
1814 return $this->mConverter->armourMath($text);
1815 }
1816
1817
1818 /**
1819 * Perform output conversion on a string, and encode for safe HTML output.
1820 * @param string $text
1821 * @param bool $isTitle -- wtf?
1822 * @return string
1823 * @todo this should get integrated somewhere sane
1824 */
1825 function convertHtml( $text, $isTitle = false ) {
1826 return htmlspecialchars( $this->convert( $text, $isTitle ) );
1827 }
1828
1829 function convertCategoryKey( $key ) {
1830 return $this->mConverter->convertCategoryKey( $key );
1831 }
1832
1833 /**
1834 * get the list of variants supported by this langauge
1835 * see sample implementation in LanguageZh.php
1836 *
1837 * @return array an array of language codes
1838 */
1839 function getVariants() {
1840 return $this->mConverter->getVariants();
1841 }
1842
1843
1844 function getPreferredVariant( $fromUser = true ) {
1845 return $this->mConverter->getPreferredVariant( $fromUser );
1846 }
1847
1848 /**
1849 * if a language supports multiple variants, it is
1850 * possible that non-existing link in one variant
1851 * actually exists in another variant. this function
1852 * tries to find it. See e.g. LanguageZh.php
1853 *
1854 * @param string $link the name of the link
1855 * @param mixed $nt the title object of the link
1856 * @return null the input parameters may be modified upon return
1857 */
1858 function findVariantLink( &$link, &$nt ) {
1859 $this->mConverter->findVariantLink($link, $nt);
1860 }
1861
1862 /**
1863 * If a language supports multiple variants, converts text
1864 * into an array of all possible variants of the text:
1865 * 'variant' => text in that variant
1866 */
1867
1868 function convertLinkToAllVariants($text){
1869 return $this->mConverter->convertLinkToAllVariants($text);
1870 }
1871
1872
1873 /**
1874 * returns language specific options used by User::getPageRenderHash()
1875 * for example, the preferred language variant
1876 *
1877 * @return string
1878 * @public
1879 */
1880 function getExtraHashOptions() {
1881 return $this->mConverter->getExtraHashOptions();
1882 }
1883
1884 /**
1885 * for languages that support multiple variants, the title of an
1886 * article may be displayed differently in different variants. this
1887 * function returns the apporiate title defined in the body of the article.
1888 *
1889 * @return string
1890 */
1891 function getParsedTitle() {
1892 return $this->mConverter->getParsedTitle();
1893 }
1894
1895 /**
1896 * Enclose a string with the "no conversion" tag. This is used by
1897 * various functions in the Parser
1898 *
1899 * @param string $text text to be tagged for no conversion
1900 * @return string the tagged text
1901 */
1902 function markNoConversion( $text, $noParse=false ) {
1903 return $this->mConverter->markNoConversion( $text, $noParse );
1904 }
1905
1906 /**
1907 * A regular expression to match legal word-trailing characters
1908 * which should be merged onto a link of the form [[foo]]bar.
1909 *
1910 * @return string
1911 * @public
1912 */
1913 function linkTrail() {
1914 $this->load();
1915 return $this->linkTrail;
1916 }
1917
1918 function getLangObj() {
1919 return $this;
1920 }
1921
1922 /**
1923 * Get the RFC 3066 code for this language object
1924 */
1925 function getCode() {
1926 return $this->mCode;
1927 }
1928
1929 function setCode( $code ) {
1930 $this->mCode = $code;
1931 }
1932
1933 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
1934 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
1935 }
1936
1937 static function getMessagesFileName( $code ) {
1938 global $IP;
1939 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
1940 }
1941
1942 static function getClassFileName( $code ) {
1943 global $IP;
1944 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
1945 }
1946
1947 static function getLocalisationArray( $code, $disableCache = false ) {
1948 self::loadLocalisation( $code, $disableCache );
1949 return self::$mLocalisationCache[$code];
1950 }
1951
1952 /**
1953 * Load localisation data for a given code into the static cache
1954 *
1955 * @return array Dependencies, map of filenames to mtimes
1956 */
1957 static function loadLocalisation( $code, $disableCache = false ) {
1958 static $recursionGuard = array();
1959 global $wgMemc;
1960
1961 if ( !$code ) {
1962 throw new MWException( "Invalid language code requested" );
1963 }
1964
1965 if ( !$disableCache ) {
1966 # Try the per-process cache
1967 if ( isset( self::$mLocalisationCache[$code] ) ) {
1968 return self::$mLocalisationCache[$code]['deps'];
1969 }
1970
1971 wfProfileIn( __METHOD__ );
1972
1973 # Try the serialized directory
1974 $cache = wfGetPrecompiledData( self::getFileName( "Messages", $code, '.ser' ) );
1975 if ( $cache ) {
1976 self::$mLocalisationCache[$code] = $cache;
1977 wfDebug( "Language::loadLocalisation(): got localisation for $code from precompiled data file\n" );
1978 wfProfileOut( __METHOD__ );
1979 return self::$mLocalisationCache[$code]['deps'];
1980 }
1981
1982 # Try the global cache
1983 $memcKey = wfMemcKey('localisation', $code );
1984 $cache = $wgMemc->get( $memcKey );
1985 if ( $cache ) {
1986 # Check file modification times
1987 foreach ( $cache['deps'] as $file => $mtime ) {
1988 if ( !file_exists( $file ) || filemtime( $file ) > $mtime ) {
1989 break;
1990 }
1991 }
1992 if ( self::isLocalisationOutOfDate( $cache ) ) {
1993 $wgMemc->delete( $memcKey );
1994 $cache = false;
1995 wfDebug( "Language::loadLocalisation(): localisation cache for $code had expired due to update of $file\n" );
1996 } else {
1997 self::$mLocalisationCache[$code] = $cache;
1998 wfDebug( "Language::loadLocalisation(): got localisation for $code from cache\n" );
1999 wfProfileOut( __METHOD__ );
2000 return $cache['deps'];
2001 }
2002 }
2003 } else {
2004 wfProfileIn( __METHOD__ );
2005 }
2006
2007 # Default fallback, may be overridden when the messages file is included
2008 if ( $code != 'en' ) {
2009 $fallback = 'en';
2010 } else {
2011 $fallback = false;
2012 }
2013
2014 # Load the primary localisation from the source file
2015 $filename = self::getMessagesFileName( $code );
2016 if ( !file_exists( $filename ) ) {
2017 wfDebug( "Language::loadLocalisation(): no localisation file for $code, using implicit fallback to en\n" );
2018 $cache = array();
2019 $deps = array();
2020 } else {
2021 $deps = array( $filename => filemtime( $filename ) );
2022 require( $filename );
2023 $cache = compact( self::$mLocalisationKeys );
2024 wfDebug( "Language::loadLocalisation(): got localisation for $code from source\n" );
2025 }
2026
2027 if ( !empty( $fallback ) ) {
2028 # Load the fallback localisation, with a circular reference guard
2029 if ( isset( $recursionGuard[$code] ) ) {
2030 throw new MWException( "Error: Circular fallback reference in language code $code" );
2031 }
2032 $recursionGuard[$code] = true;
2033 $newDeps = self::loadLocalisation( $fallback, $disableCache );
2034 unset( $recursionGuard[$code] );
2035
2036 $secondary = self::$mLocalisationCache[$fallback];
2037 $deps = array_merge( $deps, $newDeps );
2038
2039 # Merge the fallback localisation with the current localisation
2040 foreach ( self::$mLocalisationKeys as $key ) {
2041 if ( isset( $cache[$key] ) ) {
2042 if ( isset( $secondary[$key] ) ) {
2043 if ( in_array( $key, self::$mMergeableMapKeys ) ) {
2044 $cache[$key] = $cache[$key] + $secondary[$key];
2045 } elseif ( in_array( $key, self::$mMergeableListKeys ) ) {
2046 $cache[$key] = array_merge( $secondary[$key], $cache[$key] );
2047 } elseif ( in_array( $key, self::$mMergeableAliasListKeys ) ) {
2048 $cache[$key] = array_merge_recursive( $cache[$key], $secondary[$key] );
2049 }
2050 }
2051 } else {
2052 $cache[$key] = $secondary[$key];
2053 }
2054 }
2055
2056 # Merge bookstore lists if requested
2057 if ( !empty( $cache['bookstoreList']['inherit'] ) ) {
2058 $cache['bookstoreList'] = array_merge( $cache['bookstoreList'], $secondary['bookstoreList'] );
2059 }
2060 if ( isset( $cache['bookstoreList']['inherit'] ) ) {
2061 unset( $cache['bookstoreList']['inherit'] );
2062 }
2063 }
2064
2065 # Add dependencies to the cache entry
2066 $cache['deps'] = $deps;
2067
2068 # Replace spaces with underscores in namespace names
2069 $cache['namespaceNames'] = str_replace( ' ', '_', $cache['namespaceNames'] );
2070
2071 # Save to both caches
2072 self::$mLocalisationCache[$code] = $cache;
2073 if ( !$disableCache ) {
2074 $wgMemc->set( $memcKey, $cache );
2075 }
2076
2077 wfProfileOut( __METHOD__ );
2078 return $deps;
2079 }
2080
2081 /**
2082 * Test if a given localisation cache is out of date with respect to the
2083 * source Messages files. This is done automatically for the global cache
2084 * in $wgMemc, but is only done on certain occasions for the serialized
2085 * data file.
2086 *
2087 * @param $cache mixed Either a language code or a cache array
2088 */
2089 static function isLocalisationOutOfDate( $cache ) {
2090 if ( !is_array( $cache ) ) {
2091 self::loadLocalisation( $cache );
2092 $cache = self::$mLocalisationCache[$cache];
2093 }
2094 $expired = false;
2095 foreach ( $cache['deps'] as $file => $mtime ) {
2096 if ( !file_exists( $file ) || filemtime( $file ) > $mtime ) {
2097 $expired = true;
2098 break;
2099 }
2100 }
2101 return $expired;
2102 }
2103
2104 /**
2105 * Get the fallback for a given language
2106 */
2107 static function getFallbackFor( $code ) {
2108 self::loadLocalisation( $code );
2109 return self::$mLocalisationCache[$code]['fallback'];
2110 }
2111
2112 /**
2113 * Get all messages for a given language
2114 */
2115 static function getMessagesFor( $code ) {
2116 self::loadLocalisation( $code );
2117 return self::$mLocalisationCache[$code]['messages'];
2118 }
2119
2120 /**
2121 * Get a message for a given language
2122 */
2123 static function getMessageFor( $key, $code ) {
2124 self::loadLocalisation( $code );
2125 return isset( self::$mLocalisationCache[$code]['messages'][$key] ) ? self::$mLocalisationCache[$code]['messages'][$key] : null;
2126 }
2127
2128 /**
2129 * Load localisation data for this object
2130 */
2131 function load() {
2132 if ( !$this->mLoaded ) {
2133 self::loadLocalisation( $this->getCode() );
2134 $cache =& self::$mLocalisationCache[$this->getCode()];
2135 foreach ( self::$mLocalisationKeys as $key ) {
2136 $this->$key = $cache[$key];
2137 }
2138 $this->mLoaded = true;
2139
2140 $this->fixUpSettings();
2141 }
2142 }
2143
2144 /**
2145 * Do any necessary post-cache-load settings adjustment
2146 */
2147 function fixUpSettings() {
2148 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk,
2149 $wgNamespaceAliases, $wgAmericanDates;
2150 wfProfileIn( __METHOD__ );
2151 if ( $wgExtraNamespaces ) {
2152 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames;
2153 }
2154
2155 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
2156 if ( $wgMetaNamespaceTalk ) {
2157 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
2158 } else {
2159 $talk = $this->namespaceNames[NS_PROJECT_TALK];
2160 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2161
2162 # Allow grammar transformations
2163 # Allowing full message-style parsing would make simple requests
2164 # such as action=raw much more expensive than they need to be.
2165 # This will hopefully cover most cases.
2166 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2167 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2168 $talk = str_replace( ' ', '_', $talk );
2169 $this->namespaceNames[NS_PROJECT_TALK] = $talk;
2170 }
2171
2172 # The above mixing may leave namespaces out of canonical order.
2173 # Re-order by namespace ID number...
2174 ksort( $this->namespaceNames );
2175
2176 # Put namespace names and aliases into a hashtable.
2177 # If this is too slow, then we should arrange it so that it is done
2178 # before caching. The catch is that at pre-cache time, the above
2179 # class-specific fixup hasn't been done.
2180 $this->mNamespaceIds = array();
2181 foreach ( $this->namespaceNames as $index => $name ) {
2182 $this->mNamespaceIds[$this->lc($name)] = $index;
2183 }
2184 if ( $this->namespaceAliases ) {
2185 foreach ( $this->namespaceAliases as $name => $index ) {
2186 $this->mNamespaceIds[$this->lc($name)] = $index;
2187 }
2188 }
2189 if ( $wgNamespaceAliases ) {
2190 foreach ( $wgNamespaceAliases as $name => $index ) {
2191 $this->mNamespaceIds[$this->lc($name)] = $index;
2192 }
2193 }
2194
2195 if ( $this->defaultDateFormat == 'dmy or mdy' ) {
2196 $this->defaultDateFormat = $wgAmericanDates ? 'mdy' : 'dmy';
2197 }
2198 wfProfileOut( __METHOD__ );
2199 }
2200
2201 function replaceGrammarInNamespace( $m ) {
2202 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2203 }
2204
2205 static function getCaseMaps() {
2206 static $wikiUpperChars, $wikiLowerChars;
2207 if ( isset( $wikiUpperChars ) ) {
2208 return array( $wikiUpperChars, $wikiLowerChars );
2209 }
2210
2211 wfProfileIn( __METHOD__ );
2212 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2213 if ( $arr === false ) {
2214 throw new MWException(
2215 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2216 }
2217 extract( $arr );
2218 wfProfileOut( __METHOD__ );
2219 return array( $wikiUpperChars, $wikiLowerChars );
2220 }
2221
2222 function formatTimePeriod( $seconds ) {
2223 if ( $seconds < 10 ) {
2224 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . wfMsg( 'seconds-abbrev' );
2225 } elseif ( $seconds < 60 ) {
2226 return $this->formatNum( round( $seconds ) ) . wfMsg( 'seconds-abbrev' );
2227 } elseif ( $seconds < 3600 ) {
2228 return $this->formatNum( floor( $seconds / 60 ) ) . wfMsg( 'minutes-abbrev' ) .
2229 $this->formatNum( round( fmod( $seconds, 60 ) ) ) . wfMsg( 'seconds-abbrev' );
2230 } else {
2231 $hours = floor( $seconds / 3600 );
2232 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2233 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2234 return $this->formatNum( $hours ) . wfMsg( 'hours-abbrev' ) .
2235 $this->formatNum( $minutes ) . wfMsg( 'minutes-abbrev' ) .
2236 $this->formatNum( $secondsPart ) . wfMsg( 'seconds-abbrev' );
2237 }
2238 }
2239
2240 function formatBitrate( $bps ) {
2241 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2242 if ( $bps <= 0 ) {
2243 return $this->formatNum( $bps ) . $units[0];
2244 }
2245 $unitIndex = floor( log10( $bps ) / 3 );
2246 $mantissa = $bps / pow( 1000, $unitIndex );
2247 if ( $mantissa < 10 ) {
2248 $mantissa = round( $mantissa, 1 );
2249 } else {
2250 $mantissa = round( $mantissa );
2251 }
2252 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2253 }
2254
2255 /**
2256 * Format a size in bytes for output, using an appropriate
2257 * unit (B, KB, MB or GB) according to the magnitude in question
2258 *
2259 * @param $size Size to format
2260 * @return string Plain text (not HTML)
2261 */
2262 function formatSize( $size ) {
2263 // For small sizes no decimal places necessary
2264 $round = 0;
2265 if( $size > 1024 ) {
2266 $size = $size / 1024;
2267 if( $size > 1024 ) {
2268 $size = $size / 1024;
2269 // For MB and bigger two decimal places are smarter
2270 $round = 2;
2271 if( $size > 1024 ) {
2272 $size = $size / 1024;
2273 $msg = 'size-gigabytes';
2274 } else {
2275 $msg = 'size-megabytes';
2276 }
2277 } else {
2278 $msg = 'size-kilobytes';
2279 }
2280 } else {
2281 $msg = 'size-bytes';
2282 }
2283 $size = round( $size, $round );
2284 $text = $this->getMessageFromDB( $msg );
2285 return str_replace( '$1', $this->formatNum( $size ), $text );
2286 }
2287 }