3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 global $wgInputEncoding, $wgOutputEncoding;
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
35 * a fake language converter
41 function __construct( $langobj ) { $this->mLang
= $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang
->getCode() ); }
46 function getPreferredVariant() { return $this->mLang
->getCode(); }
47 function getConvRuleTitle() { return false; }
48 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
49 function getExtraHashOptions() { return ''; }
50 function getParsedTitle() { return ''; }
51 function markNoConversion( $text, $noParse = false ) { return $text; }
52 function convertCategoryKey( $key ) { return $key; }
53 function convertLinkToAllVariants( $text ) { return autoConvertToAllVariants( $text ); }
54 function armourMath( $text ) { return $text; }
58 * Internationalisation code
62 var $mConverter, $mVariants, $mCode, $mLoaded = false;
63 var $mMagicExtensions = array(), $mMagicHookDone = false;
65 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
66 var $dateFormatStrings = array();
67 var $mExtendedSpecialPageAliases;
70 * ReplacementArray object caches
72 var $transformData = array();
74 static public $dataCache;
75 static public $mLangObjCache = array();
77 static public $mWeekdayMsgs = array(
78 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
82 static public $mWeekdayAbbrevMsgs = array(
83 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
86 static public $mMonthMsgs = array(
87 'january', 'february', 'march', 'april', 'may_long', 'june',
88 'july', 'august', 'september', 'october', 'november',
91 static public $mMonthGenMsgs = array(
92 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
93 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
96 static public $mMonthAbbrevMsgs = array(
97 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
98 'sep', 'oct', 'nov', 'dec'
101 static public $mIranianCalendarMonthMsgs = array(
102 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
103 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
104 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
105 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
108 static public $mHebrewCalendarMonthMsgs = array(
109 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
110 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
111 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
112 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
113 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
116 static public $mHebrewCalendarMonthGenMsgs = array(
117 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
118 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
119 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
120 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
121 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
124 static public $mHijriCalendarMonthMsgs = array(
125 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
126 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
127 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
128 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
132 * Get a cached language object for a given language code
134 static function factory( $code ) {
135 if ( !isset( self
::$mLangObjCache[$code] ) ) {
136 if ( count( self
::$mLangObjCache ) > 10 ) {
137 // Don't keep a billion objects around, that's stupid.
138 self
::$mLangObjCache = array();
140 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
142 return self
::$mLangObjCache[$code];
146 * Create a language object for a given language code
148 protected static function newFromCode( $code ) {
150 static $recursionLevel = 0;
151 if ( $code == 'en' ) {
154 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
155 // Preload base classes to work around APC/PHP5 bug
156 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
157 include_once( "$IP/languages/classes/$class.deps.php" );
159 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
160 include_once( "$IP/languages/classes/$class.php" );
164 if ( $recursionLevel > 5 ) {
165 throw new MWException( "Language fallback loop detected when creating class $class\n" );
168 if ( !class_exists( $class ) ) {
169 $fallback = Language
::getFallbackFor( $code );
171 $lang = Language
::newFromCode( $fallback );
173 $lang->setCode( $code );
181 * Get the LocalisationCache instance
183 public static function getLocalisationCache() {
184 if ( is_null( self
::$dataCache ) ) {
185 global $wgLocalisationCacheConf;
186 $class = $wgLocalisationCacheConf['class'];
187 self
::$dataCache = new $class( $wgLocalisationCacheConf );
189 return self
::$dataCache;
192 function __construct() {
193 $this->mConverter
= new FakeConverter( $this );
194 // Set the code to the name of the descendant
195 if ( get_class( $this ) == 'Language' ) {
198 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
200 self
::getLocalisationCache();
204 * Reduce memory usage
206 function __destruct() {
207 foreach ( $this as $name => $value ) {
208 unset( $this->$name );
213 * Hook which will be called if this is the content language.
214 * Descendants can use this to register hook functions or modify globals
216 function initContLang() { }
219 * @deprecated Use User::getDefaultOptions()
222 function getDefaultUserOptions() {
223 wfDeprecated( __METHOD__
);
224 return User
::getDefaultOptions();
227 function getFallbackLanguageCode() {
228 if ( $this->mCode
=== 'en' ) {
231 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
236 * Exports $wgBookstoreListEn
239 function getBookstoreList() {
240 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
246 function getNamespaces() {
247 if ( is_null( $this->namespaceNames
) ) {
248 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
250 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
251 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
253 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
255 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
256 if ( $wgMetaNamespaceTalk ) {
257 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
259 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
260 $this->namespaceNames
[NS_PROJECT_TALK
] =
261 $this->fixVariableInNamespace( $talk );
264 # Sometimes a language will be localised but not actually exist on this wiki.
265 foreach( $this->namespaceNames
as $key => $text ) {
266 if ( !isset( $validNamespaces[$key] ) ) {
267 unset( $this->namespaceNames
[$key] );
271 # The above mixing may leave namespaces out of canonical order.
272 # Re-order by namespace ID number...
273 ksort( $this->namespaceNames
);
275 return $this->namespaceNames
;
279 * A convenience function that returns the same thing as
280 * getNamespaces() except with the array values changed to ' '
281 * where it found '_', useful for producing output to be displayed
282 * e.g. in <select> forms.
286 function getFormattedNamespaces() {
287 $ns = $this->getNamespaces();
288 foreach ( $ns as $k => $v ) {
289 $ns[$k] = strtr( $v, '_', ' ' );
295 * Get a namespace value by key
297 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
298 * echo $mw_ns; // prints 'MediaWiki'
301 * @param $index Int: the array key of the namespace to return
302 * @return mixed, string if the namespace value exists, otherwise false
304 function getNsText( $index ) {
305 $ns = $this->getNamespaces();
306 return isset( $ns[$index] ) ?
$ns[$index] : false;
310 * A convenience function that returns the same thing as
311 * getNsText() except with '_' changed to ' ', useful for
316 function getFormattedNsText( $index ) {
317 $ns = $this->getNsText( $index );
318 return strtr( $ns, '_', ' ' );
322 * Get a namespace key by value, case insensitive.
323 * Only matches namespace names for the current language, not the
324 * canonical ones defined in Namespace.php.
326 * @param $text String
327 * @return mixed An integer if $text is a valid value otherwise false
329 function getLocalNsIndex( $text ) {
330 $lctext = $this->lc( $text );
331 $ids = $this->getNamespaceIds();
332 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
335 function getNamespaceAliases() {
336 if ( is_null( $this->namespaceAliases
) ) {
337 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
341 foreach ( $aliases as $name => $index ) {
342 if ( $index === NS_PROJECT_TALK
) {
343 unset( $aliases[$name] );
344 $name = $this->fixVariableInNamespace( $name );
345 $aliases[$name] = $index;
349 $this->namespaceAliases
= $aliases;
351 return $this->namespaceAliases
;
354 function getNamespaceIds() {
355 if ( is_null( $this->mNamespaceIds
) ) {
356 global $wgNamespaceAliases;
357 # Put namespace names and aliases into a hashtable.
358 # If this is too slow, then we should arrange it so that it is done
359 # before caching. The catch is that at pre-cache time, the above
360 # class-specific fixup hasn't been done.
361 $this->mNamespaceIds
= array();
362 foreach ( $this->getNamespaces() as $index => $name ) {
363 $this->mNamespaceIds
[$this->lc( $name )] = $index;
365 foreach ( $this->getNamespaceAliases() as $name => $index ) {
366 $this->mNamespaceIds
[$this->lc( $name )] = $index;
368 if ( $wgNamespaceAliases ) {
369 foreach ( $wgNamespaceAliases as $name => $index ) {
370 $this->mNamespaceIds
[$this->lc( $name )] = $index;
374 return $this->mNamespaceIds
;
379 * Get a namespace key by value, case insensitive. Canonical namespace
380 * names override custom ones defined for the current language.
382 * @param $text String
383 * @return mixed An integer if $text is a valid value otherwise false
385 function getNsIndex( $text ) {
386 $lctext = $this->lc( $text );
387 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
390 $ids = $this->getNamespaceIds();
391 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
395 * short names for language variants used for language conversion links.
397 * @param $code String
400 function getVariantname( $code ) {
401 return $this->getMessageFromDB( "variantname-$code" );
404 function specialPage( $name ) {
405 $aliases = $this->getSpecialPageAliases();
406 if ( isset( $aliases[$name][0] ) ) {
407 $name = $aliases[$name][0];
409 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
412 function getQuickbarSettings() {
414 $this->getMessage( 'qbsettings-none' ),
415 $this->getMessage( 'qbsettings-fixedleft' ),
416 $this->getMessage( 'qbsettings-fixedright' ),
417 $this->getMessage( 'qbsettings-floatingleft' ),
418 $this->getMessage( 'qbsettings-floatingright' )
422 function getMathNames() {
423 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
426 function getDatePreferences() {
427 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
430 function getDateFormats() {
431 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
434 function getDefaultDateFormat() {
435 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
436 if ( $df === 'dmy or mdy' ) {
437 global $wgAmericanDates;
438 return $wgAmericanDates ?
'mdy' : 'dmy';
444 function getDatePreferenceMigrationMap() {
445 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
448 function getImageFile( $image ) {
449 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
452 function getDefaultUserOptionOverrides() {
453 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
456 function getExtraUserToggles() {
457 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
460 function getUserToggle( $tog ) {
461 return $this->getMessageFromDB( "tog-$tog" );
465 * Get language names, indexed by code.
466 * If $customisedOnly is true, only returns codes with a messages file
468 public static function getLanguageNames( $customisedOnly = false ) {
469 global $wgLanguageNames, $wgExtraLanguageNames;
470 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
471 if ( !$customisedOnly ) {
477 $dir = opendir( "$IP/languages/messages" );
478 while ( false !== ( $file = readdir( $dir ) ) ) {
479 $code = self
::getCodeFromFileName( $file, 'Messages' );
480 if ( $code && isset( $allNames[$code] ) ) {
481 $names[$code] = $allNames[$code];
489 * Get a message from the MediaWiki namespace.
491 * @param $msg String: message name
494 function getMessageFromDB( $msg ) {
495 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
498 function getLanguageName( $code ) {
499 $names = self
::getLanguageNames();
500 if ( !array_key_exists( $code, $names ) ) {
503 return $names[$code];
506 function getMonthName( $key ) {
507 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
510 function getMonthNameGen( $key ) {
511 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
514 function getMonthAbbreviation( $key ) {
515 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
518 function getWeekdayName( $key ) {
519 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
522 function getWeekdayAbbreviation( $key ) {
523 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
526 function getIranianCalendarMonthName( $key ) {
527 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
530 function getHebrewCalendarMonthName( $key ) {
531 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
534 function getHebrewCalendarMonthNameGen( $key ) {
535 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
538 function getHijriCalendarMonthName( $key ) {
539 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
543 * Used by date() and time() to adjust the time output.
545 * @param $ts Int the time in date('YmdHis') format
546 * @param $tz Mixed: adjust the time by this amount (default false, mean we
547 * get user timecorrection setting)
550 function userAdjust( $ts, $tz = false ) {
551 global $wgUser, $wgLocalTZoffset;
553 if ( $tz === false ) {
554 $tz = $wgUser->getOption( 'timecorrection' );
557 $data = explode( '|', $tz, 3 );
559 if ( $data[0] == 'ZoneInfo' ) {
560 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
561 $date = date_create( $ts, timezone_open( 'UTC' ) );
562 date_timezone_set( $date, timezone_open( $data[2] ) );
563 $date = date_format( $date, 'YmdHis' );
566 # Unrecognized timezone, default to 'Offset' with the stored offset.
571 if ( $data[0] == 'System' ||
$tz == '' ) {
572 # Global offset in minutes.
573 if ( isset( $wgLocalTZoffset ) ) {
574 $minDiff = $wgLocalTZoffset;
576 } else if ( $data[0] == 'Offset' ) {
577 $minDiff = intval( $data[1] );
579 $data = explode( ':', $tz );
580 if ( count( $data ) == 2 ) {
581 $data[0] = intval( $data[0] );
582 $data[1] = intval( $data[1] );
583 $minDiff = abs( $data[0] ) * 60 +
$data[1];
584 if ( $data[0] < 0 ) {
585 $minDiff = -$minDiff;
588 $minDiff = intval( $data[0] ) * 60;
592 # No difference ? Return time unchanged
593 if ( 0 == $minDiff ) {
597 wfSuppressWarnings(); // E_STRICT system time bitching
598 # Generate an adjusted date; take advantage of the fact that mktime
599 # will normalize out-of-range values so we don't have to split $minDiff
600 # into hours and minutes.
602 (int)substr( $ts, 8, 2 ) ), # Hours
603 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
604 (int)substr( $ts, 12, 2 ), # Seconds
605 (int)substr( $ts, 4, 2 ), # Month
606 (int)substr( $ts, 6, 2 ), # Day
607 (int)substr( $ts, 0, 4 ) ); # Year
609 $date = date( 'YmdHis', $t );
616 * This is a workalike of PHP's date() function, but with better
617 * internationalisation, a reduced set of format characters, and a better
620 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
621 * PHP manual for definitions. "o" format character is supported since
622 * PHP 5.1.0, previous versions return literal o.
623 * There are a number of extensions, which start with "x":
625 * xn Do not translate digits of the next numeric format character
626 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
627 * xr Use roman numerals for the next numeric format character
628 * xh Use hebrew numerals for the next numeric format character
630 * xg Genitive month name
632 * xij j (day number) in Iranian calendar
633 * xiF F (month name) in Iranian calendar
634 * xin n (month number) in Iranian calendar
635 * xiY Y (full year) in Iranian calendar
637 * xjj j (day number) in Hebrew calendar
638 * xjF F (month name) in Hebrew calendar
639 * xjt t (days in month) in Hebrew calendar
640 * xjx xg (genitive month name) in Hebrew calendar
641 * xjn n (month number) in Hebrew calendar
642 * xjY Y (full year) in Hebrew calendar
644 * xmj j (day number) in Hijri calendar
645 * xmF F (month name) in Hijri calendar
646 * xmn n (month number) in Hijri calendar
647 * xmY Y (full year) in Hijri calendar
649 * xkY Y (full year) in Thai solar calendar. Months and days are
650 * identical to the Gregorian calendar
651 * xoY Y (full year) in Minguo calendar or Juche year.
652 * Months and days are identical to the
654 * xtY Y (full year) in Japanese nengo. Months and days are
655 * identical to the Gregorian calendar
657 * Characters enclosed in double quotes will be considered literal (with
658 * the quotes themselves removed). Unmatched quotes will be considered
659 * literal quotes. Example:
661 * "The month is" F => The month is January
664 * Backslash escaping is also supported.
666 * Input timestamp is assumed to be pre-normalized to the desired local
669 * @param $format String
670 * @param $ts String: 14-character timestamp
673 * @todo emulation of "o" format character for PHP pre 5.1.0
674 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
676 function sprintfDate( $format, $ts ) {
689 for ( $p = 0; $p < strlen( $format ); $p++
) {
692 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
693 $code .= $format[++
$p];
696 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
697 $code .= $format[++
$p];
708 $rawToggle = !$rawToggle;
717 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
720 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
721 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
724 $num = substr( $ts, 6, 2 );
727 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
728 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
731 $num = intval( substr( $ts, 6, 2 ) );
735 $iranian = self
::tsToIranian( $ts );
741 $hijri = self
::tsToHijri( $ts );
747 $hebrew = self
::tsToHebrew( $ts );
753 $unix = wfTimestamp( TS_UNIX
, $ts );
755 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
759 $unix = wfTimestamp( TS_UNIX
, $ts );
761 $w = gmdate( 'w', $unix );
766 $unix = wfTimestamp( TS_UNIX
, $ts );
768 $num = gmdate( 'w', $unix );
772 $unix = wfTimestamp( TS_UNIX
, $ts );
774 $num = gmdate( 'z', $unix );
778 $unix = wfTimestamp( TS_UNIX
, $ts );
780 $num = gmdate( 'W', $unix );
783 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
787 $iranian = self
::tsToIranian( $ts );
789 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
793 $hijri = self
::tsToHijri( $ts );
795 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
799 $hebrew = self
::tsToHebrew( $ts );
801 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
804 $num = substr( $ts, 4, 2 );
807 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
810 $num = intval( substr( $ts, 4, 2 ) );
814 $iranian = self
::tsToIranian( $ts );
820 $hijri = self
::tsToHijri ( $ts );
826 $hebrew = self
::tsToHebrew( $ts );
832 $unix = wfTimestamp( TS_UNIX
, $ts );
834 $num = gmdate( 't', $unix );
838 $hebrew = self
::tsToHebrew( $ts );
844 $unix = wfTimestamp( TS_UNIX
, $ts );
846 $num = gmdate( 'L', $unix );
848 # 'o' is supported since PHP 5.1.0
849 # return literal if not supported
850 # TODO: emulation for pre 5.1.0 versions
853 $unix = wfTimestamp( TS_UNIX
, $ts );
855 if ( version_compare( PHP_VERSION
, '5.1.0' ) === 1 ) {
856 $num = date( 'o', $unix );
862 $num = substr( $ts, 0, 4 );
866 $iranian = self
::tsToIranian( $ts );
872 $hijri = self
::tsToHijri( $ts );
878 $hebrew = self
::tsToHebrew( $ts );
884 $thai = self
::tsToYear( $ts, 'thai' );
890 $minguo = self
::tsToYear( $ts, 'minguo' );
896 $tenno = self
::tsToYear( $ts, 'tenno' );
901 $num = substr( $ts, 2, 2 );
904 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
907 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
910 $h = substr( $ts, 8, 2 );
911 $num = $h %
12 ?
$h %
12 : 12;
914 $num = intval( substr( $ts, 8, 2 ) );
917 $h = substr( $ts, 8, 2 );
918 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
921 $num = substr( $ts, 8, 2 );
924 $num = substr( $ts, 10, 2 );
927 $num = substr( $ts, 12, 2 );
931 $unix = wfTimestamp( TS_UNIX
, $ts );
933 $s .= gmdate( 'c', $unix );
937 $unix = wfTimestamp( TS_UNIX
, $ts );
939 $s .= gmdate( 'r', $unix );
943 $unix = wfTimestamp( TS_UNIX
, $ts );
949 if ( $p < strlen( $format ) - 1 ) {
957 if ( $p < strlen( $format ) - 1 ) {
958 $endQuote = strpos( $format, '"', $p +
1 );
959 if ( $endQuote === false ) {
960 # No terminating quote, assume literal "
963 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
967 # Quote at end of string, assume literal "
974 if ( $num !== false ) {
975 if ( $rawToggle ||
$raw ) {
978 } elseif ( $roman ) {
979 $s .= self
::romanNumeral( $num );
981 } elseif ( $hebrewNum ) {
982 $s .= self
::hebrewNumeral( $num );
985 $s .= $this->formatNum( $num, true );
993 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
994 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
996 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
997 * Gregorian dates to Iranian dates. Originally written in C, it
998 * is released under the terms of GNU Lesser General Public
999 * License. Conversion to PHP was performed by Niklas Laxström.
1001 * Link: http://www.farsiweb.info/jalali/jalali.c
1003 private static function tsToIranian( $ts ) {
1004 $gy = substr( $ts, 0, 4 ) -1600;
1005 $gm = substr( $ts, 4, 2 ) -1;
1006 $gd = substr( $ts, 6, 2 ) -1;
1008 # Days passed from the beginning (including leap years)
1010 +
floor( ( $gy +
3 ) / 4 )
1011 - floor( ( $gy +
99 ) / 100 )
1012 +
floor( ( $gy +
399 ) / 400 );
1015 // Add days of the past months of this year
1016 for ( $i = 0; $i < $gm; $i++
) {
1017 $gDayNo +
= self
::$GREG_DAYS[$i];
1021 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1025 // Days passed in current month
1028 $jDayNo = $gDayNo - 79;
1030 $jNp = floor( $jDayNo / 12053 );
1033 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1036 if ( $jDayNo >= 366 ) {
1037 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1038 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1041 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1042 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1048 return array( $jy, $jm, $jd );
1052 * Converting Gregorian dates to Hijri dates.
1054 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1056 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1058 private static function tsToHijri( $ts ) {
1059 $year = substr( $ts, 0, 4 );
1060 $month = substr( $ts, 4, 2 );
1061 $day = substr( $ts, 6, 2 );
1069 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1070 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1073 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1074 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1075 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1078 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1079 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1082 $zl = $zjd -1948440 +
10632;
1083 $zn = (int)( ( $zl - 1 ) / 10631 );
1084 $zl = $zl - 10631 * $zn +
354;
1085 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1086 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1087 $zm = (int)( ( 24 * $zl ) / 709 );
1088 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1089 $zy = 30 * $zn +
$zj - 30;
1091 return array( $zy, $zm, $zd );
1095 * Converting Gregorian dates to Hebrew dates.
1097 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1098 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1099 * to translate the relevant functions into PHP and release them under
1102 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1103 * and Adar II is 14. In a non-leap year, Adar is 6.
1105 private static function tsToHebrew( $ts ) {
1107 $year = substr( $ts, 0, 4 );
1108 $month = substr( $ts, 4, 2 );
1109 $day = substr( $ts, 6, 2 );
1111 # Calculate Hebrew year
1112 $hebrewYear = $year +
3760;
1114 # Month number when September = 1, August = 12
1116 if ( $month > 12 ) {
1123 # Calculate day of year from 1 September
1125 for ( $i = 1; $i < $month; $i++
) {
1129 # Check if the year is leap
1130 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1133 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1140 # Calculate the start of the Hebrew year
1141 $start = self
::hebrewYearStart( $hebrewYear );
1143 # Calculate next year's start
1144 if ( $dayOfYear <= $start ) {
1145 # Day is before the start of the year - it is the previous year
1147 $nextStart = $start;
1151 # Add days since previous year's 1 September
1153 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1157 # Start of the new (previous) year
1158 $start = self
::hebrewYearStart( $hebrewYear );
1161 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1164 # Calculate Hebrew day of year
1165 $hebrewDayOfYear = $dayOfYear - $start;
1167 # Difference between year's days
1168 $diff = $nextStart - $start;
1169 # Add 12 (or 13 for leap years) days to ignore the difference between
1170 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1171 # difference is only about the year type
1172 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1178 # Check the year pattern, and is leap year
1179 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1180 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1181 # and non-leap years
1182 $yearPattern = $diff %
30;
1183 # Check if leap year
1184 $isLeap = $diff >= 30;
1186 # Calculate day in the month from number of day in the Hebrew year
1187 # Don't check Adar - if the day is not in Adar, we will stop before;
1188 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1189 $hebrewDay = $hebrewDayOfYear;
1192 while ( $hebrewMonth <= 12 ) {
1193 # Calculate days in this month
1194 if ( $isLeap && $hebrewMonth == 6 ) {
1195 # Adar in a leap year
1197 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1199 if ( $hebrewDay <= $days ) {
1203 # Subtract the days of Adar I
1204 $hebrewDay -= $days;
1207 if ( $hebrewDay <= $days ) {
1213 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1214 # Cheshvan in a complete year (otherwise as the rule below)
1216 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1217 # Kislev in an incomplete year (otherwise as the rule below)
1220 # Odd months have 30 days, even have 29
1221 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1223 if ( $hebrewDay <= $days ) {
1224 # In the current month
1227 # Subtract the days of the current month
1228 $hebrewDay -= $days;
1229 # Try in the next month
1234 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1238 * This calculates the Hebrew year start, as days since 1 September.
1239 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1240 * Used for Hebrew date.
1242 private static function hebrewYearStart( $year ) {
1243 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1244 $b = intval( ( $year - 1 ) %
4 );
1245 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1249 $Mar = intval( $m );
1255 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1256 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1258 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1260 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1264 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1269 * Algorithm to convert Gregorian dates to Thai solar dates,
1270 * Minguo dates or Minguo dates.
1272 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1273 * http://en.wikipedia.org/wiki/Minguo_calendar
1274 * http://en.wikipedia.org/wiki/Japanese_era_name
1276 * @param $ts String: 14-character timestamp
1277 * @param $cName String: calender name
1278 * @return Array: converted year, month, day
1280 private static function tsToYear( $ts, $cName ) {
1281 $gy = substr( $ts, 0, 4 );
1282 $gm = substr( $ts, 4, 2 );
1283 $gd = substr( $ts, 6, 2 );
1285 if ( !strcmp( $cName, 'thai' ) ) {
1287 # Add 543 years to the Gregorian calendar
1288 # Months and days are identical
1289 $gy_offset = $gy +
543;
1290 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1292 # Deduct 1911 years from the Gregorian calendar
1293 # Months and days are identical
1294 $gy_offset = $gy - 1911;
1295 } else if ( !strcmp( $cName, 'tenno' ) ) {
1296 # Nengō dates up to Meiji period
1297 # Deduct years from the Gregorian calendar
1298 # depending on the nengo periods
1299 # Months and days are identical
1300 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1302 $gy_gannen = $gy - 1868 +
1;
1303 $gy_offset = $gy_gannen;
1304 if ( $gy_gannen == 1 ) {
1307 $gy_offset = '明治' . $gy_offset;
1309 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1310 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1311 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1312 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1313 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1317 $gy_gannen = $gy - 1912 +
1;
1318 $gy_offset = $gy_gannen;
1319 if ( $gy_gannen == 1 ) {
1322 $gy_offset = '大正' . $gy_offset;
1324 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1325 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1326 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1330 $gy_gannen = $gy - 1926 +
1;
1331 $gy_offset = $gy_gannen;
1332 if ( $gy_gannen == 1 ) {
1335 $gy_offset = '昭和' . $gy_offset;
1338 $gy_gannen = $gy - 1989 +
1;
1339 $gy_offset = $gy_gannen;
1340 if ( $gy_gannen == 1 ) {
1343 $gy_offset = '平成' . $gy_offset;
1349 return array( $gy_offset, $gm, $gd );
1353 * Roman number formatting up to 3000
1355 static function romanNumeral( $num ) {
1356 static $table = array(
1357 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1358 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1359 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1360 array( '', 'M', 'MM', 'MMM' )
1363 $num = intval( $num );
1364 if ( $num > 3000 ||
$num <= 0 ) {
1369 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1370 if ( $num >= $pow10 ) {
1371 $s .= $table[$i][floor( $num / $pow10 )];
1373 $num = $num %
$pow10;
1379 * Hebrew Gematria number formatting up to 9999
1381 static function hebrewNumeral( $num ) {
1382 static $table = array(
1383 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1384 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1385 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1386 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1389 $num = intval( $num );
1390 if ( $num > 9999 ||
$num <= 0 ) {
1395 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1396 if ( $num >= $pow10 ) {
1397 if ( $num == 15 ||
$num == 16 ) {
1398 $s .= $table[0][9] . $table[0][$num - 9];
1401 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1402 if ( $pow10 == 1000 ) {
1407 $num = $num %
$pow10;
1409 if ( strlen( $s ) == 2 ) {
1412 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1413 $str .= substr( $s, strlen( $s ) - 2, 2 );
1415 $start = substr( $str, 0, strlen( $str ) - 2 );
1416 $end = substr( $str, strlen( $str ) - 2 );
1419 $str = $start . 'ך';
1422 $str = $start . 'ם';
1425 $str = $start . 'ן';
1428 $str = $start . 'ף';
1431 $str = $start . 'ץ';
1438 * This is meant to be used by time(), date(), and timeanddate() to get
1439 * the date preference they're supposed to use, it should be used in
1443 * function timeanddate([...], $format = true) {
1444 * $datePreference = $this->dateFormat($format);
1449 * @param $usePrefs Mixed: if true, the user's preference is used
1450 * if false, the site/language default is used
1451 * if int/string, assumed to be a format.
1454 function dateFormat( $usePrefs = true ) {
1457 if ( is_bool( $usePrefs ) ) {
1459 $datePreference = $wgUser->getDatePreference();
1461 $datePreference = (string)User
::getDefaultOption( 'date' );
1464 $datePreference = (string)$usePrefs;
1468 if ( $datePreference == '' ) {
1472 return $datePreference;
1476 * Get a format string for a given type and preference
1477 * @param $type May be date, time or both
1478 * @param $pref The format name as it appears in Messages*.php
1480 function getDateFormatString( $type, $pref ) {
1481 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1482 if ( $pref == 'default' ) {
1483 $pref = $this->getDefaultDateFormat();
1484 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1486 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1487 if ( is_null( $df ) ) {
1488 $pref = $this->getDefaultDateFormat();
1489 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1492 $this->dateFormatStrings
[$type][$pref] = $df;
1494 return $this->dateFormatStrings
[$type][$pref];
1498 * @param $ts Mixed: the time format which needs to be turned into a
1499 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1500 * @param $adj Bool: whether to adjust the time output according to the
1501 * user configured offset ($timecorrection)
1502 * @param $format Mixed: true to use user's date format preference
1503 * @param $timecorrection String: the time offset as returned by
1504 * validateTimeZone() in Special:Preferences
1507 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1509 $ts = $this->userAdjust( $ts, $timecorrection );
1511 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1512 return $this->sprintfDate( $df, $ts );
1516 * @param $ts Mixed: the time format which needs to be turned into a
1517 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1518 * @param $adj Bool: whether to adjust the time output according to the
1519 * user configured offset ($timecorrection)
1520 * @param $format Mixed: true to use user's date format preference
1521 * @param $timecorrection String: the time offset as returned by
1522 * validateTimeZone() in Special:Preferences
1525 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1527 $ts = $this->userAdjust( $ts, $timecorrection );
1529 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1530 return $this->sprintfDate( $df, $ts );
1534 * @param $ts Mixed: the time format which needs to be turned into a
1535 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1536 * @param $adj Bool: whether to adjust the time output according to the
1537 * user configured offset ($timecorrection)
1538 * @param $format Mixed: what format to return, if it's false output the
1539 * default one (default true)
1540 * @param $timecorrection String: the time offset as returned by
1541 * validateTimeZone() in Special:Preferences
1544 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1545 $ts = wfTimestamp( TS_MW
, $ts );
1547 $ts = $this->userAdjust( $ts, $timecorrection );
1549 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1550 return $this->sprintfDate( $df, $ts );
1553 function getMessage( $key ) {
1554 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1557 function getAllMessages() {
1558 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1561 function iconv( $in, $out, $string ) {
1562 # This is a wrapper for iconv in all languages except esperanto,
1563 # which does some nasty x-conversions beforehand
1565 # Even with //IGNORE iconv can whine about illegal characters in
1566 # *input* string. We just ignore those too.
1567 # REF: http://bugs.php.net/bug.php?id=37166
1568 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1569 wfSuppressWarnings();
1570 $text = iconv( $in, $out . '//IGNORE', $string );
1571 wfRestoreWarnings();
1575 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1576 function ucwordbreaksCallbackAscii( $matches ) {
1577 return $this->ucfirst( $matches[1] );
1580 function ucwordbreaksCallbackMB( $matches ) {
1581 return mb_strtoupper( $matches[0] );
1584 function ucCallback( $matches ) {
1585 list( $wikiUpperChars ) = self
::getCaseMaps();
1586 return strtr( $matches[1], $wikiUpperChars );
1589 function lcCallback( $matches ) {
1590 list( , $wikiLowerChars ) = self
::getCaseMaps();
1591 return strtr( $matches[1], $wikiLowerChars );
1594 function ucwordsCallbackMB( $matches ) {
1595 return mb_strtoupper( $matches[0] );
1598 function ucwordsCallbackWiki( $matches ) {
1599 list( $wikiUpperChars ) = self
::getCaseMaps();
1600 return strtr( $matches[0], $wikiUpperChars );
1604 * Make a string's first character uppercase
1606 function ucfirst( $str ) {
1608 if ( $o < 96 ) { // if already uppercase...
1610 } elseif ( $o < 128 ) {
1611 return ucfirst( $str ); // use PHP's ucfirst()
1613 // fall back to more complex logic in case of multibyte strings
1614 return $this->uc( $str, true );
1619 * Convert a string to uppercase
1621 function uc( $str, $first = false ) {
1622 if ( function_exists( 'mb_strtoupper' ) ) {
1624 if ( $this->isMultibyte( $str ) ) {
1625 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1627 return ucfirst( $str );
1630 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1633 if ( $this->isMultibyte( $str ) ) {
1634 $x = $first ?
'^' : '';
1635 return preg_replace_callback(
1636 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1637 array( $this, 'ucCallback' ),
1641 return $first ?
ucfirst( $str ) : strtoupper( $str );
1646 function lcfirst( $str ) {
1649 return strval( $str );
1650 } elseif ( $o >= 128 ) {
1651 return $this->lc( $str, true );
1652 } elseif ( $o > 96 ) {
1655 $str[0] = strtolower( $str[0] );
1660 function lc( $str, $first = false ) {
1661 if ( function_exists( 'mb_strtolower' ) ) {
1663 if ( $this->isMultibyte( $str ) ) {
1664 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1666 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1669 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1672 if ( $this->isMultibyte( $str ) ) {
1673 $x = $first ?
'^' : '';
1674 return preg_replace_callback(
1675 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1676 array( $this, 'lcCallback' ),
1680 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1685 function isMultibyte( $str ) {
1686 return (bool)preg_match( '/[\x80-\xff]/', $str );
1689 function ucwords( $str ) {
1690 if ( $this->isMultibyte( $str ) ) {
1691 $str = $this->lc( $str );
1693 // regexp to find first letter in each word (i.e. after each space)
1694 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1696 // function to use to capitalize a single char
1697 if ( function_exists( 'mb_strtoupper' ) ) {
1698 return preg_replace_callback(
1700 array( $this, 'ucwordsCallbackMB' ),
1704 return preg_replace_callback(
1706 array( $this, 'ucwordsCallbackWiki' ),
1711 return ucwords( strtolower( $str ) );
1715 # capitalize words at word breaks
1716 function ucwordbreaks( $str ) {
1717 if ( $this->isMultibyte( $str ) ) {
1718 $str = $this->lc( $str );
1720 // since \b doesn't work for UTF-8, we explicitely define word break chars
1721 $breaks = "[ \-\(\)\}\{\.,\?!]";
1723 // find first letter after word break
1724 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1726 if ( function_exists( 'mb_strtoupper' ) ) {
1727 return preg_replace_callback(
1729 array( $this, 'ucwordbreaksCallbackMB' ),
1733 return preg_replace_callback(
1735 array( $this, 'ucwordsCallbackWiki' ),
1740 return preg_replace_callback(
1741 '/\b([\w\x80-\xff]+)\b/',
1742 array( $this, 'ucwordbreaksCallbackAscii' ),
1749 * Return a case-folded representation of $s
1751 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1752 * and $s2 are the same except for the case of their characters. It is not
1753 * necessary for the value returned to make sense when displayed.
1755 * Do *not* perform any other normalisation in this function. If a caller
1756 * uses this function when it should be using a more general normalisation
1757 * function, then fix the caller.
1759 function caseFold( $s ) {
1760 return $this->uc( $s );
1763 function checkTitleEncoding( $s ) {
1764 if ( is_array( $s ) ) {
1765 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1767 # Check for non-UTF-8 URLs
1768 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1773 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1774 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1779 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1782 function fallback8bitEncoding() {
1783 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1787 * Most writing systems use whitespace to break up words.
1788 * Some languages such as Chinese don't conventionally do this,
1789 * which requires special handling when breaking up words for
1792 function hasWordBreaks() {
1797 * Some languages such as Chinese require word segmentation,
1798 * Specify such segmentation when overridden in derived class.
1800 * @param $string String
1803 function segmentByWord( $string ) {
1808 * Some languages have special punctuation need to be normalized.
1809 * Make such changes here.
1811 * @param $string String
1814 function normalizeForSearch( $string ) {
1815 return self
::convertDoubleWidth( $string );
1819 * convert double-width roman characters to single-width.
1820 * range: ff00-ff5f ~= 0020-007f
1822 protected static function convertDoubleWidth( $string ) {
1823 static $full = null;
1824 static $half = null;
1826 if ( $full === null ) {
1827 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1828 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1829 $full = str_split( $fullWidth, 3 );
1830 $half = str_split( $halfWidth );
1833 $string = str_replace( $full, $half, $string );
1837 protected static function insertSpace( $string, $pattern ) {
1838 $string = preg_replace( $pattern, " $1 ", $string );
1839 $string = preg_replace( '/ +/', ' ', $string );
1843 function convertForSearchResult( $termsArray ) {
1844 # some languages, e.g. Chinese, need to do a conversion
1845 # in order for search results to be displayed correctly
1850 * Get the first character of a string.
1855 function firstChar( $s ) {
1858 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1859 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1864 if ( isset( $matches[1] ) ) {
1865 if ( strlen( $matches[1] ) != 3 ) {
1869 // Break down Hangul syllables to grab the first jamo
1870 $code = utf8ToCodepoint( $matches[1] );
1871 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1873 } elseif ( $code < 0xb098 ) {
1874 return "\xe3\x84\xb1";
1875 } elseif ( $code < 0xb2e4 ) {
1876 return "\xe3\x84\xb4";
1877 } elseif ( $code < 0xb77c ) {
1878 return "\xe3\x84\xb7";
1879 } elseif ( $code < 0xb9c8 ) {
1880 return "\xe3\x84\xb9";
1881 } elseif ( $code < 0xbc14 ) {
1882 return "\xe3\x85\x81";
1883 } elseif ( $code < 0xc0ac ) {
1884 return "\xe3\x85\x82";
1885 } elseif ( $code < 0xc544 ) {
1886 return "\xe3\x85\x85";
1887 } elseif ( $code < 0xc790 ) {
1888 return "\xe3\x85\x87";
1889 } elseif ( $code < 0xcc28 ) {
1890 return "\xe3\x85\x88";
1891 } elseif ( $code < 0xce74 ) {
1892 return "\xe3\x85\x8a";
1893 } elseif ( $code < 0xd0c0 ) {
1894 return "\xe3\x85\x8b";
1895 } elseif ( $code < 0xd30c ) {
1896 return "\xe3\x85\x8c";
1897 } elseif ( $code < 0xd558 ) {
1898 return "\xe3\x85\x8d";
1900 return "\xe3\x85\x8e";
1907 function initEncoding() {
1908 # Some languages may have an alternate char encoding option
1909 # (Esperanto X-coding, Japanese furigana conversion, etc)
1910 # If this language is used as the primary content language,
1911 # an override to the defaults can be set here on startup.
1914 function recodeForEdit( $s ) {
1915 # For some languages we'll want to explicitly specify
1916 # which characters make it into the edit box raw
1917 # or are converted in some way or another.
1918 # Note that if wgOutputEncoding is different from
1919 # wgInputEncoding, this text will be further converted
1920 # to wgOutputEncoding.
1921 global $wgEditEncoding;
1922 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1925 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1929 function recodeInput( $s ) {
1930 # Take the previous into account.
1931 global $wgEditEncoding;
1932 if ( $wgEditEncoding != '' ) {
1933 $enc = $wgEditEncoding;
1937 if ( $enc == 'UTF-8' ) {
1940 return $this->iconv( $enc, 'UTF-8', $s );
1945 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1946 * also cleans up certain backwards-compatible sequences, converting them
1947 * to the modern Unicode equivalent.
1949 * This is language-specific for performance reasons only.
1951 function normalize( $s ) {
1952 global $wgAllUnicodeFixes;
1953 $s = UtfNormal
::cleanUp( $s );
1954 if ( $wgAllUnicodeFixes ) {
1955 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1956 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1963 * Transform a string using serialized data stored in the given file (which
1964 * must be in the serialized subdirectory of $IP). The file contains pairs
1965 * mapping source characters to destination characters.
1967 * The data is cached in process memory. This will go faster if you have the
1968 * FastStringSearch extension.
1970 function transformUsingPairFile( $file, $string ) {
1971 if ( !isset( $this->transformData
[$file] ) ) {
1972 $data = wfGetPrecompiledData( $file );
1973 if ( $data === false ) {
1974 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1976 $this->transformData
[$file] = new ReplacementArray( $data );
1978 return $this->transformData
[$file]->replace( $string );
1982 * For right-to-left language support
1987 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1991 * Return the correct HTML 'dir' attribute value for this language.
1995 return $this->isRTL() ?
'rtl' : 'ltr';
1999 * Return 'left' or 'right' as appropriate alignment for line-start
2000 * for this language's text direction.
2002 * Should be equivalent to CSS3 'start' text-align value....
2006 function alignStart() {
2007 return $this->isRTL() ?
'right' : 'left';
2011 * Return 'right' or 'left' as appropriate alignment for line-end
2012 * for this language's text direction.
2014 * Should be equivalent to CSS3 'end' text-align value....
2018 function alignEnd() {
2019 return $this->isRTL() ?
'left' : 'right';
2023 * A hidden direction mark (LRM or RLM), depending on the language direction
2027 function getDirMark() {
2028 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2031 function capitalizeAllNouns() {
2032 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2036 * An arrow, depending on the language direction
2040 function getArrow() {
2041 return $this->isRTL() ?
'←' : '→';
2045 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2049 function linkPrefixExtension() {
2050 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2053 function getMagicWords() {
2054 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2057 # Fill a MagicWord object with data from here
2058 function getMagic( $mw ) {
2059 if ( !$this->mMagicHookDone
) {
2060 $this->mMagicHookDone
= true;
2061 wfProfileIn( 'LanguageGetMagic' );
2062 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2063 wfProfileOut( 'LanguageGetMagic' );
2065 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2066 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2068 $magicWords = $this->getMagicWords();
2069 if ( isset( $magicWords[$mw->mId
] ) ) {
2070 $rawEntry = $magicWords[$mw->mId
];
2076 if ( !is_array( $rawEntry ) ) {
2077 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2079 $mw->mCaseSensitive
= $rawEntry[0];
2080 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2085 * Add magic words to the extension array
2087 function addMagicWordsByLang( $newWords ) {
2088 $code = $this->getCode();
2089 $fallbackChain = array();
2090 while ( $code && !in_array( $code, $fallbackChain ) ) {
2091 $fallbackChain[] = $code;
2092 $code = self
::getFallbackFor( $code );
2094 if ( !in_array( 'en', $fallbackChain ) ) {
2095 $fallbackChain[] = 'en';
2097 $fallbackChain = array_reverse( $fallbackChain );
2098 foreach ( $fallbackChain as $code ) {
2099 if ( isset( $newWords[$code] ) ) {
2100 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2106 * Get special page names, as an associative array
2107 * case folded alias => real name
2109 function getSpecialPageAliases() {
2110 // Cache aliases because it may be slow to load them
2111 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2113 $this->mExtendedSpecialPageAliases
=
2114 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2115 wfRunHooks( 'LanguageGetSpecialPageAliases',
2116 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2119 return $this->mExtendedSpecialPageAliases
;
2123 * Italic is unsuitable for some languages
2125 * @param $text String: the text to be emphasized.
2128 function emphasize( $text ) {
2129 return "<em>$text</em>";
2133 * Normally we output all numbers in plain en_US style, that is
2134 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2135 * point twohundredthirtyfive. However this is not sutable for all
2136 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2137 * Icelandic just want to use commas instead of dots, and dots instead
2138 * of commas like "293.291,235".
2140 * An example of this function being called:
2142 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2145 * See LanguageGu.php for the Gujarati implementation and
2146 * $separatorTransformTable on MessageIs.php for
2147 * the , => . and . => , implementation.
2149 * @todo check if it's viable to use localeconv() for the decimal
2151 * @param $number Mixed: the string to be formatted, should be an integer
2152 * or a floating point number.
2153 * @param $nocommafy Bool: set to true for special numbers like dates
2156 function formatNum( $number, $nocommafy = false ) {
2157 global $wgTranslateNumerals;
2158 if ( !$nocommafy ) {
2159 $number = $this->commafy( $number );
2160 $s = $this->separatorTransformTable();
2162 $number = strtr( $number, $s );
2166 if ( $wgTranslateNumerals ) {
2167 $s = $this->digitTransformTable();
2169 $number = strtr( $number, $s );
2176 function parseFormattedNumber( $number ) {
2177 $s = $this->digitTransformTable();
2179 $number = strtr( $number, array_flip( $s ) );
2182 $s = $this->separatorTransformTable();
2184 $number = strtr( $number, array_flip( $s ) );
2187 $number = strtr( $number, array( ',' => '' ) );
2192 * Adds commas to a given number
2197 function commafy( $_ ) {
2198 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2201 function digitTransformTable() {
2202 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2205 function separatorTransformTable() {
2206 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2210 * Take a list of strings and build a locale-friendly comma-separated
2211 * list, using the local comma-separator message.
2212 * The last two strings are chained with an "and".
2217 function listToText( $l ) {
2219 $m = count( $l ) - 1;
2221 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2223 for ( $i = $m; $i >= 0; $i-- ) {
2226 } else if ( $i == $m - 1 ) {
2227 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2229 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2237 * Take a list of strings and build a locale-friendly comma-separated
2238 * list, using the local comma-separator message.
2239 * @param $list array of strings to put in a comma list
2242 function commaList( $list ) {
2247 array( 'parsemag', 'escapenoentities', 'language' => $this )
2253 * Take a list of strings and build a locale-friendly semicolon-separated
2254 * list, using the local semicolon-separator message.
2255 * @param $list array of strings to put in a semicolon list
2258 function semicolonList( $list ) {
2262 'semicolon-separator',
2263 array( 'parsemag', 'escapenoentities', 'language' => $this )
2269 * Same as commaList, but separate it with the pipe instead.
2270 * @param $list array of strings to put in a pipe list
2273 function pipeList( $list ) {
2278 array( 'escapenoentities', 'language' => $this )
2284 * Truncate a string to a specified length in bytes, appending an optional
2285 * string (e.g. for ellipses)
2287 * The database offers limited byte lengths for some columns in the database;
2288 * multi-byte character sets mean we need to ensure that only whole characters
2289 * are included, otherwise broken characters can be passed to the user
2291 * If $length is negative, the string will be truncated from the beginning
2293 * @param $string String to truncate
2294 * @param $length Int: maximum length (excluding ellipses)
2295 * @param $ellipsis String to append to the truncated text
2298 function truncate( $string, $length, $ellipsis = '...' ) {
2299 # Use the localized ellipsis character
2300 if ( $ellipsis == '...' ) {
2301 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2303 # Check if there is no need to truncate
2304 if ( $length == 0 ) {
2306 } elseif ( strlen( $string ) <= abs( $length ) ) {
2309 $stringOriginal = $string;
2310 if ( $length > 0 ) {
2311 $string = substr( $string, 0, $length ); // xyz...
2312 $string = $this->removeBadCharLast( $string );
2313 $string = $string . $ellipsis;
2315 $string = substr( $string, $length ); // ...xyz
2316 $string = $this->removeBadCharFirst( $string );
2317 $string = $ellipsis . $string;
2319 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2320 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2323 return $stringOriginal;
2328 * Remove bytes that represent an incomplete Unicode character
2329 * at the end of string (e.g. bytes of the char are missing)
2331 * @param $string String
2334 protected function removeBadCharLast( $string ) {
2335 $char = ord( $string[strlen( $string ) - 1] );
2337 if ( $char >= 0xc0 ) {
2338 # We got the first byte only of a multibyte char; remove it.
2339 $string = substr( $string, 0, -1 );
2340 } elseif ( $char >= 0x80 &&
2341 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2342 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2344 # We chopped in the middle of a character; remove it
2351 * Remove bytes that represent an incomplete Unicode character
2352 * at the start of string (e.g. bytes of the char are missing)
2354 * @param $string String
2357 protected function removeBadCharFirst( $string ) {
2358 $char = ord( $string[0] );
2359 if ( $char >= 0x80 && $char < 0xc0 ) {
2360 # We chopped in the middle of a character; remove the whole thing
2361 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2367 * Truncate a string of valid HTML to a specified length in bytes,
2368 * appending an optional string (e.g. for ellipses), and return valid HTML
2370 * This is only intended for styled/linked text, such as HTML with
2371 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2373 * Note: tries to fix broken HTML with MWTidy
2375 * @param string $text String to truncate
2376 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2377 * @param string $ellipsis String to append to the truncated text
2380 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2381 # Use the localized ellipsis character
2382 if ( $ellipsis == '...' ) {
2383 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2385 # Check if there is no need to truncate
2386 if ( $length <= 0 ) {
2387 return $ellipsis; // no text shown, nothing to format
2388 } elseif ( strlen( $text ) <= $length ) {
2389 return $text; // string short enough even *with* HTML
2391 $text = MWTidy
::tidy( $text ); // fix tags
2392 $displayLen = 0; // innerHTML legth so far
2393 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2394 $tagType = 0; // 0-open, 1-close
2395 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2396 $entityState = 0; // 0-not entity, 1-entity
2397 $tag = $ret = $ch = '';
2398 $openTags = array();
2399 $textLen = strlen( $text );
2400 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2402 $lastCh = $pos ?
$text[$pos - 1] : '';
2403 $ret .= $ch; // add to result string
2405 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2406 $entityState = 0; // for bad HTML
2407 $bracketState = 1; // tag started (checking for backslash)
2408 } elseif ( $ch == '>' ) {
2409 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2410 $entityState = 0; // for bad HTML
2411 $bracketState = 0; // out of brackets
2412 } elseif ( $bracketState == 1 ) {
2414 $tagType = 1; // close tag (e.g. "</span>")
2416 $tagType = 0; // open tag (e.g. "<span>")
2419 $bracketState = 2; // building tag name
2420 } elseif ( $bracketState == 2 ) {
2424 // Name found (e.g. "<a href=..."), add on tag attributes...
2425 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2427 } elseif ( $bracketState == 0 ) {
2428 if ( $entityState ) {
2431 $displayLen++
; // entity is one displayed char
2435 $entityState = 1; // entity found, (e.g. " ")
2437 $displayLen++
; // this char is displayed
2438 // Add on the other display text after this...
2439 $skipped = $this->truncate_skip(
2440 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2441 $displayLen +
= $skipped;
2446 # Consider truncation once the display length has reached the maximim.
2447 # Double-check that we're not in the middle of a bracket/entity...
2448 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2449 if ( !$testingEllipsis ) {
2450 $testingEllipsis = true;
2451 # Save where we are; we will truncate here unless
2452 # the ellipsis actually makes the string longer.
2453 $pOpenTags = $openTags; // save state
2454 $pRet = $ret; // save state
2455 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2456 # Ellipsis won't make string longer/equal, the truncation point was OK.
2457 $openTags = $pOpenTags; // reload state
2458 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2459 $ret .= $ellipsis; // add ellipsis
2464 if ( $displayLen == 0 ) {
2465 return ''; // no text shown, nothing to format
2467 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
2468 while ( count( $openTags ) > 0 ) {
2469 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2474 // truncateHtml() helper function
2475 // like strcspn() but adds the skipped chars to $ret
2476 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2478 if ( $start < strlen( $text ) ) {
2479 $skipCount = strcspn( $text, $search, $start, $len );
2480 $ret .= substr( $text, $start, $skipCount );
2485 // truncateHtml() helper function
2486 // (a) push or pop $tag from $openTags as needed
2487 // (b) clear $tag value
2488 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2489 $tag = ltrim( $tag );
2491 if ( $tagType == 0 && $lastCh != '/' ) {
2492 $openTags[] = $tag; // tag opened (didn't close itself)
2493 } else if ( $tagType == 1 ) {
2494 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2495 array_pop( $openTags ); // tag closed
2503 * Grammatical transformations, needed for inflected languages
2504 * Invoked by putting {{grammar:case|word}} in a message
2506 * @param $word string
2507 * @param $case string
2510 function convertGrammar( $word, $case ) {
2511 global $wgGrammarForms;
2512 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2513 return $wgGrammarForms[$this->getCode()][$case][$word];
2519 * Provides an alternative text depending on specified gender.
2520 * Usage {{gender:username|masculine|feminine|neutral}}.
2521 * username is optional, in which case the gender of current user is used,
2522 * but only in (some) interface messages; otherwise default gender is used.
2523 * If second or third parameter are not specified, masculine is used.
2524 * These details may be overriden per language.
2526 function gender( $gender, $forms ) {
2527 if ( !count( $forms ) ) {
2530 $forms = $this->preConvertPlural( $forms, 2 );
2531 if ( $gender === 'male' ) {
2534 if ( $gender === 'female' ) {
2537 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2541 * Plural form transformations, needed for some languages.
2542 * For example, there are 3 form of plural in Russian and Polish,
2543 * depending on "count mod 10". See [[w:Plural]]
2544 * For English it is pretty simple.
2546 * Invoked by putting {{plural:count|wordform1|wordform2}}
2547 * or {{plural:count|wordform1|wordform2|wordform3}}
2549 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2551 * @param $count Integer: non-localized number
2552 * @param $forms Array: different plural forms
2553 * @return string Correct form of plural for $count in this language
2555 function convertPlural( $count, $forms ) {
2556 if ( !count( $forms ) ) {
2559 $forms = $this->preConvertPlural( $forms, 2 );
2561 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2565 * Checks that convertPlural was given an array and pads it to requested
2566 * amound of forms by copying the last one.
2568 * @param $count Integer: How many forms should there be at least
2569 * @param $forms Array of forms given to convertPlural
2570 * @return array Padded array of forms or an exception if not an array
2572 protected function preConvertPlural( /* Array */ $forms, $count ) {
2573 while ( count( $forms ) < $count ) {
2574 $forms[] = $forms[count( $forms ) - 1];
2580 * For translating of expiry times
2581 * @param $str String: the validated block time in English
2582 * @return Somehow translated block time
2583 * @see LanguageFi.php for example implementation
2585 function translateBlockExpiry( $str ) {
2586 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2588 if ( $scBlockExpiryOptions == '-' ) {
2592 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2593 if ( strpos( $option, ':' ) === false ) {
2596 list( $show, $value ) = explode( ':', $option );
2597 if ( strcmp( $str, $value ) == 0 ) {
2598 return htmlspecialchars( trim( $show ) );
2606 * languages like Chinese need to be segmented in order for the diff
2609 * @param $text String
2612 function segmentForDiff( $text ) {
2617 * and unsegment to show the result
2619 * @param $text String
2622 function unsegmentForDiff( $text ) {
2626 # convert text to all supported variants
2627 function autoConvertToAllVariants( $text ) {
2628 return $this->mConverter
->autoConvertToAllVariants( $text );
2631 # convert text to different variants of a language.
2632 function convert( $text ) {
2633 return $this->mConverter
->convert( $text );
2636 # Convert a Title object to a string in the preferred variant
2637 function convertTitle( $title ) {
2638 return $this->mConverter
->convertTitle( $title );
2641 # Check if this is a language with variants
2642 function hasVariants() {
2643 return sizeof( $this->getVariants() ) > 1;
2646 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2647 function armourMath( $text ) {
2648 return $this->mConverter
->armourMath( $text );
2652 * Perform output conversion on a string, and encode for safe HTML output.
2653 * @param $text String text to be converted
2654 * @param $isTitle Bool whether this conversion is for the article title
2656 * @todo this should get integrated somewhere sane
2658 function convertHtml( $text, $isTitle = false ) {
2659 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2662 function convertCategoryKey( $key ) {
2663 return $this->mConverter
->convertCategoryKey( $key );
2667 * Get the list of variants supported by this langauge
2668 * see sample implementation in LanguageZh.php
2670 * @return array an array of language codes
2672 function getVariants() {
2673 return $this->mConverter
->getVariants();
2676 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2677 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2681 * If a language supports multiple variants, it is
2682 * possible that non-existing link in one variant
2683 * actually exists in another variant. this function
2684 * tries to find it. See e.g. LanguageZh.php
2686 * @param $link String: the name of the link
2687 * @param $nt Mixed: the title object of the link
2688 * @param $ignoreOtherCond Boolean: to disable other conditions when
2689 * we need to transclude a template or update a category's link
2690 * @return null the input parameters may be modified upon return
2692 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2693 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2697 * If a language supports multiple variants, converts text
2698 * into an array of all possible variants of the text:
2699 * 'variant' => text in that variant
2701 function convertLinkToAllVariants( $text ) {
2702 return $this->mConverter
->convertLinkToAllVariants( $text );
2706 * returns language specific options used by User::getPageRenderHash()
2707 * for example, the preferred language variant
2711 function getExtraHashOptions() {
2712 return $this->mConverter
->getExtraHashOptions();
2716 * For languages that support multiple variants, the title of an
2717 * article may be displayed differently in different variants. this
2718 * function returns the apporiate title defined in the body of the article.
2722 function getParsedTitle() {
2723 return $this->mConverter
->getParsedTitle();
2727 * Enclose a string with the "no conversion" tag. This is used by
2728 * various functions in the Parser
2730 * @param $text String: text to be tagged for no conversion
2732 * @return string the tagged text
2734 function markNoConversion( $text, $noParse = false ) {
2735 return $this->mConverter
->markNoConversion( $text, $noParse );
2739 * A regular expression to match legal word-trailing characters
2740 * which should be merged onto a link of the form [[foo]]bar.
2744 function linkTrail() {
2745 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2748 function getLangObj() {
2753 * Get the RFC 3066 code for this language object
2755 function getCode() {
2756 return $this->mCode
;
2759 function setCode( $code ) {
2760 $this->mCode
= $code;
2764 * Get the name of a file for a certain language code
2765 * @param $prefix string Prepend this to the filename
2766 * @param $code string Language code
2767 * @param $suffix string Append this to the filename
2768 * @return string $prefix . $mangledCode . $suffix
2770 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2771 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2775 * Get the language code from a file name. Inverse of getFileName()
2776 * @param $filename string $prefix . $languageCode . $suffix
2777 * @param $prefix string Prefix before the language code
2778 * @param $suffix string Suffix after the language code
2779 * @return Language code, or false if $prefix or $suffix isn't found
2781 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2783 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2784 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2785 if ( !count( $m ) ) {
2788 return str_replace( '_', '-', strtolower( $m[1] ) );
2791 static function getMessagesFileName( $code ) {
2793 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2796 static function getClassFileName( $code ) {
2798 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2802 * Get the fallback for a given language
2804 static function getFallbackFor( $code ) {
2805 if ( $code === 'en' ) {
2809 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2814 * Get all messages for a given language
2815 * WARNING: this may take a long time
2817 static function getMessagesFor( $code ) {
2818 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2822 * Get a message for a given language
2824 static function getMessageFor( $key, $code ) {
2825 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2828 function fixVariableInNamespace( $talk ) {
2829 if ( strpos( $talk, '$1' ) === false ) {
2833 global $wgMetaNamespace;
2834 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2836 # Allow grammar transformations
2837 # Allowing full message-style parsing would make simple requests
2838 # such as action=raw much more expensive than they need to be.
2839 # This will hopefully cover most cases.
2840 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2841 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2842 return str_replace( ' ', '_', $talk );
2845 function replaceGrammarInNamespace( $m ) {
2846 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2849 static function getCaseMaps() {
2850 static $wikiUpperChars, $wikiLowerChars;
2851 if ( isset( $wikiUpperChars ) ) {
2852 return array( $wikiUpperChars, $wikiLowerChars );
2855 wfProfileIn( __METHOD__
);
2856 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2857 if ( $arr === false ) {
2858 throw new MWException(
2859 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2862 wfProfileOut( __METHOD__
);
2863 return array( $wikiUpperChars, $wikiLowerChars );
2866 function formatTimePeriod( $seconds ) {
2867 if ( $seconds < 10 ) {
2868 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2869 } elseif ( $seconds < 60 ) {
2870 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2871 } elseif ( $seconds < 3600 ) {
2872 $minutes = floor( $seconds / 60 );
2873 $secondsPart = round( fmod( $seconds, 60 ) );
2874 if ( $secondsPart == 60 ) {
2878 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2879 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2881 $hours = floor( $seconds / 3600 );
2882 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2883 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2884 if ( $secondsPart == 60 ) {
2888 if ( $minutes == 60 ) {
2892 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2893 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2894 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2898 function formatBitrate( $bps ) {
2899 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2901 return $this->formatNum( $bps ) . $units[0];
2903 $unitIndex = floor( log10( $bps ) / 3 );
2904 $mantissa = $bps / pow( 1000, $unitIndex );
2905 if ( $mantissa < 10 ) {
2906 $mantissa = round( $mantissa, 1 );
2908 $mantissa = round( $mantissa );
2910 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2914 * Format a size in bytes for output, using an appropriate
2915 * unit (B, KB, MB or GB) according to the magnitude in question
2917 * @param $size Size to format
2918 * @return string Plain text (not HTML)
2920 function formatSize( $size ) {
2921 // For small sizes no decimal places necessary
2923 if ( $size > 1024 ) {
2924 $size = $size / 1024;
2925 if ( $size > 1024 ) {
2926 $size = $size / 1024;
2927 // For MB and bigger two decimal places are smarter
2929 if ( $size > 1024 ) {
2930 $size = $size / 1024;
2931 $msg = 'size-gigabytes';
2933 $msg = 'size-megabytes';
2936 $msg = 'size-kilobytes';
2939 $msg = 'size-bytes';
2941 $size = round( $size, $round );
2942 $text = $this->getMessageFromDB( $msg );
2943 return str_replace( '$1', $this->formatNum( $size ), $text );
2947 * Get the conversion rule title, if any.
2949 function getConvRuleTitle() {
2950 return $this->mConverter
->getConvRuleTitle();
2954 * Given a string, convert it to a (hopefully short) key that can be used
2955 * for efficient sorting. A binary sort according to the sortkeys
2956 * corresponds to a logical sort of the corresponding strings. Current
2957 * code expects that a null character should sort before all others, but
2958 * has no other particular expectations (and that one can be changed if
2961 * @param string $string UTF-8 string
2962 * @return string Binary sortkey
2964 public function convertToSortkey( $string ) {
2965 # Fake function for now
2966 return strtoupper( $string );
2970 * Given a string, return the logical "first letter" to be used for
2971 * grouping on category pages and so on. This has to be coordinated
2972 * carefully with convertToSortkey(), or else the sorted list might jump
2973 * back and forth between the same "initial letters" or other pathological
2974 * behavior. For instance, if you just return the first character, but "a"
2975 * sorts the same as "A" based on convertToSortkey(), then you might get a
2987 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2989 * @param string $string UTF-8 string
2990 * @return string UTF-8 string corresponding to the first letter of input
2992 public function firstLetterForLists( $string ) {
2993 if ( $string[0] == "\0" ) {
2994 $string = substr( $string, 1 );
2996 return strtoupper( $this->firstChar( $string ) );