6 if( !defined( 'MEDIAWIKI' ) ) {
7 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
12 global $wgLanguageNames;
13 require_once( dirname(__FILE__
) . '/Names.php' ) ;
15 global $wgInputEncoding, $wgOutputEncoding;
18 * These are always UTF-8, they exist only for backwards compatibility
20 $wgInputEncoding = "UTF-8";
21 $wgOutputEncoding = "UTF-8";
23 if( function_exists( 'mb_strtoupper' ) ) {
24 mb_internal_encoding('UTF-8');
27 /* a fake language converter */
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; }
44 #--------------------------------------------------------------------------
45 # Internationalisation code
46 #--------------------------------------------------------------------------
49 var $mConverter, $mVariants, $mCode, $mLoaded = false;
50 var $mMagicExtensions = array(), $mMagicHookDone = false;
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' );
60 static public $mMergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
61 'dateFormats', 'defaultUserOptionOverrides', 'magicWords' );
63 static public $mMergeableListKeys = array( 'extraUserToggles' );
65 static public $mMergeableAliasListKeys = array( 'specialPageAliases' );
67 static public $mLocalisationCache = array();
69 static public $mWeekdayMsgs = array(
70 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
74 static public $mWeekdayAbbrevMsgs = array(
75 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
78 static public $mMonthMsgs = array(
79 'january', 'february', 'march', 'april', 'may_long', 'june',
80 'july', 'august', 'september', 'october', 'november',
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',
88 static public $mMonthAbbrevMsgs = array(
89 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
90 'sep', 'oct', 'nov', 'dec'
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'
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'
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'
117 * Create a language object for a given language code
119 static function factory( $code ) {
121 static $recursionLevel = 0;
123 if ( $code == 'en' ) {
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");
131 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
132 include_once("$IP/languages/classes/$class.php");
136 if ( $recursionLevel > 5 ) {
137 throw new MWException( "Language fallback loop detected when creating class $class\n" );
140 if( ! class_exists( $class ) ) {
141 $fallback = Language
::getFallbackFor( $code );
143 $lang = Language
::factory( $fallback );
145 $lang->setCode( $code );
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' ) {
159 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
164 * Hook which will be called if this is the content language.
165 * Descendants can use this to register hook functions or modify globals
167 function initContLang() {}
173 function getDefaultUserOptions() {
174 return User
::getDefaultOptions();
177 function getFallbackLanguageCode() {
179 return $this->fallback
;
183 * Exports $wgBookstoreListEn
186 function getBookstoreList() {
188 return $this->bookstoreList
;
194 function getNamespaces() {
196 return $this->namespaceNames
;
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.
207 function getFormattedNamespaces() {
208 $ns = $this->getNamespaces();
209 foreach($ns as $k => $v) {
210 $ns[$k] = strtr($v, '_', ' ');
216 * Get a namespace value by key
218 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
219 * echo $mw_ns; // prints 'MediaWiki'
222 * @param int $index the array key of the namespace to return
223 * @return mixed, string if the namespace value exists, otherwise false
225 function getNsText( $index ) {
226 $ns = $this->getNamespaces();
227 return isset( $ns[$index] ) ?
$ns[$index] : false;
231 * A convenience function that returns the same thing as
232 * getNsText() except with '_' changed to ' ', useful for
237 function getFormattedNsText( $index ) {
238 $ns = $this->getNsText( $index );
239 return strtr($ns, '_', ' ');
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.
247 * @param string $text
248 * @return mixed An integer if $text is a valid value otherwise false
250 function getLocalNsIndex( $text ) {
252 $lctext = $this->lc($text);
253 return isset( $this->mNamespaceIds
[$lctext] ) ?
$this->mNamespaceIds
[$lctext] : false;
257 * Get a namespace key by value, case insensitive. Canonical namespace
258 * names override custom ones defined for the current language.
260 * @param string $text
261 * @return mixed An integer if $text is a valid value otherwise false
263 function getNsIndex( $text ) {
265 $lctext = $this->lc($text);
266 if( ( $ns = Namespace::getCanonicalIndex( $lctext ) ) !== null ) return $ns;
267 return isset( $this->mNamespaceIds
[$lctext] ) ?
$this->mNamespaceIds
[$lctext] : false;
271 * short names for language variants used for language conversion links.
273 * @param string $code
276 function getVariantname( $code ) {
277 return $this->getMessageFromDB( "variantname-$code" );
280 function specialPage( $name ) {
281 $aliases = $this->getSpecialPageAliases();
282 if ( isset( $aliases[$name][0] ) ) {
283 $name = $aliases[$name][0];
285 return $this->getNsText(NS_SPECIAL
) . ':' . $name;
288 function getQuickbarSettings() {
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' )
298 function getSkinNames() {
300 return $this->skinNames
;
303 function getMathNames() {
305 return $this->mathNames
;
308 function getDatePreferences() {
310 return $this->datePreferences
;
313 function getDateFormats() {
315 return $this->dateFormats
;
318 function getDefaultDateFormat() {
320 return $this->defaultDateFormat
;
323 function getDatePreferenceMigrationMap() {
325 return $this->datePreferenceMigrationMap
;
328 function getDefaultUserOptionOverrides() {
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
;
338 function getExtraUserToggles() {
340 return $this->extraUserToggles
;
343 function getUserToggle( $tog ) {
344 return $this->getMessageFromDB( "tog-$tog" );
348 * Get language names, indexed by code.
349 * If $customisedOnly is true, only returns codes with a messages file
351 public static function getLanguageNames( $customisedOnly = false ) {
352 global $wgLanguageNames;
353 if ( !$customisedOnly ) {
354 return $wgLanguageNames;
359 $dir = opendir( "$IP/languages/messages" );
360 while( false !== ( $file = readdir( $dir ) ) ) {
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];
374 * Ugly hack to get a message maybe from the MediaWiki namespace, if this
375 * language object is the content or user language.
377 function getMessageFromDB( $msg ) {
378 global $wgContLang, $wgLang;
379 if ( $wgContLang->getCode() == $this->getCode() ) {
381 return wfMsgForContent( $msg );
382 } elseif ( $wgLang->getCode() == $this->getCode() ) {
384 return wfMsg( $msg );
386 # Neither, get from localisation
387 return $this->getMessage( $msg );
391 function getLanguageName( $code ) {
392 global $wgLanguageNames;
393 if ( ! array_key_exists( $code, $wgLanguageNames ) ) {
396 return $wgLanguageNames[$code];
399 function getMonthName( $key ) {
400 return $this->getMessageFromDB( self
::$mMonthMsgs[$key-1] );
403 function getMonthNameGen( $key ) {
404 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key-1] );
407 function getMonthAbbreviation( $key ) {
408 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key-1] );
411 function getWeekdayName( $key ) {
412 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key-1] );
415 function getWeekdayAbbreviation( $key ) {
416 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key-1] );
419 function getIranianCalendarMonthName( $key ) {
420 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key-1] );
423 function getHebrewCalendarMonthName( $key ) {
424 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key-1] );
427 function getHebrewCalendarMonthNameGen( $key ) {
428 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key-1] );
433 * Used by date() and time() to adjust the time output.
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)
440 function userAdjust( $ts, $tz = false ) {
441 global $wgUser, $wgLocalTZoffset;
444 $tz = $wgUser->getOption( 'timecorrection' );
447 # minutes and hours differences:
452 # Global offset in minutes.
453 if( isset($wgLocalTZoffset) ) {
454 if( $wgLocalTZoffset >= 0 ) {
455 $hrDiff = floor($wgLocalTZoffset / 60);
457 $hrDiff = ceil($wgLocalTZoffset / 60);
459 $minDiff = $wgLocalTZoffset %
60;
461 } elseif ( strpos( $tz, ':' ) !== false ) {
462 $tzArray = explode( ':', $tz );
463 $hrDiff = intval($tzArray[0]);
464 $minDiff = intval($hrDiff < 0 ?
-$tzArray[1] : $tzArray[1]);
466 $hrDiff = intval( $tz );
469 # No difference ? Return time unchanged
470 if ( 0 == $hrDiff && 0 == $minDiff ) { return $ts; }
472 wfSuppressWarnings(); // E_STRICT system time bitching
473 # Generate an adjusted date
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
482 $date = date( 'YmdHis', $t );
489 * This is a workalike of PHP's date() function, but with better
490 * internationalisation, a reduced set of format characters, and a better
493 * Supported format characters are dDjlNwzWFmMntLYyaAgGhHiscrU. See the
494 * PHP manual for definitions. There are a number of extensions, which
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
502 * xg Genitive month name
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
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
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:
519 * "The month is" F => The month is January
522 * Backslash escaping is also supported.
524 * Input timestamp is assumed to be pre-normalized to the desired local
527 * @param string $format
528 * @param string $ts 14-character timestamp
532 function sprintfDate( $format, $ts ) {
541 for ( $p = 0; $p < strlen( $format ); $p++
) {
544 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
545 $code .= $format[++
$p];
548 if ( ( $code === 'xi' ||
$code == 'xj' ) && $p < strlen( $format ) - 1 ) {
549 $code .= $format[++
$p];
560 $rawToggle = !$rawToggle;
569 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
572 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
573 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
576 $num = substr( $ts, 6, 2 );
579 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
580 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
583 $num = intval( substr( $ts, 6, 2 ) );
586 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
590 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
594 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
595 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
598 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
599 $w = gmdate( 'w', $unix );
603 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
604 $num = gmdate( 'w', $unix );
607 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
608 $num = gmdate( 'z', $unix );
611 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
612 $num = gmdate( 'W', $unix );
615 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
618 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
619 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
622 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
623 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
626 $num = substr( $ts, 4, 2 );
629 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
632 $num = intval( substr( $ts, 4, 2 ) );
635 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
639 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
643 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
644 $num = gmdate( 't', $unix );
647 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
648 $num = gmdate( 'L', $unix );
651 $num = substr( $ts, 0, 4 );
654 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
658 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
662 $num = substr( $ts, 2, 2 );
665 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
668 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
671 $h = substr( $ts, 8, 2 );
672 $num = $h %
12 ?
$h %
12 : 12;
675 $num = intval( substr( $ts, 8, 2 ) );
678 $h = substr( $ts, 8, 2 );
679 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
682 $num = substr( $ts, 8, 2 );
685 $num = substr( $ts, 10, 2 );
688 $num = substr( $ts, 12, 2 );
691 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
692 $s .= gmdate( 'c', $unix );
695 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
696 $s .= gmdate( 'r', $unix );
699 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
704 if ( $p < strlen( $format ) - 1 ) {
712 if ( $p < strlen( $format ) - 1 ) {
713 $endQuote = strpos( $format, '"', $p +
1 );
714 if ( $endQuote === false ) {
715 # No terminating quote, assume literal "
718 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
722 # Quote at end of string, assume literal "
729 if ( $num !== false ) {
730 if ( $rawToggle ||
$raw ) {
733 } elseif ( $roman ) {
734 $s .= self
::romanNumeral( $num );
736 } elseif( $hebrewNum ) {
737 $s .= self
::hebrewNumeral( $num );
740 $s .= $this->formatNum( $num, true );
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 );
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.
756 * Link: http://www.farsiweb.info/jalali/jalali.c
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;
763 # Days passed from the beginning (including leap years)
766 - floor(($gy+
99) / 100)
767 +
floor(($gy+
399) / 400);
770 // Add days of the past months of this year
771 for( $i = 0; $i < $gm; $i++
) {
772 $gDayNo +
= self
::$GREG_DAYS[$i];
776 if ( $gm > 1 && (($gy%4
===0 && $gy%100
!==0 ||
($gy%400
==0)))) {
780 // Days passed in current month
783 $jDayNo = $gDayNo - 79;
785 $jNp = floor($jDayNo / 12053);
788 $jy = 979 +
33*$jNp +
4*floor($jDayNo/1461);
791 if ( $jDayNo >= 366 ) {
792 $jy +
= floor(($jDayNo-1)/365);
793 $jDayNo = floor(($jDayNo-1)%365
);
796 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
797 $jDayNo -= self
::$IRANIAN_DAYS[$i];
803 return array($jy, $jm, $jd);
807 * Converting Gregorian dates to Hebrew dates.
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
814 private static function tsToHebrew( $ts ) {
816 $year = substr( $ts, 0, 4 );
817 $month = substr( $ts, 4, 2 );
818 $day = substr( $ts, 6, 2 );
820 # Month number when March = 1, February = 12
823 # January of February
828 # Days since 1 March - calculating 30 days a month,
829 # and then adding the missing number of days
830 $day +
= (int)( 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)
839 # Add days since previous year's 1 March
841 if( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
848 # Passover date for the new year (as days since 1 March)
849 $passover = self
::passoverDate( $hebrewYear );
851 # Next year's passover (as days since 1 March)
852 $anchor = self
::passoverDate( $hebrewYear +
1 );
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
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
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)
876 } else if( $month == 8 && $anchor %
30 == 0 ) {
877 # Kislev in an incomplete year (otherwise as the rule below)
880 # Even months have 30 days, odd have 29
881 $days = 30 - $month %
2;
883 if( $day <= $days ) {
891 # Now we move to a year from Tishrei
893 # After Tishrei, use next year
896 # Recalculate month number so that we start from Tishrei
897 $month = ( $month +
6 ) %
12 +
1;
900 if( $month == 6 && $anchor >= 30 ) {
901 # This *is* adar, and this year is leap
912 return array( $hebrewYear, $month, $day );
916 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
917 * Used for Hebrew date.
919 private static function passoverDate( $year ) {
920 $a = (int)( ( 12 * $year +
17 ) %
19 );
921 $b = (int)( $year %
4 );
922 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * $year;
932 $c = (int)( ( $Mar +
3 * $year +
5 * $b +
5 ) %
7);
933 if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
935 } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
937 } else if( $c == 2 ||
$c == 4 ||
$c == 6 ) {
941 $Mar +
= (int)( ( $year - 3760 ) / 100 ) - (int)( ( $year - 3760 ) / 400 ) - 2;
946 * Roman number formatting up to 3000
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' )
956 $num = intval( $num );
957 if ( $num > 3000 ||
$num <= 0 ) {
962 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
963 if ( $num >= $pow10 ) {
964 $s .= $table[$i][floor($num / $pow10)];
966 $num = $num %
$pow10;
972 * Hebrew Gematria number formatting up to 9999
974 static function hebrewNumeral( $num ) {
975 static $table = array(
976 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
977 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
978 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
979 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
982 $num = intval( $num );
983 if ( $num > 9999 ||
$num <= 0 ) {
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 - 10];
994 $s .= $table[$i][(int)( $num / $pow10 )];
995 if( $pow10 == 1000 ) {
1000 $num = $num %
$pow10;
1002 if( strlen( $s ) == 2 ) {
1005 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1006 $str .= substr( $s, strlen( $s ) - 2, 2 );
1012 * This is meant to be used by time(), date(), and timeanddate() to get
1013 * the date preference they're supposed to use, it should be used in
1017 * function timeanddate([...], $format = true) {
1018 * $datePreference = $this->dateFormat($format);
1023 * @param mixed $usePrefs: if true, the user's preference is used
1024 * if false, the site/language default is used
1025 * if int/string, assumed to be a format.
1028 function dateFormat( $usePrefs = true ) {
1031 if( is_bool( $usePrefs ) ) {
1033 $datePreference = $wgUser->getDatePreference();
1035 $options = User
::getDefaultOptions();
1036 $datePreference = (string)$options['date'];
1039 $datePreference = (string)$usePrefs;
1043 if( $datePreference == '' ) {
1047 return $datePreference;
1052 * @param mixed $ts the time format which needs to be turned into a
1053 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1054 * @param bool $adj whether to adjust the time output according to the
1055 * user configured offset ($timecorrection)
1056 * @param mixed $format true to use user's date format preference
1057 * @param string $timecorrection the time offset as returned by
1058 * validateTimeZone() in Special:Preferences
1061 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1064 $ts = $this->userAdjust( $ts, $timecorrection );
1067 $pref = $this->dateFormat( $format );
1068 if( $pref == 'default' ||
!isset( $this->dateFormats
["$pref date"] ) ) {
1069 $pref = $this->defaultDateFormat
;
1071 return $this->sprintfDate( $this->dateFormats
["$pref date"], $ts );
1076 * @param mixed $ts the time format which needs to be turned into a
1077 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1078 * @param bool $adj whether to adjust the time output according to the
1079 * user configured offset ($timecorrection)
1080 * @param mixed $format true to use user's date format preference
1081 * @param string $timecorrection the time offset as returned by
1082 * validateTimeZone() in Special:Preferences
1085 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1088 $ts = $this->userAdjust( $ts, $timecorrection );
1091 $pref = $this->dateFormat( $format );
1092 if( $pref == 'default' ||
!isset( $this->dateFormats
["$pref time"] ) ) {
1093 $pref = $this->defaultDateFormat
;
1095 return $this->sprintfDate( $this->dateFormats
["$pref time"], $ts );
1100 * @param mixed $ts the time format which needs to be turned into a
1101 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1102 * @param bool $adj whether to adjust the time output according to the
1103 * user configured offset ($timecorrection)
1105 * @param mixed $format what format to return, if it's false output the
1106 * default one (default true)
1107 * @param string $timecorrection the time offset as returned by
1108 * validateTimeZone() in Special:Preferences
1111 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
1114 $ts = wfTimestamp( TS_MW
, $ts );
1117 $ts = $this->userAdjust( $ts, $timecorrection );
1120 $pref = $this->dateFormat( $format );
1121 if( $pref == 'default' ||
!isset( $this->dateFormats
["$pref both"] ) ) {
1122 $pref = $this->defaultDateFormat
;
1125 return $this->sprintfDate( $this->dateFormats
["$pref both"], $ts );
1128 function getMessage( $key ) {
1130 return isset( $this->messages
[$key] ) ?
$this->messages
[$key] : null;
1133 function getAllMessages() {
1135 return $this->messages
;
1138 function iconv( $in, $out, $string ) {
1139 # For most languages, this is a wrapper for iconv
1140 return iconv( $in, $out . '//IGNORE', $string );
1143 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1144 function ucwordbreaksCallbackAscii($matches){
1145 return $this->ucfirst($matches[1]);
1148 function ucwordbreaksCallbackMB($matches){
1149 return mb_strtoupper($matches[0]);
1152 function ucCallback($matches){
1153 list( $wikiUpperChars ) = self
::getCaseMaps();
1154 return strtr( $matches[1], $wikiUpperChars );
1157 function lcCallback($matches){
1158 list( , $wikiLowerChars ) = self
::getCaseMaps();
1159 return strtr( $matches[1], $wikiLowerChars );
1162 function ucwordsCallbackMB($matches){
1163 return mb_strtoupper($matches[0]);
1166 function ucwordsCallbackWiki($matches){
1167 list( $wikiUpperChars ) = self
::getCaseMaps();
1168 return strtr( $matches[0], $wikiUpperChars );
1171 function ucfirst( $str ) {
1172 if ( empty($str) ) return $str;
1173 if ( ord($str[0]) < 128 ) return ucfirst($str);
1174 else return self
::uc($str,true); // fall back to more complex logic in case of multibyte strings
1177 function uc( $str, $first = false ) {
1178 if ( function_exists( 'mb_strtoupper' ) ) {
1180 if ( self
::isMultibyte( $str ) ) {
1181 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1183 return ucfirst( $str );
1186 return self
::isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1189 if ( self
::isMultibyte( $str ) ) {
1190 list( $wikiUpperChars ) = $this->getCaseMaps();
1191 $x = $first ?
'^' : '';
1192 return preg_replace_callback(
1193 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1194 array($this,"ucCallback"),
1198 return $first ?
ucfirst( $str ) : strtoupper( $str );
1203 function lcfirst( $str ) {
1204 if ( empty($str) ) return $str;
1205 if ( ord($str[0]) < 128 ) {
1206 // editing string in place = cool
1207 $str[0]=strtolower($str[0]);
1210 else return self
::lc( $str, true );
1213 function lc( $str, $first = false ) {
1214 if ( function_exists( 'mb_strtolower' ) )
1216 if ( self
::isMultibyte( $str ) )
1217 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1219 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1221 return self
::isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1223 if ( self
::isMultibyte( $str ) ) {
1224 list( , $wikiLowerChars ) = self
::getCaseMaps();
1225 $x = $first ?
'^' : '';
1226 return preg_replace_callback(
1227 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1228 array($this,"lcCallback"),
1232 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1235 function isMultibyte( $str ) {
1236 return (bool)preg_match( '/[\x80-\xff]/', $str );
1239 function ucwords($str) {
1240 if ( self
::isMultibyte( $str ) ) {
1241 $str = self
::lc($str);
1243 // regexp to find first letter in each word (i.e. after each space)
1244 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1246 // function to use to capitalize a single char
1247 if ( function_exists( 'mb_strtoupper' ) )
1248 return preg_replace_callback(
1250 array($this,"ucwordsCallbackMB"),
1254 return preg_replace_callback(
1256 array($this,"ucwordsCallbackWiki"),
1261 return ucwords( strtolower( $str ) );
1264 # capitalize words at word breaks
1265 function ucwordbreaks($str){
1266 if (self
::isMultibyte( $str ) ) {
1267 $str = self
::lc($str);
1269 // since \b doesn't work for UTF-8, we explicitely define word break chars
1270 $breaks= "[ \-\(\)\}\{\.,\?!]";
1272 // find first letter after word break
1273 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1275 if ( function_exists( 'mb_strtoupper' ) )
1276 return preg_replace_callback(
1278 array($this,"ucwordbreaksCallbackMB"),
1282 return preg_replace_callback(
1284 array($this,"ucwordsCallbackWiki"),
1289 return preg_replace_callback(
1290 '/\b([\w\x80-\xff]+)\b/',
1291 array($this,"ucwordbreaksCallbackAscii"),
1296 * Return a case-folded representation of $s
1298 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1299 * and $s2 are the same except for the case of their characters. It is not
1300 * necessary for the value returned to make sense when displayed.
1302 * Do *not* perform any other normalisation in this function. If a caller
1303 * uses this function when it should be using a more general normalisation
1304 * function, then fix the caller.
1306 function caseFold( $s ) {
1307 return $this->uc( $s );
1310 function checkTitleEncoding( $s ) {
1311 if( is_array( $s ) ) {
1312 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1314 # Check for non-UTF-8 URLs
1315 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1316 if(!$ishigh) return $s;
1318 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1319 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1320 if( $isutf8 ) return $s;
1322 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
1325 function fallback8bitEncoding() {
1327 return $this->fallback8bitEncoding
;
1331 * Some languages have special punctuation to strip out
1332 * or characters which need to be converted for MySQL's
1333 * indexing to grok it correctly. Make such changes here.
1338 function stripForSearch( $string ) {
1340 if ( $wgDBtype != 'mysql' ) {
1344 # MySQL fulltext index doesn't grok utf-8, so we
1345 # need to fold cases and convert to hex
1347 wfProfileIn( __METHOD__
);
1348 if( function_exists( 'mb_strtolower' ) ) {
1349 $out = preg_replace(
1350 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1351 "'U8' . bin2hex( \"$1\" )",
1352 mb_strtolower( $string ) );
1354 list( , $wikiLowerChars ) = self
::getCaseMaps();
1355 $out = preg_replace(
1356 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1357 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1360 wfProfileOut( __METHOD__
);
1364 function convertForSearchResult( $termsArray ) {
1365 # some languages, e.g. Chinese, need to do a conversion
1366 # in order for search results to be displayed correctly
1371 * Get the first character of a string.
1376 function firstChar( $s ) {
1378 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1379 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
1381 return isset( $matches[1] ) ?
$matches[1] : "";
1384 function initEncoding() {
1385 # Some languages may have an alternate char encoding option
1386 # (Esperanto X-coding, Japanese furigana conversion, etc)
1387 # If this language is used as the primary content language,
1388 # an override to the defaults can be set here on startup.
1391 function recodeForEdit( $s ) {
1392 # For some languages we'll want to explicitly specify
1393 # which characters make it into the edit box raw
1394 # or are converted in some way or another.
1395 # Note that if wgOutputEncoding is different from
1396 # wgInputEncoding, this text will be further converted
1397 # to wgOutputEncoding.
1398 global $wgEditEncoding;
1399 if( $wgEditEncoding == '' or
1400 $wgEditEncoding == 'UTF-8' ) {
1403 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1407 function recodeInput( $s ) {
1408 # Take the previous into account.
1409 global $wgEditEncoding;
1410 if($wgEditEncoding != "") {
1411 $enc = $wgEditEncoding;
1415 if( $enc == 'UTF-8' ) {
1418 return $this->iconv( $enc, 'UTF-8', $s );
1423 * For right-to-left language support
1433 * A hidden direction mark (LRM or RLM), depending on the language direction
1437 function getDirMark() {
1438 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
1442 * An arrow, depending on the language direction
1446 function getArrow() {
1447 return $this->isRTL() ?
'←' : '→';
1451 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
1455 function linkPrefixExtension() {
1457 return $this->linkPrefixExtension
;
1460 function &getMagicWords() {
1462 return $this->magicWords
;
1465 # Fill a MagicWord object with data from here
1466 function getMagic( &$mw ) {
1467 if ( !$this->mMagicHookDone
) {
1468 $this->mMagicHookDone
= true;
1469 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
1471 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
1472 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
1474 $magicWords =& $this->getMagicWords();
1475 if ( isset( $magicWords[$mw->mId
] ) ) {
1476 $rawEntry = $magicWords[$mw->mId
];
1478 # Fall back to English if local list is incomplete
1479 $magicWords =& Language
::getMagicWords();
1480 $rawEntry = $magicWords[$mw->mId
];
1484 if( !is_array( $rawEntry ) ) {
1485 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
1487 $mw->mCaseSensitive
= $rawEntry[0];
1488 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
1492 * Add magic words to the extension array
1494 function addMagicWordsByLang( $newWords ) {
1495 $code = $this->getCode();
1496 $fallbackChain = array();
1497 while ( $code && !in_array( $code, $fallbackChain ) ) {
1498 $fallbackChain[] = $code;
1499 $code = self
::getFallbackFor( $code );
1501 if ( !in_array( 'en', $fallbackChain ) ) {
1502 $fallbackChain[] = 'en';
1504 $fallbackChain = array_reverse( $fallbackChain );
1505 foreach ( $fallbackChain as $code ) {
1506 if ( isset( $newWords[$code] ) ) {
1507 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
1513 * Get special page names, as an associative array
1514 * case folded alias => real name
1516 function getSpecialPageAliases() {
1518 if ( !isset( $this->mExtendedSpecialPageAliases
) ) {
1519 $this->mExtendedSpecialPageAliases
= $this->specialPageAliases
;
1520 wfRunHooks( 'LanguageGetSpecialPageAliases',
1521 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
1523 return $this->mExtendedSpecialPageAliases
;
1527 * Italic is unsuitable for some languages
1531 * @param string $text The text to be emphasized.
1534 function emphasize( $text ) {
1535 return "<em>$text</em>";
1539 * Normally we output all numbers in plain en_US style, that is
1540 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
1541 * point twohundredthirtyfive. However this is not sutable for all
1542 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
1543 * Icelandic just want to use commas instead of dots, and dots instead
1544 * of commas like "293.291,235".
1546 * An example of this function being called:
1548 * wfMsg( 'message', $wgLang->formatNum( $num ) )
1551 * See LanguageGu.php for the Gujarati implementation and
1552 * LanguageIs.php for the , => . and . => , implementation.
1554 * @todo check if it's viable to use localeconv() for the decimal
1557 * @param mixed $number the string to be formatted, should be an integer or
1558 * a floating point number.
1559 * @param bool $nocommafy Set to true for special numbers like dates
1562 function formatNum( $number, $nocommafy = false ) {
1563 global $wgTranslateNumerals;
1565 $number = $this->commafy($number);
1566 $s = $this->separatorTransformTable();
1567 if (!is_null($s)) { $number = strtr($number, $s); }
1570 if ($wgTranslateNumerals) {
1571 $s = $this->digitTransformTable();
1572 if (!is_null($s)) { $number = strtr($number, $s); }
1578 function parseFormattedNumber( $number ) {
1579 $s = $this->digitTransformTable();
1580 if (!is_null($s)) { $number = strtr($number, array_flip($s)); }
1582 $s = $this->separatorTransformTable();
1583 if (!is_null($s)) { $number = strtr($number, array_flip($s)); }
1585 $number = strtr( $number, array (',' => '') );
1590 * Adds commas to a given number
1595 function commafy($_) {
1596 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
1599 function digitTransformTable() {
1601 return $this->digitTransformTable
;
1604 function separatorTransformTable() {
1606 return $this->separatorTransformTable
;
1611 * For the credit list in includes/Credits.php (action=credits)
1616 function listToText( $l ) {
1619 for ($i = $m; $i >= 0; $i--) {
1622 } else if ($i == $m - 1) {
1623 $s = $l[$i] . ' ' . $this->getMessageFromDB( 'and' ) . ' ' . $s;
1625 $s = $l[$i] . ', ' . $s;
1632 * Truncate a string to a specified length in bytes, appending an optional
1633 * string (e.g. for ellipses)
1635 * The database offers limited byte lengths for some columns in the database;
1636 * multi-byte character sets mean we need to ensure that only whole characters
1637 * are included, otherwise broken characters can be passed to the user
1639 * If $length is negative, the string will be truncated from the beginning
1641 * @param string $string String to truncate
1642 * @param int $length Maximum length (excluding ellipses)
1643 * @param string $ellipses String to append to the truncated text
1646 function truncate( $string, $length, $ellipsis = "" ) {
1647 if( $length == 0 ) {
1650 if ( strlen( $string ) <= abs( $length ) ) {
1654 $string = substr( $string, 0, $length );
1655 $char = ord( $string[strlen( $string ) - 1] );
1657 if ($char >= 0xc0) {
1658 # We got the first byte only of a multibyte char; remove it.
1659 $string = substr( $string, 0, -1 );
1660 } elseif( $char >= 0x80 &&
1661 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
1662 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
1663 # We chopped in the middle of a character; remove it
1666 return $string . $ellipsis;
1668 $string = substr( $string, $length );
1669 $char = ord( $string[0] );
1670 if( $char >= 0x80 && $char < 0xc0 ) {
1671 # We chopped in the middle of a character; remove the whole thing
1672 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
1674 return $ellipsis . $string;
1679 * Grammatical transformations, needed for inflected languages
1680 * Invoked by putting {{grammar:case|word}} in a message
1682 * @param string $word
1683 * @param string $case
1686 function convertGrammar( $word, $case ) {
1687 global $wgGrammarForms;
1688 if ( isset($wgGrammarForms['en'][$case][$word]) ) {
1689 return $wgGrammarForms['en'][$case][$word];
1695 * Plural form transformations, needed for some languages.
1696 * For example, there are 3 form of plural in Russian and Polish,
1697 * depending on "count mod 10". See [[w:Plural]]
1698 * For English it is pretty simple.
1700 * Invoked by putting {{plural:count|wordform1|wordform2}}
1701 * or {{plural:count|wordform1|wordform2|wordform3}}
1703 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
1705 * @param integer $count
1706 * @param string $wordform1
1707 * @param string $wordform2
1708 * @param string $wordform3 (optional)
1709 * @param string $wordform4 (optional)
1710 * @param string $wordform5 (optional)
1713 function convertPlural( $count, $w1, $w2, $w3, $w4, $w5) {
1714 return ( $count == '1' ||
$count == '-1' ) ?
$w1 : $w2;
1718 * For translaing of expiry times
1719 * @param string The validated block time in English
1720 * @return Somehow translated block time
1721 * @see LanguageFi.php for example implementation
1723 function translateBlockExpiry( $str ) {
1725 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
1727 if ( $scBlockExpiryOptions == '-') {
1731 foreach (explode(',', $scBlockExpiryOptions) as $option) {
1732 if ( strpos($option, ":") === false )
1734 list($show, $value) = explode(":", $option);
1735 if ( strcmp ( $str, $value) == 0 ) {
1736 return htmlspecialchars( trim( $show ) );
1744 * languages like Chinese need to be segmented in order for the diff
1747 * @param string $text
1750 function segmentForDiff( $text ) {
1755 * and unsegment to show the result
1757 * @param string $text
1760 function unsegmentForDiff( $text ) {
1764 # convert text to different variants of a language.
1765 function convert( $text, $isTitle = false) {
1766 return $this->mConverter
->convert($text, $isTitle);
1769 # Convert text from within Parser
1770 function parserConvert( $text, &$parser ) {
1771 return $this->mConverter
->parserConvert( $text, $parser );
1774 # Check if this is a language with variants
1775 function hasVariants(){
1776 return sizeof($this->getVariants())>1;
1779 # Put custom tags (e.g. -{ }-) around math to prevent conversion
1780 function armourMath($text){
1781 return $this->mConverter
->armourMath($text);
1786 * Perform output conversion on a string, and encode for safe HTML output.
1787 * @param string $text
1788 * @param bool $isTitle -- wtf?
1790 * @todo this should get integrated somewhere sane
1792 function convertHtml( $text, $isTitle = false ) {
1793 return htmlspecialchars( $this->convert( $text, $isTitle ) );
1796 function convertCategoryKey( $key ) {
1797 return $this->mConverter
->convertCategoryKey( $key );
1801 * get the list of variants supported by this langauge
1802 * see sample implementation in LanguageZh.php
1804 * @return array an array of language codes
1806 function getVariants() {
1807 return $this->mConverter
->getVariants();
1811 function getPreferredVariant( $fromUser = true ) {
1812 return $this->mConverter
->getPreferredVariant( $fromUser );
1816 * if a language supports multiple variants, it is
1817 * possible that non-existing link in one variant
1818 * actually exists in another variant. this function
1819 * tries to find it. See e.g. LanguageZh.php
1821 * @param string $link the name of the link
1822 * @param mixed $nt the title object of the link
1823 * @return null the input parameters may be modified upon return
1825 function findVariantLink( &$link, &$nt ) {
1826 $this->mConverter
->findVariantLink($link, $nt);
1830 * If a language supports multiple variants, converts text
1831 * into an array of all possible variants of the text:
1832 * 'variant' => text in that variant
1835 function convertLinkToAllVariants($text){
1836 return $this->mConverter
->convertLinkToAllVariants($text);
1841 * returns language specific options used by User::getPageRenderHash()
1842 * for example, the preferred language variant
1847 function getExtraHashOptions() {
1848 return $this->mConverter
->getExtraHashOptions();
1852 * for languages that support multiple variants, the title of an
1853 * article may be displayed differently in different variants. this
1854 * function returns the apporiate title defined in the body of the article.
1858 function getParsedTitle() {
1859 return $this->mConverter
->getParsedTitle();
1863 * Enclose a string with the "no conversion" tag. This is used by
1864 * various functions in the Parser
1866 * @param string $text text to be tagged for no conversion
1867 * @return string the tagged text
1869 function markNoConversion( $text, $noParse=false ) {
1870 return $this->mConverter
->markNoConversion( $text, $noParse );
1874 * A regular expression to match legal word-trailing characters
1875 * which should be merged onto a link of the form [[foo]]bar.
1880 function linkTrail() {
1882 return $this->linkTrail
;
1885 function getLangObj() {
1890 * Get the RFC 3066 code for this language object
1892 function getCode() {
1893 return $this->mCode
;
1896 function setCode( $code ) {
1897 $this->mCode
= $code;
1900 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
1901 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
1904 static function getMessagesFileName( $code ) {
1906 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
1909 static function getClassFileName( $code ) {
1911 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
1914 static function getLocalisationArray( $code, $disableCache = false ) {
1915 self
::loadLocalisation( $code, $disableCache );
1916 return self
::$mLocalisationCache[$code];
1920 * Load localisation data for a given code into the static cache
1922 * @return array Dependencies, map of filenames to mtimes
1924 static function loadLocalisation( $code, $disableCache = false ) {
1925 static $recursionGuard = array();
1929 throw new MWException( "Invalid language code requested" );
1932 if ( !$disableCache ) {
1933 # Try the per-process cache
1934 if ( isset( self
::$mLocalisationCache[$code] ) ) {
1935 return self
::$mLocalisationCache[$code]['deps'];
1938 wfProfileIn( __METHOD__
);
1940 # Try the serialized directory
1941 $cache = wfGetPrecompiledData( self
::getFileName( "Messages", $code, '.ser' ) );
1943 self
::$mLocalisationCache[$code] = $cache;
1944 wfDebug( "Language::loadLocalisation(): got localisation for $code from precompiled data file\n" );
1945 wfProfileOut( __METHOD__
);
1946 return self
::$mLocalisationCache[$code]['deps'];
1949 # Try the global cache
1950 $memcKey = wfMemcKey('localisation', $code );
1951 $cache = $wgMemc->get( $memcKey );
1953 # Check file modification times
1954 foreach ( $cache['deps'] as $file => $mtime ) {
1955 if ( !file_exists( $file ) ||
filemtime( $file ) > $mtime ) {
1959 if ( self
::isLocalisationOutOfDate( $cache ) ) {
1960 $wgMemc->delete( $memcKey );
1962 wfDebug( "Language::loadLocalisation(): localisation cache for $code had expired due to update of $file\n" );
1964 self
::$mLocalisationCache[$code] = $cache;
1965 wfDebug( "Language::loadLocalisation(): got localisation for $code from cache\n" );
1966 wfProfileOut( __METHOD__
);
1967 return $cache['deps'];
1971 wfProfileIn( __METHOD__
);
1974 # Default fallback, may be overridden when the messages file is included
1975 if ( $code != 'en' ) {
1981 # Load the primary localisation from the source file
1982 $filename = self
::getMessagesFileName( $code );
1983 if ( !file_exists( $filename ) ) {
1984 wfDebug( "Language::loadLocalisation(): no localisation file for $code, using implicit fallback to en\n" );
1988 $deps = array( $filename => filemtime( $filename ) );
1989 require( $filename );
1990 $cache = compact( self
::$mLocalisationKeys );
1991 wfDebug( "Language::loadLocalisation(): got localisation for $code from source\n" );
1994 if ( !empty( $fallback ) ) {
1995 # Load the fallback localisation, with a circular reference guard
1996 if ( isset( $recursionGuard[$code] ) ) {
1997 throw new MWException( "Error: Circular fallback reference in language code $code" );
1999 $recursionGuard[$code] = true;
2000 $newDeps = self
::loadLocalisation( $fallback, $disableCache );
2001 unset( $recursionGuard[$code] );
2003 $secondary = self
::$mLocalisationCache[$fallback];
2004 $deps = array_merge( $deps, $newDeps );
2006 # Merge the fallback localisation with the current localisation
2007 foreach ( self
::$mLocalisationKeys as $key ) {
2008 if ( isset( $cache[$key] ) ) {
2009 if ( isset( $secondary[$key] ) ) {
2010 if ( in_array( $key, self
::$mMergeableMapKeys ) ) {
2011 $cache[$key] = $cache[$key] +
$secondary[$key];
2012 } elseif ( in_array( $key, self
::$mMergeableListKeys ) ) {
2013 $cache[$key] = array_merge( $secondary[$key], $cache[$key] );
2014 } elseif ( in_array( $key, self
::$mMergeableAliasListKeys ) ) {
2015 $cache[$key] = array_merge_recursive( $cache[$key], $secondary[$key] );
2019 $cache[$key] = $secondary[$key];
2023 # Merge bookstore lists if requested
2024 if ( !empty( $cache['bookstoreList']['inherit'] ) ) {
2025 $cache['bookstoreList'] = array_merge( $cache['bookstoreList'], $secondary['bookstoreList'] );
2027 if ( isset( $cache['bookstoreList']['inherit'] ) ) {
2028 unset( $cache['bookstoreList']['inherit'] );
2032 # Add dependencies to the cache entry
2033 $cache['deps'] = $deps;
2035 # Replace spaces with underscores in namespace names
2036 $cache['namespaceNames'] = str_replace( ' ', '_', $cache['namespaceNames'] );
2038 # Save to both caches
2039 self
::$mLocalisationCache[$code] = $cache;
2040 if ( !$disableCache ) {
2041 $wgMemc->set( $memcKey, $cache );
2044 wfProfileOut( __METHOD__
);
2049 * Test if a given localisation cache is out of date with respect to the
2050 * source Messages files. This is done automatically for the global cache
2051 * in $wgMemc, but is only done on certain occasions for the serialized
2054 * @param $cache mixed Either a language code or a cache array
2056 static function isLocalisationOutOfDate( $cache ) {
2057 if ( !is_array( $cache ) ) {
2058 self
::loadLocalisation( $cache );
2059 $cache = self
::$mLocalisationCache[$cache];
2062 foreach ( $cache['deps'] as $file => $mtime ) {
2063 if ( !file_exists( $file ) ||
filemtime( $file ) > $mtime ) {
2072 * Get the fallback for a given language
2074 static function getFallbackFor( $code ) {
2075 self
::loadLocalisation( $code );
2076 return self
::$mLocalisationCache[$code]['fallback'];
2080 * Get all messages for a given language
2082 static function getMessagesFor( $code ) {
2083 self
::loadLocalisation( $code );
2084 return self
::$mLocalisationCache[$code]['messages'];
2088 * Get a message for a given language
2090 static function getMessageFor( $key, $code ) {
2091 self
::loadLocalisation( $code );
2092 return isset( self
::$mLocalisationCache[$code]['messages'][$key] ) ? self
::$mLocalisationCache[$code]['messages'][$key] : null;
2096 * Load localisation data for this object
2099 if ( !$this->mLoaded
) {
2100 self
::loadLocalisation( $this->getCode() );
2101 $cache =& self
::$mLocalisationCache[$this->getCode()];
2102 foreach ( self
::$mLocalisationKeys as $key ) {
2103 $this->$key = $cache[$key];
2105 $this->mLoaded
= true;
2107 $this->fixUpSettings();
2112 * Do any necessary post-cache-load settings adjustment
2114 function fixUpSettings() {
2115 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk,
2116 $wgNamespaceAliases, $wgAmericanDates;
2117 wfProfileIn( __METHOD__
);
2118 if ( $wgExtraNamespaces ) {
2119 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames
;
2122 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
2123 if ( $wgMetaNamespaceTalk ) {
2124 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
2126 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
2127 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2129 # Allow grammar transformations
2130 # Allowing full message-style parsing would make simple requests
2131 # such as action=raw much more expensive than they need to be.
2132 # This will hopefully cover most cases.
2133 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2134 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2135 $talk = str_replace( ' ', '_', $talk );
2136 $this->namespaceNames
[NS_PROJECT_TALK
] = $talk;
2139 # The above mixing may leave namespaces out of canonical order.
2140 # Re-order by namespace ID number...
2141 ksort( $this->namespaceNames
);
2143 # Put namespace names and aliases into a hashtable.
2144 # If this is too slow, then we should arrange it so that it is done
2145 # before caching. The catch is that at pre-cache time, the above
2146 # class-specific fixup hasn't been done.
2147 $this->mNamespaceIds
= array();
2148 foreach ( $this->namespaceNames
as $index => $name ) {
2149 $this->mNamespaceIds
[$this->lc($name)] = $index;
2151 if ( $this->namespaceAliases
) {
2152 foreach ( $this->namespaceAliases
as $name => $index ) {
2153 $this->mNamespaceIds
[$this->lc($name)] = $index;
2156 if ( $wgNamespaceAliases ) {
2157 foreach ( $wgNamespaceAliases as $name => $index ) {
2158 $this->mNamespaceIds
[$this->lc($name)] = $index;
2162 if ( $this->defaultDateFormat
== 'dmy or mdy' ) {
2163 $this->defaultDateFormat
= $wgAmericanDates ?
'mdy' : 'dmy';
2165 wfProfileOut( __METHOD__
);
2168 function replaceGrammarInNamespace( $m ) {
2169 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2172 static function getCaseMaps() {
2173 static $wikiUpperChars, $wikiLowerChars;
2174 if ( isset( $wikiUpperChars ) ) {
2175 return array( $wikiUpperChars, $wikiLowerChars );
2178 wfProfileIn( __METHOD__
);
2179 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2180 if ( $arr === false ) {
2181 throw new MWException(
2182 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2185 wfProfileOut( __METHOD__
);
2186 return array( $wikiUpperChars, $wikiLowerChars );
2189 function formatTimePeriod( $seconds ) {
2190 if ( $seconds < 10 ) {
2191 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . wfMsg( 'seconds-abbrev' );
2192 } elseif ( $seconds < 60 ) {
2193 return $this->formatNum( round( $seconds ) ) . wfMsg( 'seconds-abbrev' );
2194 } elseif ( $seconds < 3600 ) {
2195 return $this->formatNum( floor( $seconds / 60 ) ) . wfMsg( 'minutes-abbrev' ) .
2196 $this->formatNum( round( fmod( $seconds, 60 ) ) ) . wfMsg( 'seconds-abbrev' );
2198 $hours = floor( $seconds / 3600 );
2199 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2200 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2201 return $this->formatNum( $hours ) . wfMsg( 'hours-abbrev' ) .
2202 $this->formatNum( $minutes ) . wfMsg( 'minutes-abbrev' ) .
2203 $this->formatNum( $secondsPart ) . wfMsg( 'seconds-abbrev' );
2207 function formatBitrate( $bps ) {
2208 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2210 return $this->formatNum( $bps ) . $units[0];
2212 $unitIndex = floor( log10( $bps ) / 3 );
2213 $mantissa = $bps / pow( 1000, $unitIndex );
2214 if ( $mantissa < 10 ) {
2215 $mantissa = round( $mantissa, 1 );
2217 $mantissa = round( $mantissa );
2219 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2223 * Format a size in bytes for output, using an appropriate
2224 * unit (B, KB, MB or GB) according to the magnitude in question
2226 * @param $size Size to format
2227 * @return string Plain text (not HTML)
2229 function formatSize( $size ) {
2230 // For small sizes no decimal places necessary
2232 if( $size > 1024 ) {
2233 $size = $size / 1024;
2234 if( $size > 1024 ) {
2235 $size = $size / 1024;
2236 // For MB and bigger two decimal places are smarter
2238 if( $size > 1024 ) {
2239 $size = $size / 1024;
2240 $msg = 'size-gigabytes';
2242 $msg = 'size-megabytes';
2245 $msg = 'size-kilobytes';
2248 $msg = 'size-bytes';
2250 $size = round( $size, $round );
2251 $text = $this->getMessageFromDB( $msg );
2252 return str_replace( '$1', $this->formatNum( $size ), $text );