3 * @defgroup Language Language
9 if( !defined( 'MEDIAWIKI' ) ) {
10 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 global $wgLanguageNames;
16 require_once( dirname(__FILE__
) . '/Names.php' ) ;
18 global $wgInputEncoding, $wgOutputEncoding;
21 * These are always UTF-8, they exist only for backwards compatibility
23 $wgInputEncoding = "UTF-8";
24 $wgOutputEncoding = "UTF-8";
26 if( function_exists( 'mb_strtoupper' ) ) {
27 mb_internal_encoding('UTF-8');
31 * a fake language converter
37 function FakeConverter($langobj) {$this->mLang
= $langobj;}
38 function autoConvertToAllVariants($text) {return $text;}
39 function convert($t, $i) {return $t;}
40 function getVariants() { return array( $this->mLang
->getCode() ); }
41 function getPreferredVariant() { return $this->mLang
->getCode(); }
42 function getConvRuleTitle() { return false; }
43 function findVariantLink(&$l, &$n, $ignoreOtherCond = false) {}
44 function getExtraHashOptions() {return '';}
45 function getParsedTitle() {return '';}
46 function markNoConversion($text, $noParse=false) {return $text;}
47 function convertCategoryKey( $key ) {return $key; }
48 function convertLinkToAllVariants($text){ return array( $this->mLang
->getCode() => $text); }
49 function armourMath($text){ return $text; }
53 * Internationalisation code
57 var $mConverter, $mVariants, $mCode, $mLoaded = false;
58 var $mMagicExtensions = array(), $mMagicHookDone = false;
60 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
61 var $dateFormatStrings = array();
62 var $mExtendedSpecialPageAliases;
65 * ReplacementArray object caches
67 var $transformData = array();
69 static public $dataCache;
70 static public $mLangObjCache = array();
72 static public $mWeekdayMsgs = array(
73 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
77 static public $mWeekdayAbbrevMsgs = array(
78 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
81 static public $mMonthMsgs = array(
82 'january', 'february', 'march', 'april', 'may_long', 'june',
83 'july', 'august', 'september', 'october', 'november',
86 static public $mMonthGenMsgs = array(
87 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
88 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
91 static public $mMonthAbbrevMsgs = array(
92 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
93 'sep', 'oct', 'nov', 'dec'
96 static public $mIranianCalendarMonthMsgs = array(
97 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
98 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
99 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
100 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
103 static public $mHebrewCalendarMonthMsgs = array(
104 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
105 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
106 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
107 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
108 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
111 static public $mHebrewCalendarMonthGenMsgs = array(
112 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
113 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
114 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
115 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
116 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
119 static public $mHijriCalendarMonthMsgs = array(
120 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
121 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
122 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
123 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
127 * Get a cached language object for a given language code
129 static function factory( $code ) {
130 if ( !isset( self
::$mLangObjCache[$code] ) ) {
131 if( count( self
::$mLangObjCache ) > 10 ) {
132 // Don't keep a billion objects around, that's stupid.
133 self
::$mLangObjCache = array();
135 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
137 return self
::$mLangObjCache[$code];
141 * Create a language object for a given language code
143 protected static function newFromCode( $code ) {
145 static $recursionLevel = 0;
146 if ( $code == 'en' ) {
149 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
150 // Preload base classes to work around APC/PHP5 bug
151 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
152 include_once("$IP/languages/classes/$class.deps.php");
154 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
155 include_once("$IP/languages/classes/$class.php");
159 if ( $recursionLevel > 5 ) {
160 throw new MWException( "Language fallback loop detected when creating class $class\n" );
163 if( ! class_exists( $class ) ) {
164 $fallback = Language
::getFallbackFor( $code );
166 $lang = Language
::newFromCode( $fallback );
168 $lang->setCode( $code );
176 * Get the LocalisationCache instance
178 public static function getLocalisationCache() {
179 if ( is_null( self
::$dataCache ) ) {
180 global $wgLocalisationCacheConf;
181 $class = $wgLocalisationCacheConf['class'];
182 self
::$dataCache = new $class( $wgLocalisationCacheConf );
184 return self
::$dataCache;
187 function __construct() {
188 $this->mConverter
= new FakeConverter($this);
189 // Set the code to the name of the descendant
190 if ( get_class( $this ) == 'Language' ) {
193 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
195 self
::getLocalisationCache();
199 * Reduce memory usage
201 function __destruct() {
202 foreach ( $this as $name => $value ) {
203 unset( $this->$name );
208 * Hook which will be called if this is the content language.
209 * Descendants can use this to register hook functions or modify globals
211 function initContLang() {}
214 * @deprecated Use User::getDefaultOptions()
217 function getDefaultUserOptions() {
218 wfDeprecated( __METHOD__
);
219 return User
::getDefaultOptions();
222 function getFallbackLanguageCode() {
223 if ( $this->mCode
=== 'en' ) {
226 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
231 * Exports $wgBookstoreListEn
234 function getBookstoreList() {
235 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
241 function getNamespaces() {
242 if ( is_null( $this->namespaceNames
) ) {
243 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk;
245 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
246 if ( $wgExtraNamespaces ) {
247 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames
;
250 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
251 if ( $wgMetaNamespaceTalk ) {
252 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
254 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
255 $this->namespaceNames
[NS_PROJECT_TALK
] =
256 $this->fixVariableInNamespace( $talk );
259 # The above mixing may leave namespaces out of canonical order.
260 # Re-order by namespace ID number...
261 ksort( $this->namespaceNames
);
263 return $this->namespaceNames
;
267 * A convenience function that returns the same thing as
268 * getNamespaces() except with the array values changed to ' '
269 * where it found '_', useful for producing output to be displayed
270 * e.g. in <select> forms.
274 function getFormattedNamespaces() {
275 $ns = $this->getNamespaces();
276 foreach($ns as $k => $v) {
277 $ns[$k] = strtr($v, '_', ' ');
283 * Get a namespace value by key
285 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
286 * echo $mw_ns; // prints 'MediaWiki'
289 * @param $index Int: the array key of the namespace to return
290 * @return mixed, string if the namespace value exists, otherwise false
292 function getNsText( $index ) {
293 $ns = $this->getNamespaces();
294 return isset( $ns[$index] ) ?
$ns[$index] : false;
298 * A convenience function that returns the same thing as
299 * getNsText() except with '_' changed to ' ', useful for
304 function getFormattedNsText( $index ) {
305 $ns = $this->getNsText( $index );
306 return strtr($ns, '_', ' ');
310 * Get a namespace key by value, case insensitive.
311 * Only matches namespace names for the current language, not the
312 * canonical ones defined in Namespace.php.
314 * @param $text String
315 * @return mixed An integer if $text is a valid value otherwise false
317 function getLocalNsIndex( $text ) {
318 $lctext = $this->lc($text);
319 $ids = $this->getNamespaceIds();
320 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
323 function getNamespaceAliases() {
324 if ( is_null( $this->namespaceAliases
) ) {
325 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
329 foreach ( $aliases as $name => $index ) {
330 if ( $index === NS_PROJECT_TALK
) {
331 unset( $aliases[$name] );
332 $name = $this->fixVariableInNamespace( $name );
333 $aliases[$name] = $index;
337 $this->namespaceAliases
= $aliases;
339 return $this->namespaceAliases
;
342 function getNamespaceIds() {
343 if ( is_null( $this->mNamespaceIds
) ) {
344 global $wgNamespaceAliases;
345 # Put namespace names and aliases into a hashtable.
346 # If this is too slow, then we should arrange it so that it is done
347 # before caching. The catch is that at pre-cache time, the above
348 # class-specific fixup hasn't been done.
349 $this->mNamespaceIds
= array();
350 foreach ( $this->getNamespaces() as $index => $name ) {
351 $this->mNamespaceIds
[$this->lc($name)] = $index;
353 foreach ( $this->getNamespaceAliases() as $name => $index ) {
354 $this->mNamespaceIds
[$this->lc($name)] = $index;
356 if ( $wgNamespaceAliases ) {
357 foreach ( $wgNamespaceAliases as $name => $index ) {
358 $this->mNamespaceIds
[$this->lc($name)] = $index;
362 return $this->mNamespaceIds
;
367 * Get a namespace key by value, case insensitive. Canonical namespace
368 * names override custom ones defined for the current language.
370 * @param $text String
371 * @return mixed An integer if $text is a valid value otherwise false
373 function getNsIndex( $text ) {
374 $lctext = $this->lc($text);
375 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
378 $ids = $this->getNamespaceIds();
379 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
383 * short names for language variants used for language conversion links.
385 * @param $code String
388 function getVariantname( $code ) {
389 return $this->getMessageFromDB( "variantname-$code" );
392 function specialPage( $name ) {
393 $aliases = $this->getSpecialPageAliases();
394 if ( isset( $aliases[$name][0] ) ) {
395 $name = $aliases[$name][0];
397 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
400 function getQuickbarSettings() {
402 $this->getMessage( 'qbsettings-none' ),
403 $this->getMessage( 'qbsettings-fixedleft' ),
404 $this->getMessage( 'qbsettings-fixedright' ),
405 $this->getMessage( 'qbsettings-floatingleft' ),
406 $this->getMessage( 'qbsettings-floatingright' )
410 function getMathNames() {
411 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
414 function getDatePreferences() {
415 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
418 function getDateFormats() {
419 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
422 function getDefaultDateFormat() {
423 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
424 if ( $df === 'dmy or mdy' ) {
425 global $wgAmericanDates;
426 return $wgAmericanDates ?
'mdy' : 'dmy';
432 function getDatePreferenceMigrationMap() {
433 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
436 function getImageFile( $image ) {
437 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
440 function getDefaultUserOptionOverrides() {
441 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
444 function getExtraUserToggles() {
445 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
448 function getUserToggle( $tog ) {
449 return $this->getMessageFromDB( "tog-$tog" );
453 * Get language names, indexed by code.
454 * If $customisedOnly is true, only returns codes with a messages file
456 public static function getLanguageNames( $customisedOnly = false ) {
457 global $wgLanguageNames, $wgExtraLanguageNames;
458 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
459 if ( !$customisedOnly ) {
465 $dir = opendir( "$IP/languages/messages" );
466 while( false !== ( $file = readdir( $dir ) ) ) {
467 $code = self
::getCodeFromFileName( $file, 'Messages' );
468 if ( $code && isset( $allNames[$code] ) ) {
469 $names[$code] = $allNames[$code];
477 * Get a message from the MediaWiki namespace.
479 * @param $msg String: message name
482 function getMessageFromDB( $msg ) {
483 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
486 function getLanguageName( $code ) {
487 $names = self
::getLanguageNames();
488 if ( !array_key_exists( $code, $names ) ) {
491 return $names[$code];
494 function getMonthName( $key ) {
495 return $this->getMessageFromDB( self
::$mMonthMsgs[$key-1] );
498 function getMonthNameGen( $key ) {
499 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key-1] );
502 function getMonthAbbreviation( $key ) {
503 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key-1] );
506 function getWeekdayName( $key ) {
507 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key-1] );
510 function getWeekdayAbbreviation( $key ) {
511 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key-1] );
514 function getIranianCalendarMonthName( $key ) {
515 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key-1] );
518 function getHebrewCalendarMonthName( $key ) {
519 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key-1] );
522 function getHebrewCalendarMonthNameGen( $key ) {
523 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key-1] );
526 function getHijriCalendarMonthName( $key ) {
527 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key-1] );
531 * Used by date() and time() to adjust the time output.
533 * @param $ts Int the time in date('YmdHis') format
534 * @param $tz Mixed: adjust the time by this amount (default false, mean we
535 * get user timecorrection setting)
538 function userAdjust( $ts, $tz = false ) {
539 global $wgUser, $wgLocalTZoffset;
541 if ( $tz === false ) {
542 $tz = $wgUser->getOption( 'timecorrection' );
545 $data = explode( '|', $tz, 3 );
547 if ( $data[0] == 'ZoneInfo' ) {
548 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
549 $date = date_create( $ts, timezone_open( 'UTC' ) );
550 date_timezone_set( $date, timezone_open( $data[2] ) );
551 $date = date_format( $date, 'YmdHis' );
554 # Unrecognized timezone, default to 'Offset' with the stored offset.
559 if ( $data[0] == 'System' ||
$tz == '' ) {
560 # Global offset in minutes.
561 if( isset($wgLocalTZoffset) ) $minDiff = $wgLocalTZoffset;
562 } else if ( $data[0] == 'Offset' ) {
563 $minDiff = intval( $data[1] );
565 $data = explode( ':', $tz );
566 if( count( $data ) == 2 ) {
567 $data[0] = intval( $data[0] );
568 $data[1] = intval( $data[1] );
569 $minDiff = abs( $data[0] ) * 60 +
$data[1];
570 if ( $data[0] < 0 ) $minDiff = -$minDiff;
572 $minDiff = intval( $data[0] ) * 60;
576 # No difference ? Return time unchanged
577 if ( 0 == $minDiff ) return $ts;
579 wfSuppressWarnings(); // E_STRICT system time bitching
580 # Generate an adjusted date; take advantage of the fact that mktime
581 # will normalize out-of-range values so we don't have to split $minDiff
582 # into hours and minutes.
584 (int)substr( $ts, 8, 2) ), # Hours
585 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
586 (int)substr( $ts, 12, 2 ), # Seconds
587 (int)substr( $ts, 4, 2 ), # Month
588 (int)substr( $ts, 6, 2 ), # Day
589 (int)substr( $ts, 0, 4 ) ); #Year
591 $date = date( 'YmdHis', $t );
598 * This is a workalike of PHP's date() function, but with better
599 * internationalisation, a reduced set of format characters, and a better
602 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
603 * PHP manual for definitions. "o" format character is supported since
604 * PHP 5.1.0, previous versions return literal o.
605 * There are a number of extensions, which start with "x":
607 * xn Do not translate digits of the next numeric format character
608 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
609 * xr Use roman numerals for the next numeric format character
610 * xh Use hebrew numerals for the next numeric format character
612 * xg Genitive month name
614 * xij j (day number) in Iranian calendar
615 * xiF F (month name) in Iranian calendar
616 * xin n (month number) in Iranian calendar
617 * xiY Y (full year) in Iranian calendar
619 * xjj j (day number) in Hebrew calendar
620 * xjF F (month name) in Hebrew calendar
621 * xjt t (days in month) in Hebrew calendar
622 * xjx xg (genitive month name) in Hebrew calendar
623 * xjn n (month number) in Hebrew calendar
624 * xjY Y (full year) in Hebrew calendar
626 * xmj j (day number) in Hijri calendar
627 * xmF F (month name) in Hijri calendar
628 * xmn n (month number) in Hijri calendar
629 * xmY Y (full year) in Hijri calendar
631 * xkY Y (full year) in Thai solar calendar. Months and days are
632 * identical to the Gregorian calendar
633 * xoY Y (full year) in Minguo calendar or Juche year.
634 * Months and days are identical to the
636 * xtY Y (full year) in Japanese nengo. Months and days are
637 * identical to the Gregorian calendar
639 * Characters enclosed in double quotes will be considered literal (with
640 * the quotes themselves removed). Unmatched quotes will be considered
641 * literal quotes. Example:
643 * "The month is" F => The month is January
646 * Backslash escaping is also supported.
648 * Input timestamp is assumed to be pre-normalized to the desired local
651 * @param $format String
652 * @param $ts String: 14-character timestamp
655 * @todo emulation of "o" format character for PHP pre 5.1.0
656 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
658 function sprintfDate( $format, $ts ) {
671 for ( $p = 0; $p < strlen( $format ); $p++
) {
674 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
675 $code .= $format[++
$p];
678 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
679 $code .= $format[++
$p];
690 $rawToggle = !$rawToggle;
699 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
702 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
703 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
706 $num = substr( $ts, 6, 2 );
709 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
710 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
713 $num = intval( substr( $ts, 6, 2 ) );
716 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
720 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
724 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
728 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
729 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
732 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
733 $w = gmdate( 'w', $unix );
737 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
738 $num = gmdate( 'w', $unix );
741 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
742 $num = gmdate( 'z', $unix );
745 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
746 $num = gmdate( 'W', $unix );
749 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
752 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
753 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
756 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
757 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
760 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
761 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
764 $num = substr( $ts, 4, 2 );
767 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
770 $num = intval( substr( $ts, 4, 2 ) );
773 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
777 if ( !$hijri ) $hijri = self
::tsToHijri ( $ts );
781 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
785 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
786 $num = gmdate( 't', $unix );
789 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
793 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
794 $num = gmdate( 'L', $unix );
796 # 'o' is supported since PHP 5.1.0
797 # return literal if not supported
798 # TODO: emulation for pre 5.1.0 versions
800 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
801 if ( version_compare(PHP_VERSION
, '5.1.0') === 1 )
802 $num = date( 'o', $unix );
807 $num = substr( $ts, 0, 4 );
810 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
814 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
818 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
822 if ( !$thai ) $thai = self
::tsToYear( $ts, 'thai' );
826 if ( !$minguo ) $minguo = self
::tsToYear( $ts, 'minguo' );
830 if ( !$tenno ) $tenno = self
::tsToYear( $ts, 'tenno' );
834 $num = substr( $ts, 2, 2 );
837 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
840 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
843 $h = substr( $ts, 8, 2 );
844 $num = $h %
12 ?
$h %
12 : 12;
847 $num = intval( substr( $ts, 8, 2 ) );
850 $h = substr( $ts, 8, 2 );
851 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
854 $num = substr( $ts, 8, 2 );
857 $num = substr( $ts, 10, 2 );
860 $num = substr( $ts, 12, 2 );
863 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
864 $s .= gmdate( 'c', $unix );
867 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
868 $s .= gmdate( 'r', $unix );
871 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
876 if ( $p < strlen( $format ) - 1 ) {
884 if ( $p < strlen( $format ) - 1 ) {
885 $endQuote = strpos( $format, '"', $p +
1 );
886 if ( $endQuote === false ) {
887 # No terminating quote, assume literal "
890 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
894 # Quote at end of string, assume literal "
901 if ( $num !== false ) {
902 if ( $rawToggle ||
$raw ) {
905 } elseif ( $roman ) {
906 $s .= self
::romanNumeral( $num );
908 } elseif( $hebrewNum ) {
909 $s .= self
::hebrewNumeral( $num );
912 $s .= $this->formatNum( $num, true );
920 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
921 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
923 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
924 * Gregorian dates to Iranian dates. Originally written in C, it
925 * is released under the terms of GNU Lesser General Public
926 * License. Conversion to PHP was performed by Niklas Laxström.
928 * Link: http://www.farsiweb.info/jalali/jalali.c
930 private static function tsToIranian( $ts ) {
931 $gy = substr( $ts, 0, 4 ) -1600;
932 $gm = substr( $ts, 4, 2 ) -1;
933 $gd = substr( $ts, 6, 2 ) -1;
935 # Days passed from the beginning (including leap years)
938 - floor(($gy+
99) / 100)
939 +
floor(($gy+
399) / 400);
942 // Add days of the past months of this year
943 for( $i = 0; $i < $gm; $i++
) {
944 $gDayNo +
= self
::$GREG_DAYS[$i];
948 if ( $gm > 1 && (($gy%4
===0 && $gy%100
!==0 ||
($gy%400
==0)))) {
952 // Days passed in current month
955 $jDayNo = $gDayNo - 79;
957 $jNp = floor($jDayNo / 12053);
960 $jy = 979 +
33*$jNp +
4*floor($jDayNo/1461);
963 if ( $jDayNo >= 366 ) {
964 $jy +
= floor(($jDayNo-1)/365);
965 $jDayNo = floor(($jDayNo-1)%365
);
968 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
969 $jDayNo -= self
::$IRANIAN_DAYS[$i];
975 return array($jy, $jm, $jd);
978 * Converting Gregorian dates to Hijri dates.
980 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
982 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
984 private static function tsToHijri ( $ts ) {
985 $year = substr( $ts, 0, 4 );
986 $month = substr( $ts, 4, 2 );
987 $day = substr( $ts, 6, 2 );
996 if (($zy>1582)||
(($zy==1582)&&($zm>10))||
(($zy==1582)&&($zm==10)&&($zd>14)))
1000 $zjd=(int)((1461*($zy +
4800 +
(int)( ($zm-14) /12) ))/4) +
(int)((367*($zm-2-12*((int)(($zm-14)/12))))/12)-(int)((3*(int)(( ($zy+
4900+
(int)(($zm-14)/12))/100)))/4)+
$zd-32075;
1004 $zjd = 367*$zy-(int)((7*($zy+
5001+
(int)(($zm-9)/7)))/4)+
(int)((275*$zm)/9)+
$zd+
1729777;
1007 $zl=$zjd-1948440+
10632;
1008 $zn=(int)(($zl-1)/10631);
1009 $zl=$zl-10631*$zn+
354;
1010 $zj=((int)((10985-$zl)/5316))*((int)((50*$zl)/17719))+
((int)($zl/5670))*((int)((43*$zl)/15238));
1011 $zl=$zl-((int)((30-$zj)/15))*((int)((17719*$zj)/50))-((int)($zj/16))*((int)((15238*$zj)/43))+
29;
1012 $zm=(int)((24*$zl)/709);
1013 $zd=$zl-(int)((709*$zm)/24);
1016 return array ($zy, $zm, $zd);
1020 * Converting Gregorian dates to Hebrew dates.
1022 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1023 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1024 * to translate the relevant functions into PHP and release them under
1027 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1028 * and Adar II is 14. In a non-leap year, Adar is 6.
1030 private static function tsToHebrew( $ts ) {
1032 $year = substr( $ts, 0, 4 );
1033 $month = substr( $ts, 4, 2 );
1034 $day = substr( $ts, 6, 2 );
1036 # Calculate Hebrew year
1037 $hebrewYear = $year +
3760;
1039 # Month number when September = 1, August = 12
1048 # Calculate day of year from 1 September
1050 for( $i = 1; $i < $month; $i++
) {
1054 # Check if the year is leap
1055 if( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1058 } elseif( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1065 # Calculate the start of the Hebrew year
1066 $start = self
::hebrewYearStart( $hebrewYear );
1068 # Calculate next year's start
1069 if( $dayOfYear <= $start ) {
1070 # Day is before the start of the year - it is the previous year
1072 $nextStart = $start;
1076 # Add days since previous year's 1 September
1078 if( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1082 # Start of the new (previous) year
1083 $start = self
::hebrewYearStart( $hebrewYear );
1086 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1089 # Calculate Hebrew day of year
1090 $hebrewDayOfYear = $dayOfYear - $start;
1092 # Difference between year's days
1093 $diff = $nextStart - $start;
1094 # Add 12 (or 13 for leap years) days to ignore the difference between
1095 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1096 # difference is only about the year type
1097 if( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1103 # Check the year pattern, and is leap year
1104 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1105 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1106 # and non-leap years
1107 $yearPattern = $diff %
30;
1108 # Check if leap year
1109 $isLeap = $diff >= 30;
1111 # Calculate day in the month from number of day in the Hebrew year
1112 # Don't check Adar - if the day is not in Adar, we will stop before;
1113 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1114 $hebrewDay = $hebrewDayOfYear;
1117 while( $hebrewMonth <= 12 ) {
1118 # Calculate days in this month
1119 if( $isLeap && $hebrewMonth == 6 ) {
1120 # Adar in a leap year
1122 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1124 if( $hebrewDay <= $days ) {
1128 # Subtract the days of Adar I
1129 $hebrewDay -= $days;
1132 if( $hebrewDay <= $days ) {
1138 } elseif( $hebrewMonth == 2 && $yearPattern == 2 ) {
1139 # Cheshvan in a complete year (otherwise as the rule below)
1141 } elseif( $hebrewMonth == 3 && $yearPattern == 0 ) {
1142 # Kislev in an incomplete year (otherwise as the rule below)
1145 # Odd months have 30 days, even have 29
1146 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1148 if( $hebrewDay <= $days ) {
1149 # In the current month
1152 # Subtract the days of the current month
1153 $hebrewDay -= $days;
1154 # Try in the next month
1159 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1163 * This calculates the Hebrew year start, as days since 1 September.
1164 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1165 * Used for Hebrew date.
1167 private static function hebrewYearStart( $year ) {
1168 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1169 $b = intval( ( $year - 1 ) %
4 );
1170 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1174 $Mar = intval( $m );
1180 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7);
1181 if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1183 } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1185 } else if( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1189 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1194 * Algorithm to convert Gregorian dates to Thai solar dates,
1195 * Minguo dates or Minguo dates.
1197 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1198 * http://en.wikipedia.org/wiki/Minguo_calendar
1199 * http://en.wikipedia.org/wiki/Japanese_era_name
1201 * @param $ts String: 14-character timestamp
1202 * @param $cName String: calender name
1203 * @return Array: converted year, month, day
1205 private static function tsToYear( $ts, $cName ) {
1206 $gy = substr( $ts, 0, 4 );
1207 $gm = substr( $ts, 4, 2 );
1208 $gd = substr( $ts, 6, 2 );
1210 if (!strcmp($cName,'thai')) {
1212 # Add 543 years to the Gregorian calendar
1213 # Months and days are identical
1214 $gy_offset = $gy +
543;
1215 } else if ((!strcmp($cName,'minguo')) ||
!strcmp($cName,'juche')) {
1217 # Deduct 1911 years from the Gregorian calendar
1218 # Months and days are identical
1219 $gy_offset = $gy - 1911;
1220 } else if (!strcmp($cName,'tenno')) {
1221 # Nengō dates up to Meiji period
1222 # Deduct years from the Gregorian calendar
1223 # depending on the nengo periods
1224 # Months and days are identical
1225 if (($gy < 1912) ||
(($gy == 1912) && ($gm < 7)) ||
(($gy == 1912) && ($gm == 7) && ($gd < 31))) {
1227 $gy_gannen = $gy - 1868 +
1;
1228 $gy_offset = $gy_gannen;
1229 if ($gy_gannen == 1)
1231 $gy_offset = '明治'.$gy_offset;
1232 } else if ((($gy == 1912) && ($gm == 7) && ($gd == 31)) ||
(($gy == 1912) && ($gm >= 8)) ||
(($gy > 1912) && ($gy < 1926)) ||
(($gy == 1926) && ($gm < 12)) ||
(($gy == 1926) && ($gm == 12) && ($gd < 26))) {
1234 $gy_gannen = $gy - 1912 +
1;
1235 $gy_offset = $gy_gannen;
1236 if ($gy_gannen == 1)
1238 $gy_offset = '大正'.$gy_offset;
1239 } else if ((($gy == 1926) && ($gm == 12) && ($gd >= 26)) ||
(($gy > 1926) && ($gy < 1989)) ||
(($gy == 1989) && ($gm == 1) && ($gd < 8))) {
1241 $gy_gannen = $gy - 1926 +
1;
1242 $gy_offset = $gy_gannen;
1243 if ($gy_gannen == 1)
1245 $gy_offset = '昭和'.$gy_offset;
1248 $gy_gannen = $gy - 1989 +
1;
1249 $gy_offset = $gy_gannen;
1250 if ($gy_gannen == 1)
1252 $gy_offset = '平成'.$gy_offset;
1258 return array( $gy_offset, $gm, $gd );
1262 * Roman number formatting up to 3000
1264 static function romanNumeral( $num ) {
1265 static $table = array(
1266 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1267 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1268 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1269 array( '', 'M', 'MM', 'MMM' )
1272 $num = intval( $num );
1273 if ( $num > 3000 ||
$num <= 0 ) {
1278 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1279 if ( $num >= $pow10 ) {
1280 $s .= $table[$i][floor($num / $pow10)];
1282 $num = $num %
$pow10;
1288 * Hebrew Gematria number formatting up to 9999
1290 static function hebrewNumeral( $num ) {
1291 static $table = array(
1292 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1293 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1294 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1295 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1298 $num = intval( $num );
1299 if ( $num > 9999 ||
$num <= 0 ) {
1304 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1305 if ( $num >= $pow10 ) {
1306 if ( $num == 15 ||
$num == 16 ) {
1307 $s .= $table[0][9] . $table[0][$num - 9];
1310 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1311 if( $pow10 == 1000 ) {
1316 $num = $num %
$pow10;
1318 if( strlen( $s ) == 2 ) {
1321 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1322 $str .= substr( $s, strlen( $s ) - 2, 2 );
1324 $start = substr( $str, 0, strlen( $str ) - 2 );
1325 $end = substr( $str, strlen( $str ) - 2 );
1328 $str = $start . 'ך';
1331 $str = $start . 'ם';
1334 $str = $start . 'ן';
1337 $str = $start . 'ף';
1340 $str = $start . 'ץ';
1347 * This is meant to be used by time(), date(), and timeanddate() to get
1348 * the date preference they're supposed to use, it should be used in
1352 * function timeanddate([...], $format = true) {
1353 * $datePreference = $this->dateFormat($format);
1358 * @param $usePrefs Mixed: if true, the user's preference is used
1359 * if false, the site/language default is used
1360 * if int/string, assumed to be a format.
1363 function dateFormat( $usePrefs = true ) {
1366 if( is_bool( $usePrefs ) ) {
1368 $datePreference = $wgUser->getDatePreference();
1370 $datePreference = (string)User
::getDefaultOption( 'date' );
1373 $datePreference = (string)$usePrefs;
1377 if( $datePreference == '' ) {
1381 return $datePreference;
1385 * Get a format string for a given type and preference
1386 * @param $type May be date, time or both
1387 * @param $pref The format name as it appears in Messages*.php
1389 function getDateFormatString( $type, $pref ) {
1390 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1391 if ( $pref == 'default' ) {
1392 $pref = $this->getDefaultDateFormat();
1393 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1395 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1396 if ( is_null( $df ) ) {
1397 $pref = $this->getDefaultDateFormat();
1398 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1401 $this->dateFormatStrings
[$type][$pref] = $df;
1403 return $this->dateFormatStrings
[$type][$pref];
1407 * @param $ts Mixed: the time format which needs to be turned into a
1408 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1409 * @param $adj Bool: whether to adjust the time output according to the
1410 * user configured offset ($timecorrection)
1411 * @param $format Mixed: true to use user's date format preference
1412 * @param $timecorrection String: the time offset as returned by
1413 * validateTimeZone() in Special:Preferences
1416 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1418 $ts = $this->userAdjust( $ts, $timecorrection );
1420 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1421 return $this->sprintfDate( $df, $ts );
1425 * @param $ts Mixed: the time format which needs to be turned into a
1426 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1427 * @param $adj Bool: whether to adjust the time output according to the
1428 * user configured offset ($timecorrection)
1429 * @param $format Mixed: true to use user's date format preference
1430 * @param $timecorrection String: the time offset as returned by
1431 * validateTimeZone() in Special:Preferences
1434 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1436 $ts = $this->userAdjust( $ts, $timecorrection );
1438 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1439 return $this->sprintfDate( $df, $ts );
1443 * @param $ts Mixed: the time format which needs to be turned into a
1444 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1445 * @param $adj Bool: whether to adjust the time output according to the
1446 * user configured offset ($timecorrection)
1447 * @param $format Mixed: what format to return, if it's false output the
1448 * default one (default true)
1449 * @param $timecorrection String: the time offset as returned by
1450 * validateTimeZone() in Special:Preferences
1453 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
1454 $ts = wfTimestamp( TS_MW
, $ts );
1456 $ts = $this->userAdjust( $ts, $timecorrection );
1458 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1459 return $this->sprintfDate( $df, $ts );
1462 function getMessage( $key ) {
1463 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1466 function getAllMessages() {
1467 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1470 function iconv( $in, $out, $string ) {
1471 # This is a wrapper for iconv in all languages except esperanto,
1472 # which does some nasty x-conversions beforehand
1474 # Even with //IGNORE iconv can whine about illegal characters in
1475 # *input* string. We just ignore those too.
1476 # REF: http://bugs.php.net/bug.php?id=37166
1477 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1478 wfSuppressWarnings();
1479 $text = iconv( $in, $out . '//IGNORE', $string );
1480 wfRestoreWarnings();
1484 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1485 function ucwordbreaksCallbackAscii($matches){
1486 return $this->ucfirst($matches[1]);
1489 function ucwordbreaksCallbackMB($matches){
1490 return mb_strtoupper($matches[0]);
1493 function ucCallback($matches){
1494 list( $wikiUpperChars ) = self
::getCaseMaps();
1495 return strtr( $matches[1], $wikiUpperChars );
1498 function lcCallback($matches){
1499 list( , $wikiLowerChars ) = self
::getCaseMaps();
1500 return strtr( $matches[1], $wikiLowerChars );
1503 function ucwordsCallbackMB($matches){
1504 return mb_strtoupper($matches[0]);
1507 function ucwordsCallbackWiki($matches){
1508 list( $wikiUpperChars ) = self
::getCaseMaps();
1509 return strtr( $matches[0], $wikiUpperChars );
1512 function ucfirst( $str ) {
1516 } elseif ( $o < 128 ) {
1517 return ucfirst($str);
1519 // fall back to more complex logic in case of multibyte strings
1520 return self
::uc($str,true);
1524 function uc( $str, $first = false ) {
1525 if ( function_exists( 'mb_strtoupper' ) ) {
1527 if ( self
::isMultibyte( $str ) ) {
1528 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1530 return ucfirst( $str );
1533 return self
::isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1536 if ( self
::isMultibyte( $str ) ) {
1537 list( $wikiUpperChars ) = $this->getCaseMaps();
1538 $x = $first ?
'^' : '';
1539 return preg_replace_callback(
1540 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1541 array($this,"ucCallback"),
1545 return $first ?
ucfirst( $str ) : strtoupper( $str );
1550 function lcfirst( $str ) {
1553 return strval( $str );
1554 } elseif ( $o >= 128 ) {
1555 return self
::lc( $str, true );
1556 } elseif ( $o > 96 ) {
1559 $str[0] = strtolower( $str[0] );
1564 function lc( $str, $first = false ) {
1565 if ( function_exists( 'mb_strtolower' ) )
1567 if ( self
::isMultibyte( $str ) )
1568 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1570 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1572 return self
::isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1574 if ( self
::isMultibyte( $str ) ) {
1575 list( , $wikiLowerChars ) = self
::getCaseMaps();
1576 $x = $first ?
'^' : '';
1577 return preg_replace_callback(
1578 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1579 array($this,"lcCallback"),
1583 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1586 function isMultibyte( $str ) {
1587 return (bool)preg_match( '/[\x80-\xff]/', $str );
1590 function ucwords($str) {
1591 if ( self
::isMultibyte( $str ) ) {
1592 $str = self
::lc($str);
1594 // regexp to find first letter in each word (i.e. after each space)
1595 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1597 // function to use to capitalize a single char
1598 if ( function_exists( 'mb_strtoupper' ) )
1599 return preg_replace_callback(
1601 array($this,"ucwordsCallbackMB"),
1605 return preg_replace_callback(
1607 array($this,"ucwordsCallbackWiki"),
1612 return ucwords( strtolower( $str ) );
1615 # capitalize words at word breaks
1616 function ucwordbreaks($str){
1617 if (self
::isMultibyte( $str ) ) {
1618 $str = self
::lc($str);
1620 // since \b doesn't work for UTF-8, we explicitely define word break chars
1621 $breaks= "[ \-\(\)\}\{\.,\?!]";
1623 // find first letter after word break
1624 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1626 if ( function_exists( 'mb_strtoupper' ) )
1627 return preg_replace_callback(
1629 array($this,"ucwordbreaksCallbackMB"),
1633 return preg_replace_callback(
1635 array($this,"ucwordsCallbackWiki"),
1640 return preg_replace_callback(
1641 '/\b([\w\x80-\xff]+)\b/',
1642 array($this,"ucwordbreaksCallbackAscii"),
1647 * Return a case-folded representation of $s
1649 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1650 * and $s2 are the same except for the case of their characters. It is not
1651 * necessary for the value returned to make sense when displayed.
1653 * Do *not* perform any other normalisation in this function. If a caller
1654 * uses this function when it should be using a more general normalisation
1655 * function, then fix the caller.
1657 function caseFold( $s ) {
1658 return $this->uc( $s );
1661 function checkTitleEncoding( $s ) {
1662 if( is_array( $s ) ) {
1663 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1665 # Check for non-UTF-8 URLs
1666 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1667 if(!$ishigh) return $s;
1669 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1670 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1671 if( $isutf8 ) return $s;
1673 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
1676 function fallback8bitEncoding() {
1677 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1681 * Most writing systems use whitespace to break up words.
1682 * Some languages such as Chinese don't conventionally do this,
1683 * which requires special handling when breaking up words for
1686 function hasWordBreaks() {
1691 * Some languages such as Chinese require word segmentation,
1692 * Specify such segmentation when overridden in derived class.
1694 * @param $string String
1697 function segmentByWord( $string ) {
1702 * Some languages have special punctuation need to be normalized.
1703 * Make such changes here.
1705 * @param $string String
1708 function normalizeForSearch( $string ) {
1709 return self
::convertDoubleWidth($string);
1713 * convert double-width roman characters to single-width.
1714 * range: ff00-ff5f ~= 0020-007f
1716 protected static function convertDoubleWidth( $string ) {
1717 static $full = null;
1718 static $half = null;
1720 if( $full === null ) {
1721 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1722 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1723 $full = str_split( $fullWidth, 3 );
1724 $half = str_split( $halfWidth );
1727 $string = str_replace( $full, $half, $string );
1731 protected static function insertSpace( $string, $pattern ) {
1732 $string = preg_replace( $pattern, " $1 ", $string );
1733 $string = preg_replace( '/ +/', ' ', $string );
1737 function convertForSearchResult( $termsArray ) {
1738 # some languages, e.g. Chinese, need to do a conversion
1739 # in order for search results to be displayed correctly
1744 * Get the first character of a string.
1749 function firstChar( $s ) {
1751 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1752 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
1754 if ( isset( $matches[1] ) ) {
1755 if ( strlen( $matches[1] ) != 3 ) {
1759 // Break down Hangul syllables to grab the first jamo
1760 $code = utf8ToCodepoint( $matches[1] );
1761 if ( $code < 0xac00 ||
0xd7a4 <= $code) {
1763 } elseif ( $code < 0xb098 ) {
1764 return "\xe3\x84\xb1";
1765 } elseif ( $code < 0xb2e4 ) {
1766 return "\xe3\x84\xb4";
1767 } elseif ( $code < 0xb77c ) {
1768 return "\xe3\x84\xb7";
1769 } elseif ( $code < 0xb9c8 ) {
1770 return "\xe3\x84\xb9";
1771 } elseif ( $code < 0xbc14 ) {
1772 return "\xe3\x85\x81";
1773 } elseif ( $code < 0xc0ac ) {
1774 return "\xe3\x85\x82";
1775 } elseif ( $code < 0xc544 ) {
1776 return "\xe3\x85\x85";
1777 } elseif ( $code < 0xc790 ) {
1778 return "\xe3\x85\x87";
1779 } elseif ( $code < 0xcc28 ) {
1780 return "\xe3\x85\x88";
1781 } elseif ( $code < 0xce74 ) {
1782 return "\xe3\x85\x8a";
1783 } elseif ( $code < 0xd0c0 ) {
1784 return "\xe3\x85\x8b";
1785 } elseif ( $code < 0xd30c ) {
1786 return "\xe3\x85\x8c";
1787 } elseif ( $code < 0xd558 ) {
1788 return "\xe3\x85\x8d";
1790 return "\xe3\x85\x8e";
1797 function initEncoding() {
1798 # Some languages may have an alternate char encoding option
1799 # (Esperanto X-coding, Japanese furigana conversion, etc)
1800 # If this language is used as the primary content language,
1801 # an override to the defaults can be set here on startup.
1804 function recodeForEdit( $s ) {
1805 # For some languages we'll want to explicitly specify
1806 # which characters make it into the edit box raw
1807 # or are converted in some way or another.
1808 # Note that if wgOutputEncoding is different from
1809 # wgInputEncoding, this text will be further converted
1810 # to wgOutputEncoding.
1811 global $wgEditEncoding;
1812 if( $wgEditEncoding == '' or
1813 $wgEditEncoding == 'UTF-8' ) {
1816 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1820 function recodeInput( $s ) {
1821 # Take the previous into account.
1822 global $wgEditEncoding;
1823 if($wgEditEncoding != "") {
1824 $enc = $wgEditEncoding;
1828 if( $enc == 'UTF-8' ) {
1831 return $this->iconv( $enc, 'UTF-8', $s );
1836 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1837 * also cleans up certain backwards-compatible sequences, converting them
1838 * to the modern Unicode equivalent.
1840 * This is language-specific for performance reasons only.
1842 function normalize( $s ) {
1843 return UtfNormal
::cleanUp( $s );
1847 * Transform a string using serialized data stored in the given file (which
1848 * must be in the serialized subdirectory of $IP). The file contains pairs
1849 * mapping source characters to destination characters.
1851 * The data is cached in process memory. This will go faster if you have the
1852 * FastStringSearch extension.
1854 function transformUsingPairFile( $file, $string ) {
1855 if ( !isset( $this->transformData
[$file] ) ) {
1856 $data = wfGetPrecompiledData( $file );
1857 if ( $data === false ) {
1858 throw new MWException( __METHOD__
.": The transformation file $file is missing" );
1860 $this->transformData
[$file] = new ReplacementArray( $data );
1862 return $this->transformData
[$file]->replace( $string );
1866 * For right-to-left language support
1871 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1875 * Return the correct HTML 'dir' attribute value for this language.
1879 return $this->isRTL() ?
'rtl' : 'ltr';
1883 * Return 'left' or 'right' as appropriate alignment for line-start
1884 * for this language's text direction.
1886 * Should be equivalent to CSS3 'start' text-align value....
1890 function alignStart() {
1891 return $this->isRTL() ?
'right' : 'left';
1895 * Return 'right' or 'left' as appropriate alignment for line-end
1896 * for this language's text direction.
1898 * Should be equivalent to CSS3 'end' text-align value....
1902 function alignEnd() {
1903 return $this->isRTL() ?
'left' : 'right';
1907 * A hidden direction mark (LRM or RLM), depending on the language direction
1911 function getDirMark() {
1912 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
1915 function capitalizeAllNouns() {
1916 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
1920 * An arrow, depending on the language direction
1924 function getArrow() {
1925 return $this->isRTL() ?
'←' : '→';
1929 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
1933 function linkPrefixExtension() {
1934 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
1937 function getMagicWords() {
1938 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
1941 # Fill a MagicWord object with data from here
1942 function getMagic( $mw ) {
1943 if ( !$this->mMagicHookDone
) {
1944 $this->mMagicHookDone
= true;
1945 wfProfileIn( 'LanguageGetMagic' );
1946 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
1947 wfProfileOut( 'LanguageGetMagic' );
1949 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
1950 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
1952 $magicWords = $this->getMagicWords();
1953 if ( isset( $magicWords[$mw->mId
] ) ) {
1954 $rawEntry = $magicWords[$mw->mId
];
1960 if( !is_array( $rawEntry ) ) {
1961 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
1963 $mw->mCaseSensitive
= $rawEntry[0];
1964 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
1969 * Add magic words to the extension array
1971 function addMagicWordsByLang( $newWords ) {
1972 $code = $this->getCode();
1973 $fallbackChain = array();
1974 while ( $code && !in_array( $code, $fallbackChain ) ) {
1975 $fallbackChain[] = $code;
1976 $code = self
::getFallbackFor( $code );
1978 if ( !in_array( 'en', $fallbackChain ) ) {
1979 $fallbackChain[] = 'en';
1981 $fallbackChain = array_reverse( $fallbackChain );
1982 foreach ( $fallbackChain as $code ) {
1983 if ( isset( $newWords[$code] ) ) {
1984 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
1990 * Get special page names, as an associative array
1991 * case folded alias => real name
1993 function getSpecialPageAliases() {
1994 // Cache aliases because it may be slow to load them
1995 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
1997 $this->mExtendedSpecialPageAliases
=
1998 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
1999 wfRunHooks( 'LanguageGetSpecialPageAliases',
2000 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2003 return $this->mExtendedSpecialPageAliases
;
2007 * Italic is unsuitable for some languages
2009 * @param $text String: the text to be emphasized.
2012 function emphasize( $text ) {
2013 return "<em>$text</em>";
2017 * Normally we output all numbers in plain en_US style, that is
2018 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2019 * point twohundredthirtyfive. However this is not sutable for all
2020 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2021 * Icelandic just want to use commas instead of dots, and dots instead
2022 * of commas like "293.291,235".
2024 * An example of this function being called:
2026 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2029 * See LanguageGu.php for the Gujarati implementation and
2030 * $separatorTransformTable on MessageIs.php for
2031 * the , => . and . => , implementation.
2033 * @todo check if it's viable to use localeconv() for the decimal
2035 * @param $number Mixed: the string to be formatted, should be an integer
2036 * or a floating point number.
2037 * @param $nocommafy Bool: set to true for special numbers like dates
2040 function formatNum( $number, $nocommafy = false ) {
2041 global $wgTranslateNumerals;
2043 $number = $this->commafy($number);
2044 $s = $this->separatorTransformTable();
2045 if ($s) { $number = strtr($number, $s); }
2048 if ($wgTranslateNumerals) {
2049 $s = $this->digitTransformTable();
2050 if ($s) { $number = strtr($number, $s); }
2056 function parseFormattedNumber( $number ) {
2057 $s = $this->digitTransformTable();
2058 if ($s) { $number = strtr($number, array_flip($s)); }
2060 $s = $this->separatorTransformTable();
2061 if ($s) { $number = strtr($number, array_flip($s)); }
2063 $number = strtr( $number, array (',' => '') );
2068 * Adds commas to a given number
2073 function commafy($_) {
2074 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
2077 function digitTransformTable() {
2078 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2081 function separatorTransformTable() {
2082 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2087 * Take a list of strings and build a locale-friendly comma-separated
2088 * list, using the local comma-separator message.
2089 * The last two strings are chained with an "and".
2094 function listToText( $l ) {
2096 $m = count( $l ) - 1;
2098 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2101 for ( $i = $m; $i >= 0; $i-- ) {
2104 } else if( $i == $m - 1 ) {
2105 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2107 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2115 * Take a list of strings and build a locale-friendly comma-separated
2116 * list, using the local comma-separator message.
2117 * @param $list array of strings to put in a comma list
2120 function commaList( $list ) {
2123 wfMsgExt( 'comma-separator', array( 'parsemag', 'escapenoentities', 'language' => $this ) ) );
2127 * Take a list of strings and build a locale-friendly semicolon-separated
2128 * list, using the local semicolon-separator message.
2129 * @param $list array of strings to put in a semicolon list
2132 function semicolonList( $list ) {
2135 wfMsgExt( 'semicolon-separator', array( 'parsemag', 'escapenoentities', 'language' => $this ) ) );
2139 * Same as commaList, but separate it with the pipe instead.
2140 * @param $list array of strings to put in a pipe list
2143 function pipeList( $list ) {
2146 wfMsgExt( 'pipe-separator', array( 'escapenoentities', 'language' => $this ) ) );
2150 * Truncate a string to a specified length in bytes, appending an optional
2151 * string (e.g. for ellipses)
2153 * The database offers limited byte lengths for some columns in the database;
2154 * multi-byte character sets mean we need to ensure that only whole characters
2155 * are included, otherwise broken characters can be passed to the user
2157 * If $length is negative, the string will be truncated from the beginning
2159 * @param $string String to truncate
2160 * @param $length Int: maximum length (excluding ellipses)
2161 * @param $ellipsis String to append to the truncated text
2164 function truncate( $string, $length, $ellipsis = '...' ) {
2165 # Use the localized ellipsis character
2166 if ( $ellipsis == '...' ) {
2167 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2169 # Check if there is no need to truncate
2170 if ( $length == 0 ) {
2172 } elseif ( strlen( $string ) <= abs( $length ) ) {
2175 $stringOriginal = $string;
2176 if ( $length > 0 ) {
2177 $string = substr( $string, 0, $length ); // xyz...
2178 $string = $this->removeBadCharLast( $string );
2179 $string = $string . $ellipsis;
2181 $string = substr( $string, $length ); // ...xyz
2182 $string = $this->removeBadCharFirst( $string );
2183 $string = $ellipsis . $string;
2185 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2186 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2189 return $stringOriginal;
2194 * Remove bytes that represent an incomplete Unicode character
2195 * at the end of string (e.g. bytes of the char are missing)
2197 * @param $string String
2200 protected function removeBadCharLast( $string ) {
2201 $char = ord( $string[strlen( $string ) - 1] );
2203 if ( $char >= 0xc0 ) {
2204 # We got the first byte only of a multibyte char; remove it.
2205 $string = substr( $string, 0, -1 );
2206 } elseif ( $char >= 0x80 &&
2207 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2208 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2210 # We chopped in the middle of a character; remove it
2217 * Remove bytes that represent an incomplete Unicode character
2218 * at the start of string (e.g. bytes of the char are missing)
2220 * @param $string String
2223 protected function removeBadCharFirst( $string ) {
2224 $char = ord( $string[0] );
2225 if ( $char >= 0x80 && $char < 0xc0 ) {
2226 # We chopped in the middle of a character; remove the whole thing
2227 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2233 * Truncate a string of valid HTML to a specified length in bytes,
2234 * appending an optional string (e.g. for ellipses), and return valid HTML
2236 * This is only intended for styled/linked text, such as HTML with
2237 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2239 * Note: tries to fix broken HTML with MWTidy
2241 * @param string $text String to truncate
2242 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2243 * @param string $ellipsis String to append to the truncated text
2246 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2247 # Use the localized ellipsis character
2248 if ( $ellipsis == '...' ) {
2249 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2251 # Check if there is no need to truncate
2252 if ( $length <= 0 ) {
2253 return $ellipsis; // no text shown, nothing to format
2254 } elseif ( strlen($text) <= $length ) {
2255 return $text; // string short enough even *with* HTML
2257 $text = MWTidy
::tidy( $text ); // fix tags
2258 $displayLen = 0; // innerHTML legth so far
2259 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2260 $tagType = 0; // 0-open, 1-close
2261 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2262 $entityState = 0; // 0-not entity, 1-entity
2263 $tag = $ret = $ch = '';
2264 $openTags = array();
2265 $textLen = strlen($text);
2266 for( $pos = 0; $pos < $textLen; ++
$pos ) {
2268 $lastCh = $pos ?
$text[$pos-1] : '';
2269 $ret .= $ch; // add to result string
2271 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2272 $entityState = 0; // for bad HTML
2273 $bracketState = 1; // tag started (checking for backslash)
2274 } elseif ( $ch == '>' ) {
2275 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2276 $entityState = 0; // for bad HTML
2277 $bracketState = 0; // out of brackets
2278 } elseif ( $bracketState == 1 ) {
2280 $tagType = 1; // close tag (e.g. "</span>")
2282 $tagType = 0; // open tag (e.g. "<span>")
2285 $bracketState = 2; // building tag name
2286 } elseif ( $bracketState == 2 ) {
2290 // Name found (e.g. "<a href=..."), add on tag attributes...
2291 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2293 } elseif ( $bracketState == 0 ) {
2294 if ( $entityState ) {
2297 $displayLen++
; // entity is one displayed char
2301 $entityState = 1; // entity found, (e.g. " ")
2303 $displayLen++
; // this char is displayed
2304 // Add on the other display text after this...
2305 $skipped = $this->truncate_skip(
2306 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2307 $displayLen +
= $skipped;
2312 # Consider truncation once the display length has reached the maximim.
2313 # Double-check that we're not in the middle of a bracket/entity...
2314 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2315 if ( !$testingEllipsis ) {
2316 $testingEllipsis = true;
2317 # Save where we are; we will truncate here unless
2318 # the ellipsis actually makes the string longer.
2319 $pOpenTags = $openTags; // save state
2320 $pRet = $ret; // save state
2321 } elseif ( $displayLen > ($length +
strlen($ellipsis)) ) {
2322 # Ellipsis won't make string longer/equal, the truncation point was OK.
2323 $openTags = $pOpenTags; // reload state
2324 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2325 $ret .= $ellipsis; // add ellipsis
2330 if ( $displayLen == 0 ) {
2331 return ''; // no text shown, nothing to format
2333 $this->truncate_endBracket( $tag, $text[$textLen-1], $tagType, $openTags ); // for bad HTML
2334 while ( count( $openTags ) > 0 ) {
2335 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2340 // truncateHtml() helper function
2341 // like strcspn() but adds the skipped chars to $ret
2342 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2344 if( $start < strlen($text) ) {
2345 $skipCount = strcspn( $text, $search, $start, $len );
2346 $ret .= substr( $text, $start, $skipCount );
2351 // truncateHtml() helper function
2352 // (a) push or pop $tag from $openTags as needed
2353 // (b) clear $tag value
2354 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2355 $tag = ltrim( $tag );
2357 if( $tagType == 0 && $lastCh != '/' ) {
2358 $openTags[] = $tag; // tag opened (didn't close itself)
2359 } else if( $tagType == 1 ) {
2360 if( $openTags && $tag == $openTags[count($openTags)-1] ) {
2361 array_pop( $openTags ); // tag closed
2369 * Grammatical transformations, needed for inflected languages
2370 * Invoked by putting {{grammar:case|word}} in a message
2372 * @param $word string
2373 * @param $case string
2376 function convertGrammar( $word, $case ) {
2377 global $wgGrammarForms;
2378 if ( isset($wgGrammarForms[$this->getCode()][$case][$word]) ) {
2379 return $wgGrammarForms[$this->getCode()][$case][$word];
2385 * Provides an alternative text depending on specified gender.
2386 * Usage {{gender:username|masculine|feminine|neutral}}.
2387 * username is optional, in which case the gender of current user is used,
2388 * but only in (some) interface messages; otherwise default gender is used.
2389 * If second or third parameter are not specified, masculine is used.
2390 * These details may be overriden per language.
2392 function gender( $gender, $forms ) {
2393 if ( !count($forms) ) { return ''; }
2394 $forms = $this->preConvertPlural( $forms, 2 );
2395 if ( $gender === 'male' ) return $forms[0];
2396 if ( $gender === 'female' ) return $forms[1];
2397 return isset($forms[2]) ?
$forms[2] : $forms[0];
2401 * Plural form transformations, needed for some languages.
2402 * For example, there are 3 form of plural in Russian and Polish,
2403 * depending on "count mod 10". See [[w:Plural]]
2404 * For English it is pretty simple.
2406 * Invoked by putting {{plural:count|wordform1|wordform2}}
2407 * or {{plural:count|wordform1|wordform2|wordform3}}
2409 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2411 * @param $count Integer: non-localized number
2412 * @param $forms Array: different plural forms
2413 * @return string Correct form of plural for $count in this language
2415 function convertPlural( $count, $forms ) {
2416 if ( !count($forms) ) { return ''; }
2417 $forms = $this->preConvertPlural( $forms, 2 );
2419 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2423 * Checks that convertPlural was given an array and pads it to requested
2424 * amound of forms by copying the last one.
2426 * @param $count Integer: How many forms should there be at least
2427 * @param $forms Array of forms given to convertPlural
2428 * @return array Padded array of forms or an exception if not an array
2430 protected function preConvertPlural( /* Array */ $forms, $count ) {
2431 while ( count($forms) < $count ) {
2432 $forms[] = $forms[count($forms)-1];
2438 * For translaing of expiry times
2439 * @param $str String: the validated block time in English
2440 * @return Somehow translated block time
2441 * @see LanguageFi.php for example implementation
2443 function translateBlockExpiry( $str ) {
2445 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2447 if ( $scBlockExpiryOptions == '-') {
2451 foreach (explode(',', $scBlockExpiryOptions) as $option) {
2452 if ( strpos($option, ":") === false )
2454 list($show, $value) = explode(":", $option);
2455 if ( strcmp ( $str, $value) == 0 ) {
2456 return htmlspecialchars( trim( $show ) );
2464 * languages like Chinese need to be segmented in order for the diff
2467 * @param $text String
2470 function segmentForDiff( $text ) {
2475 * and unsegment to show the result
2477 * @param $text String
2480 function unsegmentForDiff( $text ) {
2484 # convert text to all supported variants
2485 function autoConvertToAllVariants($text) {
2486 return $this->mConverter
->autoConvertToAllVariants($text);
2489 # convert text to different variants of a language.
2490 function convert( $text, $isTitle = false) {
2491 return $this->mConverter
->convert($text, $isTitle);
2494 # Check if this is a language with variants
2495 function hasVariants(){
2496 return sizeof($this->getVariants())>1;
2499 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2500 function armourMath($text){
2501 return $this->mConverter
->armourMath($text);
2506 * Perform output conversion on a string, and encode for safe HTML output.
2507 * @param $text String text to be converted
2508 * @param $isTitle Bool whether this conversion is for the article title
2510 * @todo this should get integrated somewhere sane
2512 function convertHtml( $text, $isTitle = false ) {
2513 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2516 function convertCategoryKey( $key ) {
2517 return $this->mConverter
->convertCategoryKey( $key );
2521 * get the list of variants supported by this langauge
2522 * see sample implementation in LanguageZh.php
2524 * @return array an array of language codes
2526 function getVariants() {
2527 return $this->mConverter
->getVariants();
2531 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2532 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2536 * if a language supports multiple variants, it is
2537 * possible that non-existing link in one variant
2538 * actually exists in another variant. this function
2539 * tries to find it. See e.g. LanguageZh.php
2541 * @param $link String: the name of the link
2542 * @param $nt Mixed: the title object of the link
2543 * @param $ignoreOtherCond Boolean: to disable other conditions when
2544 * we need to transclude a template or update a category's link
2545 * @return null the input parameters may be modified upon return
2547 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2548 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2552 * If a language supports multiple variants, converts text
2553 * into an array of all possible variants of the text:
2554 * 'variant' => text in that variant
2556 function convertLinkToAllVariants($text){
2557 return $this->mConverter
->convertLinkToAllVariants($text);
2562 * returns language specific options used by User::getPageRenderHash()
2563 * for example, the preferred language variant
2567 function getExtraHashOptions() {
2568 return $this->mConverter
->getExtraHashOptions();
2572 * for languages that support multiple variants, the title of an
2573 * article may be displayed differently in different variants. this
2574 * function returns the apporiate title defined in the body of the article.
2578 function getParsedTitle() {
2579 return $this->mConverter
->getParsedTitle();
2583 * Enclose a string with the "no conversion" tag. This is used by
2584 * various functions in the Parser
2586 * @param $text String: text to be tagged for no conversion
2588 * @return string the tagged text
2590 function markNoConversion( $text, $noParse=false ) {
2591 return $this->mConverter
->markNoConversion( $text, $noParse );
2595 * A regular expression to match legal word-trailing characters
2596 * which should be merged onto a link of the form [[foo]]bar.
2600 function linkTrail() {
2601 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2604 function getLangObj() {
2609 * Get the RFC 3066 code for this language object
2611 function getCode() {
2612 return $this->mCode
;
2615 function setCode( $code ) {
2616 $this->mCode
= $code;
2620 * Get the name of a file for a certain language code
2621 * @param $prefix string Prepend this to the filename
2622 * @param $code string Language code
2623 * @param $suffix string Append this to the filename
2624 * @return string $prefix . $mangledCode . $suffix
2626 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2627 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2631 * Get the language code from a file name. Inverse of getFileName()
2632 * @param $filename string $prefix . $languageCode . $suffix
2633 * @param $prefix string Prefix before the language code
2634 * @param $suffix string Suffix after the language code
2635 * @return Language code, or false if $prefix or $suffix isn't found
2637 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2639 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2640 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2641 if ( !count( $m ) ) {
2644 return str_replace( '_', '-', strtolower( $m[1] ) );
2647 static function getMessagesFileName( $code ) {
2649 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2652 static function getClassFileName( $code ) {
2654 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2658 * Get the fallback for a given language
2660 static function getFallbackFor( $code ) {
2661 if ( $code === 'en' ) {
2665 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2670 * Get all messages for a given language
2671 * WARNING: this may take a long time
2673 static function getMessagesFor( $code ) {
2674 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2678 * Get a message for a given language
2680 static function getMessageFor( $key, $code ) {
2681 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2684 function fixVariableInNamespace( $talk ) {
2685 if ( strpos( $talk, '$1' ) === false ) return $talk;
2687 global $wgMetaNamespace;
2688 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2690 # Allow grammar transformations
2691 # Allowing full message-style parsing would make simple requests
2692 # such as action=raw much more expensive than they need to be.
2693 # This will hopefully cover most cases.
2694 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2695 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2696 return str_replace( ' ', '_', $talk );
2699 function replaceGrammarInNamespace( $m ) {
2700 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2703 static function getCaseMaps() {
2704 static $wikiUpperChars, $wikiLowerChars;
2705 if ( isset( $wikiUpperChars ) ) {
2706 return array( $wikiUpperChars, $wikiLowerChars );
2709 wfProfileIn( __METHOD__
);
2710 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2711 if ( $arr === false ) {
2712 throw new MWException(
2713 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2716 wfProfileOut( __METHOD__
);
2717 return array( $wikiUpperChars, $wikiLowerChars );
2720 function formatTimePeriod( $seconds ) {
2721 if ( $seconds < 10 ) {
2722 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . ' ' . wfMsg( 'seconds-abbrev' );
2723 } elseif ( $seconds < 60 ) {
2724 return $this->formatNum( round( $seconds ) ) . ' ' . wfMsg( 'seconds-abbrev' );
2725 } elseif ( $seconds < 3600 ) {
2726 return $this->formatNum( floor( $seconds / 60 ) ) . ' ' . wfMsg( 'minutes-abbrev' ) . ' ' .
2727 $this->formatNum( round( fmod( $seconds, 60 ) ) ) . ' ' . wfMsg( 'seconds-abbrev' );
2729 $hours = floor( $seconds / 3600 );
2730 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2731 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2732 return $this->formatNum( $hours ) . ' ' . wfMsg( 'hours-abbrev' ) . ' ' .
2733 $this->formatNum( $minutes ) . ' ' . wfMsg( 'minutes-abbrev' ) . ' ' .
2734 $this->formatNum( $secondsPart ) . ' ' . wfMsg( 'seconds-abbrev' );
2738 function formatBitrate( $bps ) {
2739 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2741 return $this->formatNum( $bps ) . $units[0];
2743 $unitIndex = floor( log10( $bps ) / 3 );
2744 $mantissa = $bps / pow( 1000, $unitIndex );
2745 if ( $mantissa < 10 ) {
2746 $mantissa = round( $mantissa, 1 );
2748 $mantissa = round( $mantissa );
2750 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2754 * Format a size in bytes for output, using an appropriate
2755 * unit (B, KB, MB or GB) according to the magnitude in question
2757 * @param $size Size to format
2758 * @return string Plain text (not HTML)
2760 function formatSize( $size ) {
2761 // For small sizes no decimal places necessary
2763 if( $size > 1024 ) {
2764 $size = $size / 1024;
2765 if( $size > 1024 ) {
2766 $size = $size / 1024;
2767 // For MB and bigger two decimal places are smarter
2769 if( $size > 1024 ) {
2770 $size = $size / 1024;
2771 $msg = 'size-gigabytes';
2773 $msg = 'size-megabytes';
2776 $msg = 'size-kilobytes';
2779 $msg = 'size-bytes';
2781 $size = round( $size, $round );
2782 $text = $this->getMessageFromDB( $msg );
2783 return str_replace( '$1', $this->formatNum( $size ), $text );
2787 * Get the conversion rule title, if any.
2789 function getConvRuleTitle() {
2790 return $this->mConverter
->getConvRuleTitle();