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 getDefaultVariant() { return $this->mLang
->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
60 * Internationalisation code
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
135 * @param $code String
138 static function factory( $code ) {
139 if ( !isset( self
::$mLangObjCache[$code] ) ) {
140 if ( count( self
::$mLangObjCache ) > 10 ) {
141 // Don't keep a billion objects around, that's stupid.
142 self
::$mLangObjCache = array();
144 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
146 return self
::$mLangObjCache[$code];
150 * Create a language object for a given language code
151 * @param $code String
154 protected static function newFromCode( $code ) {
156 static $recursionLevel = 0;
157 if ( $code == 'en' ) {
160 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
161 // Preload base classes to work around APC/PHP5 bug
162 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
163 include_once( "$IP/languages/classes/$class.deps.php" );
165 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
166 include_once( "$IP/languages/classes/$class.php" );
170 if ( $recursionLevel > 5 ) {
171 throw new MWException( "Language fallback loop detected when creating class $class\n" );
174 if ( !class_exists( $class ) ) {
175 $fallback = Language
::getFallbackFor( $code );
177 $lang = Language
::newFromCode( $fallback );
179 $lang->setCode( $code );
187 * Get the LocalisationCache instance
189 public static function getLocalisationCache() {
190 if ( is_null( self
::$dataCache ) ) {
191 global $wgLocalisationCacheConf;
192 $class = $wgLocalisationCacheConf['class'];
193 self
::$dataCache = new $class( $wgLocalisationCacheConf );
195 return self
::$dataCache;
198 function __construct() {
199 $this->mConverter
= new FakeConverter( $this );
200 // Set the code to the name of the descendant
201 if ( get_class( $this ) == 'Language' ) {
204 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
206 self
::getLocalisationCache();
210 * Reduce memory usage
212 function __destruct() {
213 foreach ( $this as $name => $value ) {
214 unset( $this->$name );
219 * Hook which will be called if this is the content language.
220 * Descendants can use this to register hook functions or modify globals
222 function initContLang() { }
225 * @deprecated Use User::getDefaultOptions()
228 function getDefaultUserOptions() {
229 wfDeprecated( __METHOD__
);
230 return User
::getDefaultOptions();
233 function getFallbackLanguageCode() {
234 if ( $this->mCode
=== 'en' ) {
237 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
242 * Exports $wgBookstoreListEn
245 function getBookstoreList() {
246 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
252 function getNamespaces() {
253 if ( is_null( $this->namespaceNames
) ) {
254 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
256 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
257 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
259 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
261 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
262 if ( $wgMetaNamespaceTalk ) {
263 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
265 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
266 $this->namespaceNames
[NS_PROJECT_TALK
] =
267 $this->fixVariableInNamespace( $talk );
270 # Sometimes a language will be localised but not actually exist on this wiki.
271 foreach( $this->namespaceNames
as $key => $text ) {
272 if ( !isset( $validNamespaces[$key] ) ) {
273 unset( $this->namespaceNames
[$key] );
277 # The above mixing may leave namespaces out of canonical order.
278 # Re-order by namespace ID number...
279 ksort( $this->namespaceNames
);
281 return $this->namespaceNames
;
285 * A convenience function that returns the same thing as
286 * getNamespaces() except with the array values changed to ' '
287 * where it found '_', useful for producing output to be displayed
288 * e.g. in <select> forms.
292 function getFormattedNamespaces() {
293 $ns = $this->getNamespaces();
294 foreach ( $ns as $k => $v ) {
295 $ns[$k] = strtr( $v, '_', ' ' );
301 * Get a namespace value by key
303 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
304 * echo $mw_ns; // prints 'MediaWiki'
307 * @param $index Int: the array key of the namespace to return
308 * @return mixed, string if the namespace value exists, otherwise false
310 function getNsText( $index ) {
311 $ns = $this->getNamespaces();
312 return isset( $ns[$index] ) ?
$ns[$index] : false;
316 * A convenience function that returns the same thing as
317 * getNsText() except with '_' changed to ' ', useful for
322 function getFormattedNsText( $index ) {
323 $ns = $this->getNsText( $index );
324 return strtr( $ns, '_', ' ' );
328 * Get a namespace key by value, case insensitive.
329 * Only matches namespace names for the current language, not the
330 * canonical ones defined in Namespace.php.
332 * @param $text String
333 * @return mixed An integer if $text is a valid value otherwise false
335 function getLocalNsIndex( $text ) {
336 $lctext = $this->lc( $text );
337 $ids = $this->getNamespaceIds();
338 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
341 function getNamespaceAliases() {
342 if ( is_null( $this->namespaceAliases
) ) {
343 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
347 foreach ( $aliases as $name => $index ) {
348 if ( $index === NS_PROJECT_TALK
) {
349 unset( $aliases[$name] );
350 $name = $this->fixVariableInNamespace( $name );
351 $aliases[$name] = $index;
355 $this->namespaceAliases
= $aliases;
357 return $this->namespaceAliases
;
360 function getNamespaceIds() {
361 if ( is_null( $this->mNamespaceIds
) ) {
362 global $wgNamespaceAliases;
363 # Put namespace names and aliases into a hashtable.
364 # If this is too slow, then we should arrange it so that it is done
365 # before caching. The catch is that at pre-cache time, the above
366 # class-specific fixup hasn't been done.
367 $this->mNamespaceIds
= array();
368 foreach ( $this->getNamespaces() as $index => $name ) {
369 $this->mNamespaceIds
[$this->lc( $name )] = $index;
371 foreach ( $this->getNamespaceAliases() as $name => $index ) {
372 $this->mNamespaceIds
[$this->lc( $name )] = $index;
374 if ( $wgNamespaceAliases ) {
375 foreach ( $wgNamespaceAliases as $name => $index ) {
376 $this->mNamespaceIds
[$this->lc( $name )] = $index;
380 return $this->mNamespaceIds
;
385 * Get a namespace key by value, case insensitive. Canonical namespace
386 * names override custom ones defined for the current language.
388 * @param $text String
389 * @return mixed An integer if $text is a valid value otherwise false
391 function getNsIndex( $text ) {
392 $lctext = $this->lc( $text );
393 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
396 $ids = $this->getNamespaceIds();
397 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
401 * short names for language variants used for language conversion links.
403 * @param $code String
406 function getVariantname( $code ) {
407 return $this->getMessageFromDB( "variantname-$code" );
410 function specialPage( $name ) {
411 $aliases = $this->getSpecialPageAliases();
412 if ( isset( $aliases[$name][0] ) ) {
413 $name = $aliases[$name][0];
415 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
418 function getQuickbarSettings() {
420 $this->getMessage( 'qbsettings-none' ),
421 $this->getMessage( 'qbsettings-fixedleft' ),
422 $this->getMessage( 'qbsettings-fixedright' ),
423 $this->getMessage( 'qbsettings-floatingleft' ),
424 $this->getMessage( 'qbsettings-floatingright' )
428 function getMathNames() {
429 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
432 function getDatePreferences() {
433 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
436 function getDateFormats() {
437 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
440 function getDefaultDateFormat() {
441 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
442 if ( $df === 'dmy or mdy' ) {
443 global $wgAmericanDates;
444 return $wgAmericanDates ?
'mdy' : 'dmy';
450 function getDatePreferenceMigrationMap() {
451 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
454 function getImageFile( $image ) {
455 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
458 function getDefaultUserOptionOverrides() {
459 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
462 function getExtraUserToggles() {
463 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
466 function getUserToggle( $tog ) {
467 return $this->getMessageFromDB( "tog-$tog" );
471 * Get language names, indexed by code.
472 * If $customisedOnly is true, only returns codes with a messages file
474 public static function getLanguageNames( $customisedOnly = false ) {
475 global $wgLanguageNames, $wgExtraLanguageNames;
476 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
477 if ( !$customisedOnly ) {
483 $dir = opendir( "$IP/languages/messages" );
484 while ( false !== ( $file = readdir( $dir ) ) ) {
485 $code = self
::getCodeFromFileName( $file, 'Messages' );
486 if ( $code && isset( $allNames[$code] ) ) {
487 $names[$code] = $allNames[$code];
495 * Get translated language names. This is done on best effort and
496 * by default this is exactly the same as Language::getLanguageNames.
497 * The CLDR extension provides translated names.
498 * @param $code String Language code.
499 * @return Array language code => language name
502 public static function getTranslatedLanguageNames( $code ) {
504 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
506 foreach ( self
::getLanguageNames() as $code => $name ) {
507 if ( !isset( $names[$code] ) ) $names[$code] = $name;
514 * Get a message from the MediaWiki namespace.
516 * @param $msg String: message name
519 function getMessageFromDB( $msg ) {
520 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
523 function getLanguageName( $code ) {
524 $names = self
::getLanguageNames();
525 if ( !array_key_exists( $code, $names ) ) {
528 return $names[$code];
531 function getMonthName( $key ) {
532 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
535 function getMonthNameGen( $key ) {
536 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
539 function getMonthAbbreviation( $key ) {
540 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
543 function getWeekdayName( $key ) {
544 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
547 function getWeekdayAbbreviation( $key ) {
548 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
551 function getIranianCalendarMonthName( $key ) {
552 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
555 function getHebrewCalendarMonthName( $key ) {
556 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
559 function getHebrewCalendarMonthNameGen( $key ) {
560 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
563 function getHijriCalendarMonthName( $key ) {
564 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
568 * Used by date() and time() to adjust the time output.
570 * @param $ts Int the time in date('YmdHis') format
571 * @param $tz Mixed: adjust the time by this amount (default false, mean we
572 * get user timecorrection setting)
575 function userAdjust( $ts, $tz = false ) {
576 global $wgUser, $wgLocalTZoffset;
578 if ( $tz === false ) {
579 $tz = $wgUser->getOption( 'timecorrection' );
582 $data = explode( '|', $tz, 3 );
584 if ( $data[0] == 'ZoneInfo' ) {
585 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
586 $date = date_create( $ts, timezone_open( 'UTC' ) );
587 date_timezone_set( $date, timezone_open( $data[2] ) );
588 $date = date_format( $date, 'YmdHis' );
591 # Unrecognized timezone, default to 'Offset' with the stored offset.
596 if ( $data[0] == 'System' ||
$tz == '' ) {
597 # Global offset in minutes.
598 if ( isset( $wgLocalTZoffset ) ) {
599 $minDiff = $wgLocalTZoffset;
601 } else if ( $data[0] == 'Offset' ) {
602 $minDiff = intval( $data[1] );
604 $data = explode( ':', $tz );
605 if ( count( $data ) == 2 ) {
606 $data[0] = intval( $data[0] );
607 $data[1] = intval( $data[1] );
608 $minDiff = abs( $data[0] ) * 60 +
$data[1];
609 if ( $data[0] < 0 ) {
610 $minDiff = -$minDiff;
613 $minDiff = intval( $data[0] ) * 60;
617 # No difference ? Return time unchanged
618 if ( 0 == $minDiff ) {
622 wfSuppressWarnings(); // E_STRICT system time bitching
623 # Generate an adjusted date; take advantage of the fact that mktime
624 # will normalize out-of-range values so we don't have to split $minDiff
625 # into hours and minutes.
627 (int)substr( $ts, 8, 2 ) ), # Hours
628 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
629 (int)substr( $ts, 12, 2 ), # Seconds
630 (int)substr( $ts, 4, 2 ), # Month
631 (int)substr( $ts, 6, 2 ), # Day
632 (int)substr( $ts, 0, 4 ) ); # Year
634 $date = date( 'YmdHis', $t );
641 * This is a workalike of PHP's date() function, but with better
642 * internationalisation, a reduced set of format characters, and a better
645 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
646 * PHP manual for definitions. There are a number of extensions, which
649 * xn Do not translate digits of the next numeric format character
650 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
651 * xr Use roman numerals for the next numeric format character
652 * xh Use hebrew numerals for the next numeric format character
654 * xg Genitive month name
656 * xij j (day number) in Iranian calendar
657 * xiF F (month name) in Iranian calendar
658 * xin n (month number) in Iranian calendar
659 * xiY Y (full year) in Iranian calendar
661 * xjj j (day number) in Hebrew calendar
662 * xjF F (month name) in Hebrew calendar
663 * xjt t (days in month) in Hebrew calendar
664 * xjx xg (genitive month name) in Hebrew calendar
665 * xjn n (month number) in Hebrew calendar
666 * xjY Y (full year) in Hebrew calendar
668 * xmj j (day number) in Hijri calendar
669 * xmF F (month name) in Hijri calendar
670 * xmn n (month number) in Hijri calendar
671 * xmY Y (full year) in Hijri calendar
673 * xkY Y (full year) in Thai solar calendar. Months and days are
674 * identical to the Gregorian calendar
675 * xoY Y (full year) in Minguo calendar or Juche year.
676 * Months and days are identical to the
678 * xtY Y (full year) in Japanese nengo. Months and days are
679 * identical to the Gregorian calendar
681 * Characters enclosed in double quotes will be considered literal (with
682 * the quotes themselves removed). Unmatched quotes will be considered
683 * literal quotes. Example:
685 * "The month is" F => The month is January
688 * Backslash escaping is also supported.
690 * Input timestamp is assumed to be pre-normalized to the desired local
693 * @param $format String
694 * @param $ts String: 14-character timestamp
697 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
699 function sprintfDate( $format, $ts ) {
712 for ( $p = 0; $p < strlen( $format ); $p++
) {
715 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
716 $code .= $format[++
$p];
719 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
720 $code .= $format[++
$p];
731 $rawToggle = !$rawToggle;
740 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
743 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
744 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
747 $num = substr( $ts, 6, 2 );
750 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
751 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
754 $num = intval( substr( $ts, 6, 2 ) );
758 $iranian = self
::tsToIranian( $ts );
764 $hijri = self
::tsToHijri( $ts );
770 $hebrew = self
::tsToHebrew( $ts );
776 $unix = wfTimestamp( TS_UNIX
, $ts );
778 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
782 $unix = wfTimestamp( TS_UNIX
, $ts );
784 $w = gmdate( 'w', $unix );
789 $unix = wfTimestamp( TS_UNIX
, $ts );
791 $num = gmdate( 'w', $unix );
795 $unix = wfTimestamp( TS_UNIX
, $ts );
797 $num = gmdate( 'z', $unix );
801 $unix = wfTimestamp( TS_UNIX
, $ts );
803 $num = gmdate( 'W', $unix );
806 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
810 $iranian = self
::tsToIranian( $ts );
812 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
816 $hijri = self
::tsToHijri( $ts );
818 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
822 $hebrew = self
::tsToHebrew( $ts );
824 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
827 $num = substr( $ts, 4, 2 );
830 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
833 $num = intval( substr( $ts, 4, 2 ) );
837 $iranian = self
::tsToIranian( $ts );
843 $hijri = self
::tsToHijri ( $ts );
849 $hebrew = self
::tsToHebrew( $ts );
855 $unix = wfTimestamp( TS_UNIX
, $ts );
857 $num = gmdate( 't', $unix );
861 $hebrew = self
::tsToHebrew( $ts );
867 $unix = wfTimestamp( TS_UNIX
, $ts );
869 $num = gmdate( 'L', $unix );
873 $unix = wfTimestamp( TS_UNIX
, $ts );
875 $num = date( 'o', $unix );
878 $num = substr( $ts, 0, 4 );
882 $iranian = self
::tsToIranian( $ts );
888 $hijri = self
::tsToHijri( $ts );
894 $hebrew = self
::tsToHebrew( $ts );
900 $thai = self
::tsToYear( $ts, 'thai' );
906 $minguo = self
::tsToYear( $ts, 'minguo' );
912 $tenno = self
::tsToYear( $ts, 'tenno' );
917 $num = substr( $ts, 2, 2 );
920 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
923 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
926 $h = substr( $ts, 8, 2 );
927 $num = $h %
12 ?
$h %
12 : 12;
930 $num = intval( substr( $ts, 8, 2 ) );
933 $h = substr( $ts, 8, 2 );
934 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
937 $num = substr( $ts, 8, 2 );
940 $num = substr( $ts, 10, 2 );
943 $num = substr( $ts, 12, 2 );
947 $unix = wfTimestamp( TS_UNIX
, $ts );
949 $s .= gmdate( 'c', $unix );
953 $unix = wfTimestamp( TS_UNIX
, $ts );
955 $s .= gmdate( 'r', $unix );
959 $unix = wfTimestamp( TS_UNIX
, $ts );
965 if ( $p < strlen( $format ) - 1 ) {
973 if ( $p < strlen( $format ) - 1 ) {
974 $endQuote = strpos( $format, '"', $p +
1 );
975 if ( $endQuote === false ) {
976 # No terminating quote, assume literal "
979 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
983 # Quote at end of string, assume literal "
990 if ( $num !== false ) {
991 if ( $rawToggle ||
$raw ) {
994 } elseif ( $roman ) {
995 $s .= self
::romanNumeral( $num );
997 } elseif ( $hebrewNum ) {
998 $s .= self
::hebrewNumeral( $num );
1001 $s .= $this->formatNum( $num, true );
1008 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1009 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1011 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1012 * Gregorian dates to Iranian dates. Originally written in C, it
1013 * is released under the terms of GNU Lesser General Public
1014 * License. Conversion to PHP was performed by Niklas Laxström.
1016 * Link: http://www.farsiweb.info/jalali/jalali.c
1018 private static function tsToIranian( $ts ) {
1019 $gy = substr( $ts, 0, 4 ) -1600;
1020 $gm = substr( $ts, 4, 2 ) -1;
1021 $gd = substr( $ts, 6, 2 ) -1;
1023 # Days passed from the beginning (including leap years)
1025 +
floor( ( $gy +
3 ) / 4 )
1026 - floor( ( $gy +
99 ) / 100 )
1027 +
floor( ( $gy +
399 ) / 400 );
1030 // Add days of the past months of this year
1031 for ( $i = 0; $i < $gm; $i++
) {
1032 $gDayNo +
= self
::$GREG_DAYS[$i];
1036 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1040 // Days passed in current month
1043 $jDayNo = $gDayNo - 79;
1045 $jNp = floor( $jDayNo / 12053 );
1048 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1051 if ( $jDayNo >= 366 ) {
1052 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1053 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1056 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1057 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1063 return array( $jy, $jm, $jd );
1067 * Converting Gregorian dates to Hijri dates.
1069 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1071 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1073 private static function tsToHijri( $ts ) {
1074 $year = substr( $ts, 0, 4 );
1075 $month = substr( $ts, 4, 2 );
1076 $day = substr( $ts, 6, 2 );
1084 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1085 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1088 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1089 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1090 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1093 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1094 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1097 $zl = $zjd -1948440 +
10632;
1098 $zn = (int)( ( $zl - 1 ) / 10631 );
1099 $zl = $zl - 10631 * $zn +
354;
1100 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1101 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1102 $zm = (int)( ( 24 * $zl ) / 709 );
1103 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1104 $zy = 30 * $zn +
$zj - 30;
1106 return array( $zy, $zm, $zd );
1110 * Converting Gregorian dates to Hebrew dates.
1112 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1113 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1114 * to translate the relevant functions into PHP and release them under
1117 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1118 * and Adar II is 14. In a non-leap year, Adar is 6.
1120 private static function tsToHebrew( $ts ) {
1122 $year = substr( $ts, 0, 4 );
1123 $month = substr( $ts, 4, 2 );
1124 $day = substr( $ts, 6, 2 );
1126 # Calculate Hebrew year
1127 $hebrewYear = $year +
3760;
1129 # Month number when September = 1, August = 12
1131 if ( $month > 12 ) {
1138 # Calculate day of year from 1 September
1140 for ( $i = 1; $i < $month; $i++
) {
1144 # Check if the year is leap
1145 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1148 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1155 # Calculate the start of the Hebrew year
1156 $start = self
::hebrewYearStart( $hebrewYear );
1158 # Calculate next year's start
1159 if ( $dayOfYear <= $start ) {
1160 # Day is before the start of the year - it is the previous year
1162 $nextStart = $start;
1166 # Add days since previous year's 1 September
1168 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1172 # Start of the new (previous) year
1173 $start = self
::hebrewYearStart( $hebrewYear );
1176 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1179 # Calculate Hebrew day of year
1180 $hebrewDayOfYear = $dayOfYear - $start;
1182 # Difference between year's days
1183 $diff = $nextStart - $start;
1184 # Add 12 (or 13 for leap years) days to ignore the difference between
1185 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1186 # difference is only about the year type
1187 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1193 # Check the year pattern, and is leap year
1194 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1195 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1196 # and non-leap years
1197 $yearPattern = $diff %
30;
1198 # Check if leap year
1199 $isLeap = $diff >= 30;
1201 # Calculate day in the month from number of day in the Hebrew year
1202 # Don't check Adar - if the day is not in Adar, we will stop before;
1203 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1204 $hebrewDay = $hebrewDayOfYear;
1207 while ( $hebrewMonth <= 12 ) {
1208 # Calculate days in this month
1209 if ( $isLeap && $hebrewMonth == 6 ) {
1210 # Adar in a leap year
1212 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1214 if ( $hebrewDay <= $days ) {
1218 # Subtract the days of Adar I
1219 $hebrewDay -= $days;
1222 if ( $hebrewDay <= $days ) {
1228 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1229 # Cheshvan in a complete year (otherwise as the rule below)
1231 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1232 # Kislev in an incomplete year (otherwise as the rule below)
1235 # Odd months have 30 days, even have 29
1236 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1238 if ( $hebrewDay <= $days ) {
1239 # In the current month
1242 # Subtract the days of the current month
1243 $hebrewDay -= $days;
1244 # Try in the next month
1249 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1253 * This calculates the Hebrew year start, as days since 1 September.
1254 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1255 * Used for Hebrew date.
1257 private static function hebrewYearStart( $year ) {
1258 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1259 $b = intval( ( $year - 1 ) %
4 );
1260 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1264 $Mar = intval( $m );
1270 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1271 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1273 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1275 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1279 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1284 * Algorithm to convert Gregorian dates to Thai solar dates,
1285 * Minguo dates or Minguo dates.
1287 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1288 * http://en.wikipedia.org/wiki/Minguo_calendar
1289 * http://en.wikipedia.org/wiki/Japanese_era_name
1291 * @param $ts String: 14-character timestamp
1292 * @param $cName String: calender name
1293 * @return Array: converted year, month, day
1295 private static function tsToYear( $ts, $cName ) {
1296 $gy = substr( $ts, 0, 4 );
1297 $gm = substr( $ts, 4, 2 );
1298 $gd = substr( $ts, 6, 2 );
1300 if ( !strcmp( $cName, 'thai' ) ) {
1302 # Add 543 years to the Gregorian calendar
1303 # Months and days are identical
1304 $gy_offset = $gy +
543;
1305 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1307 # Deduct 1911 years from the Gregorian calendar
1308 # Months and days are identical
1309 $gy_offset = $gy - 1911;
1310 } else if ( !strcmp( $cName, 'tenno' ) ) {
1311 # Nengō dates up to Meiji period
1312 # Deduct years from the Gregorian calendar
1313 # depending on the nengo periods
1314 # Months and days are identical
1315 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1317 $gy_gannen = $gy - 1868 +
1;
1318 $gy_offset = $gy_gannen;
1319 if ( $gy_gannen == 1 ) {
1322 $gy_offset = '明治' . $gy_offset;
1324 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1325 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1326 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1327 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1328 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1332 $gy_gannen = $gy - 1912 +
1;
1333 $gy_offset = $gy_gannen;
1334 if ( $gy_gannen == 1 ) {
1337 $gy_offset = '大正' . $gy_offset;
1339 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1340 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1341 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1345 $gy_gannen = $gy - 1926 +
1;
1346 $gy_offset = $gy_gannen;
1347 if ( $gy_gannen == 1 ) {
1350 $gy_offset = '昭和' . $gy_offset;
1353 $gy_gannen = $gy - 1989 +
1;
1354 $gy_offset = $gy_gannen;
1355 if ( $gy_gannen == 1 ) {
1358 $gy_offset = '平成' . $gy_offset;
1364 return array( $gy_offset, $gm, $gd );
1368 * Roman number formatting up to 3000
1370 static function romanNumeral( $num ) {
1371 static $table = array(
1372 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1373 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1374 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1375 array( '', 'M', 'MM', 'MMM' )
1378 $num = intval( $num );
1379 if ( $num > 3000 ||
$num <= 0 ) {
1384 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1385 if ( $num >= $pow10 ) {
1386 $s .= $table[$i][floor( $num / $pow10 )];
1388 $num = $num %
$pow10;
1394 * Hebrew Gematria number formatting up to 9999
1396 static function hebrewNumeral( $num ) {
1397 static $table = array(
1398 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1399 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1400 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1401 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1404 $num = intval( $num );
1405 if ( $num > 9999 ||
$num <= 0 ) {
1410 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1411 if ( $num >= $pow10 ) {
1412 if ( $num == 15 ||
$num == 16 ) {
1413 $s .= $table[0][9] . $table[0][$num - 9];
1416 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1417 if ( $pow10 == 1000 ) {
1422 $num = $num %
$pow10;
1424 if ( strlen( $s ) == 2 ) {
1427 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1428 $str .= substr( $s, strlen( $s ) - 2, 2 );
1430 $start = substr( $str, 0, strlen( $str ) - 2 );
1431 $end = substr( $str, strlen( $str ) - 2 );
1434 $str = $start . 'ך';
1437 $str = $start . 'ם';
1440 $str = $start . 'ן';
1443 $str = $start . 'ף';
1446 $str = $start . 'ץ';
1453 * This is meant to be used by time(), date(), and timeanddate() to get
1454 * the date preference they're supposed to use, it should be used in
1458 * function timeanddate([...], $format = true) {
1459 * $datePreference = $this->dateFormat($format);
1464 * @param $usePrefs Mixed: if true, the user's preference is used
1465 * if false, the site/language default is used
1466 * if int/string, assumed to be a format.
1469 function dateFormat( $usePrefs = true ) {
1472 if ( is_bool( $usePrefs ) ) {
1474 $datePreference = $wgUser->getDatePreference();
1476 $datePreference = (string)User
::getDefaultOption( 'date' );
1479 $datePreference = (string)$usePrefs;
1483 if ( $datePreference == '' ) {
1487 return $datePreference;
1491 * Get a format string for a given type and preference
1492 * @param $type May be date, time or both
1493 * @param $pref The format name as it appears in Messages*.php
1495 function getDateFormatString( $type, $pref ) {
1496 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1497 if ( $pref == 'default' ) {
1498 $pref = $this->getDefaultDateFormat();
1499 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1501 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1502 if ( is_null( $df ) ) {
1503 $pref = $this->getDefaultDateFormat();
1504 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1507 $this->dateFormatStrings
[$type][$pref] = $df;
1509 return $this->dateFormatStrings
[$type][$pref];
1513 * @param $ts Mixed: the time format which needs to be turned into a
1514 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1515 * @param $adj Bool: whether to adjust the time output according to the
1516 * user configured offset ($timecorrection)
1517 * @param $format Mixed: true to use user's date format preference
1518 * @param $timecorrection String: the time offset as returned by
1519 * validateTimeZone() in Special:Preferences
1522 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1523 $ts = wfTimestamp( TS_MW
, $ts );
1525 $ts = $this->userAdjust( $ts, $timecorrection );
1527 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1528 return $this->sprintfDate( $df, $ts );
1532 * @param $ts Mixed: the time format which needs to be turned into a
1533 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1534 * @param $adj Bool: whether to adjust the time output according to the
1535 * user configured offset ($timecorrection)
1536 * @param $format Mixed: true to use user's date format preference
1537 * @param $timecorrection String: the time offset as returned by
1538 * validateTimeZone() in Special:Preferences
1541 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1542 $ts = wfTimestamp( TS_MW
, $ts );
1544 $ts = $this->userAdjust( $ts, $timecorrection );
1546 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1547 return $this->sprintfDate( $df, $ts );
1551 * @param $ts Mixed: the time format which needs to be turned into a
1552 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1553 * @param $adj Bool: whether to adjust the time output according to the
1554 * user configured offset ($timecorrection)
1555 * @param $format Mixed: what format to return, if it's false output the
1556 * default one (default true)
1557 * @param $timecorrection String: the time offset as returned by
1558 * validateTimeZone() in Special:Preferences
1561 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1562 $ts = wfTimestamp( TS_MW
, $ts );
1564 $ts = $this->userAdjust( $ts, $timecorrection );
1566 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1567 return $this->sprintfDate( $df, $ts );
1570 function getMessage( $key ) {
1571 // Don't change getPreferredVariant() to getCode() / mCode, because:
1573 // 1. Some language like Chinese has multiple variant languages. Only
1574 // getPreferredVariant() (in LanguageConverter) could return a
1575 // sub-language which would be more suitable for the user.
1576 // 2. To languages without multiple variants, getPreferredVariant()
1577 // (in FakeConverter) functions exactly same as getCode() / mCode,
1578 // it won't break anything.
1581 return self
::$dataCache->getSubitem( $this->getPreferredVariant(), 'messages', $key );
1584 function getAllMessages() {
1585 return self
::$dataCache->getItem( $this->getPreferredVariant(), 'messages' );
1588 function iconv( $in, $out, $string ) {
1589 # This is a wrapper for iconv in all languages except esperanto,
1590 # which does some nasty x-conversions beforehand
1592 # Even with //IGNORE iconv can whine about illegal characters in
1593 # *input* string. We just ignore those too.
1594 # REF: http://bugs.php.net/bug.php?id=37166
1595 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1596 wfSuppressWarnings();
1597 $text = iconv( $in, $out . '//IGNORE', $string );
1598 wfRestoreWarnings();
1602 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1603 function ucwordbreaksCallbackAscii( $matches ) {
1604 return $this->ucfirst( $matches[1] );
1607 function ucwordbreaksCallbackMB( $matches ) {
1608 return mb_strtoupper( $matches[0] );
1611 function ucCallback( $matches ) {
1612 list( $wikiUpperChars ) = self
::getCaseMaps();
1613 return strtr( $matches[1], $wikiUpperChars );
1616 function lcCallback( $matches ) {
1617 list( , $wikiLowerChars ) = self
::getCaseMaps();
1618 return strtr( $matches[1], $wikiLowerChars );
1621 function ucwordsCallbackMB( $matches ) {
1622 return mb_strtoupper( $matches[0] );
1625 function ucwordsCallbackWiki( $matches ) {
1626 list( $wikiUpperChars ) = self
::getCaseMaps();
1627 return strtr( $matches[0], $wikiUpperChars );
1631 * Make a string's first character uppercase
1633 function ucfirst( $str ) {
1635 if ( $o < 96 ) { // if already uppercase...
1637 } elseif ( $o < 128 ) {
1638 return ucfirst( $str ); // use PHP's ucfirst()
1640 // fall back to more complex logic in case of multibyte strings
1641 return $this->uc( $str, true );
1646 * Convert a string to uppercase
1648 function uc( $str, $first = false ) {
1649 if ( function_exists( 'mb_strtoupper' ) ) {
1651 if ( $this->isMultibyte( $str ) ) {
1652 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1654 return ucfirst( $str );
1657 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1660 if ( $this->isMultibyte( $str ) ) {
1661 $x = $first ?
'^' : '';
1662 return preg_replace_callback(
1663 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1664 array( $this, 'ucCallback' ),
1668 return $first ?
ucfirst( $str ) : strtoupper( $str );
1673 function lcfirst( $str ) {
1676 return strval( $str );
1677 } elseif ( $o >= 128 ) {
1678 return $this->lc( $str, true );
1679 } elseif ( $o > 96 ) {
1682 $str[0] = strtolower( $str[0] );
1687 function lc( $str, $first = false ) {
1688 if ( function_exists( 'mb_strtolower' ) ) {
1690 if ( $this->isMultibyte( $str ) ) {
1691 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1693 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1696 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1699 if ( $this->isMultibyte( $str ) ) {
1700 $x = $first ?
'^' : '';
1701 return preg_replace_callback(
1702 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1703 array( $this, 'lcCallback' ),
1707 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1712 function isMultibyte( $str ) {
1713 return (bool)preg_match( '/[\x80-\xff]/', $str );
1716 function ucwords( $str ) {
1717 if ( $this->isMultibyte( $str ) ) {
1718 $str = $this->lc( $str );
1720 // regexp to find first letter in each word (i.e. after each space)
1721 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1723 // function to use to capitalize a single char
1724 if ( function_exists( 'mb_strtoupper' ) ) {
1725 return preg_replace_callback(
1727 array( $this, 'ucwordsCallbackMB' ),
1731 return preg_replace_callback(
1733 array( $this, 'ucwordsCallbackWiki' ),
1738 return ucwords( strtolower( $str ) );
1742 # capitalize words at word breaks
1743 function ucwordbreaks( $str ) {
1744 if ( $this->isMultibyte( $str ) ) {
1745 $str = $this->lc( $str );
1747 // since \b doesn't work for UTF-8, we explicitely define word break chars
1748 $breaks = "[ \-\(\)\}\{\.,\?!]";
1750 // find first letter after word break
1751 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1753 if ( function_exists( 'mb_strtoupper' ) ) {
1754 return preg_replace_callback(
1756 array( $this, 'ucwordbreaksCallbackMB' ),
1760 return preg_replace_callback(
1762 array( $this, 'ucwordsCallbackWiki' ),
1767 return preg_replace_callback(
1768 '/\b([\w\x80-\xff]+)\b/',
1769 array( $this, 'ucwordbreaksCallbackAscii' ),
1776 * Return a case-folded representation of $s
1778 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1779 * and $s2 are the same except for the case of their characters. It is not
1780 * necessary for the value returned to make sense when displayed.
1782 * Do *not* perform any other normalisation in this function. If a caller
1783 * uses this function when it should be using a more general normalisation
1784 * function, then fix the caller.
1786 function caseFold( $s ) {
1787 return $this->uc( $s );
1790 function checkTitleEncoding( $s ) {
1791 if ( is_array( $s ) ) {
1792 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1794 # Check for non-UTF-8 URLs
1795 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1800 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1801 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1806 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1809 function fallback8bitEncoding() {
1810 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1814 * Most writing systems use whitespace to break up words.
1815 * Some languages such as Chinese don't conventionally do this,
1816 * which requires special handling when breaking up words for
1819 function hasWordBreaks() {
1824 * Some languages such as Chinese require word segmentation,
1825 * Specify such segmentation when overridden in derived class.
1827 * @param $string String
1830 function segmentByWord( $string ) {
1835 * Some languages have special punctuation need to be normalized.
1836 * Make such changes here.
1838 * @param $string String
1841 function normalizeForSearch( $string ) {
1842 return self
::convertDoubleWidth( $string );
1846 * convert double-width roman characters to single-width.
1847 * range: ff00-ff5f ~= 0020-007f
1849 protected static function convertDoubleWidth( $string ) {
1850 static $full = null;
1851 static $half = null;
1853 if ( $full === null ) {
1854 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1855 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1856 $full = str_split( $fullWidth, 3 );
1857 $half = str_split( $halfWidth );
1860 $string = str_replace( $full, $half, $string );
1864 protected static function insertSpace( $string, $pattern ) {
1865 $string = preg_replace( $pattern, " $1 ", $string );
1866 $string = preg_replace( '/ +/', ' ', $string );
1870 function convertForSearchResult( $termsArray ) {
1871 # some languages, e.g. Chinese, need to do a conversion
1872 # in order for search results to be displayed correctly
1877 * Get the first character of a string.
1882 function firstChar( $s ) {
1885 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1886 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1891 if ( isset( $matches[1] ) ) {
1892 if ( strlen( $matches[1] ) != 3 ) {
1896 // Break down Hangul syllables to grab the first jamo
1897 $code = utf8ToCodepoint( $matches[1] );
1898 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1900 } elseif ( $code < 0xb098 ) {
1901 return "\xe3\x84\xb1";
1902 } elseif ( $code < 0xb2e4 ) {
1903 return "\xe3\x84\xb4";
1904 } elseif ( $code < 0xb77c ) {
1905 return "\xe3\x84\xb7";
1906 } elseif ( $code < 0xb9c8 ) {
1907 return "\xe3\x84\xb9";
1908 } elseif ( $code < 0xbc14 ) {
1909 return "\xe3\x85\x81";
1910 } elseif ( $code < 0xc0ac ) {
1911 return "\xe3\x85\x82";
1912 } elseif ( $code < 0xc544 ) {
1913 return "\xe3\x85\x85";
1914 } elseif ( $code < 0xc790 ) {
1915 return "\xe3\x85\x87";
1916 } elseif ( $code < 0xcc28 ) {
1917 return "\xe3\x85\x88";
1918 } elseif ( $code < 0xce74 ) {
1919 return "\xe3\x85\x8a";
1920 } elseif ( $code < 0xd0c0 ) {
1921 return "\xe3\x85\x8b";
1922 } elseif ( $code < 0xd30c ) {
1923 return "\xe3\x85\x8c";
1924 } elseif ( $code < 0xd558 ) {
1925 return "\xe3\x85\x8d";
1927 return "\xe3\x85\x8e";
1934 function initEncoding() {
1935 # Some languages may have an alternate char encoding option
1936 # (Esperanto X-coding, Japanese furigana conversion, etc)
1937 # If this language is used as the primary content language,
1938 # an override to the defaults can be set here on startup.
1941 function recodeForEdit( $s ) {
1942 # For some languages we'll want to explicitly specify
1943 # which characters make it into the edit box raw
1944 # or are converted in some way or another.
1945 # Note that if wgOutputEncoding is different from
1946 # wgInputEncoding, this text will be further converted
1947 # to wgOutputEncoding.
1948 global $wgEditEncoding;
1949 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1952 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1956 function recodeInput( $s ) {
1957 # Take the previous into account.
1958 global $wgEditEncoding;
1959 if ( $wgEditEncoding != '' ) {
1960 $enc = $wgEditEncoding;
1964 if ( $enc == 'UTF-8' ) {
1967 return $this->iconv( $enc, 'UTF-8', $s );
1972 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1973 * also cleans up certain backwards-compatible sequences, converting them
1974 * to the modern Unicode equivalent.
1976 * This is language-specific for performance reasons only.
1978 function normalize( $s ) {
1979 global $wgAllUnicodeFixes;
1980 $s = UtfNormal
::cleanUp( $s );
1981 if ( $wgAllUnicodeFixes ) {
1982 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1983 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1990 * Transform a string using serialized data stored in the given file (which
1991 * must be in the serialized subdirectory of $IP). The file contains pairs
1992 * mapping source characters to destination characters.
1994 * The data is cached in process memory. This will go faster if you have the
1995 * FastStringSearch extension.
1997 function transformUsingPairFile( $file, $string ) {
1998 if ( !isset( $this->transformData
[$file] ) ) {
1999 $data = wfGetPrecompiledData( $file );
2000 if ( $data === false ) {
2001 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2003 $this->transformData
[$file] = new ReplacementArray( $data );
2005 return $this->transformData
[$file]->replace( $string );
2009 * For right-to-left language support
2014 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2018 * Return the correct HTML 'dir' attribute value for this language.
2022 return $this->isRTL() ?
'rtl' : 'ltr';
2026 * Return 'left' or 'right' as appropriate alignment for line-start
2027 * for this language's text direction.
2029 * Should be equivalent to CSS3 'start' text-align value....
2033 function alignStart() {
2034 return $this->isRTL() ?
'right' : 'left';
2038 * Return 'right' or 'left' as appropriate alignment for line-end
2039 * for this language's text direction.
2041 * Should be equivalent to CSS3 'end' text-align value....
2045 function alignEnd() {
2046 return $this->isRTL() ?
'left' : 'right';
2050 * A hidden direction mark (LRM or RLM), depending on the language direction
2054 function getDirMark() {
2055 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2058 function capitalizeAllNouns() {
2059 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2063 * An arrow, depending on the language direction
2067 function getArrow() {
2068 return $this->isRTL() ?
'←' : '→';
2072 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2076 function linkPrefixExtension() {
2077 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2080 function getMagicWords() {
2081 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2084 # Fill a MagicWord object with data from here
2085 function getMagic( $mw ) {
2086 if ( !$this->mMagicHookDone
) {
2087 $this->mMagicHookDone
= true;
2088 wfProfileIn( 'LanguageGetMagic' );
2089 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2090 wfProfileOut( 'LanguageGetMagic' );
2092 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2093 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2095 $magicWords = $this->getMagicWords();
2096 if ( isset( $magicWords[$mw->mId
] ) ) {
2097 $rawEntry = $magicWords[$mw->mId
];
2103 if ( !is_array( $rawEntry ) ) {
2104 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2106 $mw->mCaseSensitive
= $rawEntry[0];
2107 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2112 * Add magic words to the extension array
2114 function addMagicWordsByLang( $newWords ) {
2115 $code = $this->getCode();
2116 $fallbackChain = array();
2117 while ( $code && !in_array( $code, $fallbackChain ) ) {
2118 $fallbackChain[] = $code;
2119 $code = self
::getFallbackFor( $code );
2121 if ( !in_array( 'en', $fallbackChain ) ) {
2122 $fallbackChain[] = 'en';
2124 $fallbackChain = array_reverse( $fallbackChain );
2125 foreach ( $fallbackChain as $code ) {
2126 if ( isset( $newWords[$code] ) ) {
2127 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2133 * Get special page names, as an associative array
2134 * case folded alias => real name
2136 function getSpecialPageAliases() {
2137 // Cache aliases because it may be slow to load them
2138 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2140 $this->mExtendedSpecialPageAliases
=
2141 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2142 wfRunHooks( 'LanguageGetSpecialPageAliases',
2143 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2146 return $this->mExtendedSpecialPageAliases
;
2150 * Italic is unsuitable for some languages
2152 * @param $text String: the text to be emphasized.
2155 function emphasize( $text ) {
2156 return "<em>$text</em>";
2160 * Normally we output all numbers in plain en_US style, that is
2161 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2162 * point twohundredthirtyfive. However this is not sutable for all
2163 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2164 * Icelandic just want to use commas instead of dots, and dots instead
2165 * of commas like "293.291,235".
2167 * An example of this function being called:
2169 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2172 * See LanguageGu.php for the Gujarati implementation and
2173 * $separatorTransformTable on MessageIs.php for
2174 * the , => . and . => , implementation.
2176 * @todo check if it's viable to use localeconv() for the decimal
2178 * @param $number Mixed: the string to be formatted, should be an integer
2179 * or a floating point number.
2180 * @param $nocommafy Bool: set to true for special numbers like dates
2183 function formatNum( $number, $nocommafy = false ) {
2184 global $wgTranslateNumerals;
2185 if ( !$nocommafy ) {
2186 $number = $this->commafy( $number );
2187 $s = $this->separatorTransformTable();
2189 $number = strtr( $number, $s );
2193 if ( $wgTranslateNumerals ) {
2194 $s = $this->digitTransformTable();
2196 $number = strtr( $number, $s );
2203 function parseFormattedNumber( $number ) {
2204 $s = $this->digitTransformTable();
2206 $number = strtr( $number, array_flip( $s ) );
2209 $s = $this->separatorTransformTable();
2211 $number = strtr( $number, array_flip( $s ) );
2214 $number = strtr( $number, array( ',' => '' ) );
2219 * Adds commas to a given number
2224 function commafy( $_ ) {
2225 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2228 function digitTransformTable() {
2229 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2232 function separatorTransformTable() {
2233 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2237 * Take a list of strings and build a locale-friendly comma-separated
2238 * list, using the local comma-separator message.
2239 * The last two strings are chained with an "and".
2244 function listToText( $l ) {
2246 $m = count( $l ) - 1;
2248 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2250 for ( $i = $m; $i >= 0; $i-- ) {
2253 } else if ( $i == $m - 1 ) {
2254 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2256 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2264 * Take a list of strings and build a locale-friendly comma-separated
2265 * list, using the local comma-separator message.
2266 * @param $list array of strings to put in a comma list
2269 function commaList( $list ) {
2274 array( 'parsemag', 'escapenoentities', 'language' => $this )
2280 * Take a list of strings and build a locale-friendly semicolon-separated
2281 * list, using the local semicolon-separator message.
2282 * @param $list array of strings to put in a semicolon list
2285 function semicolonList( $list ) {
2289 'semicolon-separator',
2290 array( 'parsemag', 'escapenoentities', 'language' => $this )
2296 * Same as commaList, but separate it with the pipe instead.
2297 * @param $list array of strings to put in a pipe list
2300 function pipeList( $list ) {
2305 array( 'escapenoentities', 'language' => $this )
2311 * Truncate a string to a specified length in bytes, appending an optional
2312 * string (e.g. for ellipses)
2314 * The database offers limited byte lengths for some columns in the database;
2315 * multi-byte character sets mean we need to ensure that only whole characters
2316 * are included, otherwise broken characters can be passed to the user
2318 * If $length is negative, the string will be truncated from the beginning
2320 * @param $string String to truncate
2321 * @param $length Int: maximum length (excluding ellipses)
2322 * @param $ellipsis String to append to the truncated text
2325 function truncate( $string, $length, $ellipsis = '...' ) {
2326 # Use the localized ellipsis character
2327 if ( $ellipsis == '...' ) {
2328 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2330 # Check if there is no need to truncate
2331 if ( $length == 0 ) {
2333 } elseif ( strlen( $string ) <= abs( $length ) ) {
2336 $stringOriginal = $string;
2337 if ( $length > 0 ) {
2338 $string = substr( $string, 0, $length ); // xyz...
2339 $string = $this->removeBadCharLast( $string );
2340 $string = $string . $ellipsis;
2342 $string = substr( $string, $length ); // ...xyz
2343 $string = $this->removeBadCharFirst( $string );
2344 $string = $ellipsis . $string;
2346 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2347 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2350 return $stringOriginal;
2355 * Remove bytes that represent an incomplete Unicode character
2356 * at the end of string (e.g. bytes of the char are missing)
2358 * @param $string String
2361 protected function removeBadCharLast( $string ) {
2362 $char = ord( $string[strlen( $string ) - 1] );
2364 if ( $char >= 0xc0 ) {
2365 # We got the first byte only of a multibyte char; remove it.
2366 $string = substr( $string, 0, -1 );
2367 } elseif ( $char >= 0x80 &&
2368 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2369 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2371 # We chopped in the middle of a character; remove it
2378 * Remove bytes that represent an incomplete Unicode character
2379 * at the start of string (e.g. bytes of the char are missing)
2381 * @param $string String
2384 protected function removeBadCharFirst( $string ) {
2385 $char = ord( $string[0] );
2386 if ( $char >= 0x80 && $char < 0xc0 ) {
2387 # We chopped in the middle of a character; remove the whole thing
2388 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2394 * Truncate a string of valid HTML to a specified length in bytes,
2395 * appending an optional string (e.g. for ellipses), and return valid HTML
2397 * This is only intended for styled/linked text, such as HTML with
2398 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2400 * Note: tries to fix broken HTML with MWTidy
2402 * @param string $text HTML string to truncate
2403 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2404 * @param string $ellipsis String to append to the truncated text
2407 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2408 # Use the localized ellipsis character
2409 if ( $ellipsis == '...' ) {
2410 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2412 # Check if there is no need to truncate
2413 if ( $length <= 0 ) {
2414 return $ellipsis; // no text shown, nothing to format
2415 } elseif ( strlen( $text ) <= $length ) {
2416 return $text; // string short enough even *with* HTML
2418 $text = MWTidy
::tidy( $text ); // fix tags
2419 $displayLen = 0; // innerHTML legth so far
2420 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2421 $tagType = 0; // 0-open, 1-close
2422 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2423 $entityState = 0; // 0-not entity, 1-entity
2425 $openTags = array(); // open tag stack
2426 $textLen = strlen( $text );
2427 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2429 $lastCh = $pos ?
$text[$pos - 1] : '';
2430 $ret .= $ch; // add to result string
2432 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2433 $entityState = 0; // for bad HTML
2434 $bracketState = 1; // tag started (checking for backslash)
2435 } elseif ( $ch == '>' ) {
2436 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2437 $entityState = 0; // for bad HTML
2438 $bracketState = 0; // out of brackets
2439 } elseif ( $bracketState == 1 ) {
2441 $tagType = 1; // close tag (e.g. "</span>")
2443 $tagType = 0; // open tag (e.g. "<span>")
2446 $bracketState = 2; // building tag name
2447 } elseif ( $bracketState == 2 ) {
2451 // Name found (e.g. "<a href=..."), add on tag attributes...
2452 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2454 } elseif ( $bracketState == 0 ) {
2455 if ( $entityState ) {
2458 $displayLen++
; // entity is one displayed char
2462 $entityState = 1; // entity found, (e.g. " ")
2464 $displayLen++
; // this char is displayed
2465 // Add on the other display text after this...
2466 $skipped = $this->truncate_skip(
2467 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2468 $displayLen +
= $skipped;
2473 # Consider truncation once the display length has reached the maximim.
2474 # Double-check that we're not in the middle of a bracket/entity...
2475 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2476 if ( !$testingEllipsis ) {
2477 $testingEllipsis = true;
2478 # Save where we are; we will truncate here unless
2479 # the ellipsis actually makes the string longer.
2480 $pOpenTags = $openTags; // save state
2481 $pRet = $ret; // save state
2482 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2483 # Ellipsis won't make string longer/equal, the truncation point was OK.
2484 $openTags = $pOpenTags; // reload state
2485 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2486 $ret .= $ellipsis; // add ellipsis
2491 if ( $displayLen == 0 ) {
2492 return ''; // no text shown, nothing to format
2494 // Close the last tag if left unclosed by bad HTML
2495 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2496 while ( count( $openTags ) > 0 ) {
2497 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2502 // truncateHtml() helper function
2503 // like strcspn() but adds the skipped chars to $ret
2504 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2506 if ( $start < strlen( $text ) ) {
2507 $skipCount = strcspn( $text, $search, $start, $len );
2508 $ret .= substr( $text, $start, $skipCount );
2514 * truncateHtml() helper function
2515 * (a) push or pop $tag from $openTags as needed
2516 * (b) clear $tag value
2517 * @param String &$tag Current HTML tag name we are looking at
2518 * @param int $tagType (0-open tag, 1-close tag)
2519 * @param char $lastCh Character before the '>' that ended this tag
2520 * @param array &$openTags Open tag stack (not accounting for $tag)
2522 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2523 $tag = ltrim( $tag );
2525 if ( $tagType == 0 && $lastCh != '/' ) {
2526 $openTags[] = $tag; // tag opened (didn't close itself)
2527 } else if ( $tagType == 1 ) {
2528 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2529 array_pop( $openTags ); // tag closed
2537 * Grammatical transformations, needed for inflected languages
2538 * Invoked by putting {{grammar:case|word}} in a message
2540 * @param $word string
2541 * @param $case string
2544 function convertGrammar( $word, $case ) {
2545 global $wgGrammarForms;
2546 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2547 return $wgGrammarForms[$this->getCode()][$case][$word];
2553 * Provides an alternative text depending on specified gender.
2554 * Usage {{gender:username|masculine|feminine|neutral}}.
2555 * username is optional, in which case the gender of current user is used,
2556 * but only in (some) interface messages; otherwise default gender is used.
2557 * If second or third parameter are not specified, masculine is used.
2558 * These details may be overriden per language.
2560 function gender( $gender, $forms ) {
2561 if ( !count( $forms ) ) {
2564 $forms = $this->preConvertPlural( $forms, 2 );
2565 if ( $gender === 'male' ) {
2568 if ( $gender === 'female' ) {
2571 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2575 * Plural form transformations, needed for some languages.
2576 * For example, there are 3 form of plural in Russian and Polish,
2577 * depending on "count mod 10". See [[w:Plural]]
2578 * For English it is pretty simple.
2580 * Invoked by putting {{plural:count|wordform1|wordform2}}
2581 * or {{plural:count|wordform1|wordform2|wordform3}}
2583 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2585 * @param $count Integer: non-localized number
2586 * @param $forms Array: different plural forms
2587 * @return string Correct form of plural for $count in this language
2589 function convertPlural( $count, $forms ) {
2590 if ( !count( $forms ) ) {
2593 $forms = $this->preConvertPlural( $forms, 2 );
2595 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2599 * Checks that convertPlural was given an array and pads it to requested
2600 * amound of forms by copying the last one.
2602 * @param $count Integer: How many forms should there be at least
2603 * @param $forms Array of forms given to convertPlural
2604 * @return array Padded array of forms or an exception if not an array
2606 protected function preConvertPlural( /* Array */ $forms, $count ) {
2607 while ( count( $forms ) < $count ) {
2608 $forms[] = $forms[count( $forms ) - 1];
2614 * For translating of expiry times
2615 * @param $str String: the validated block time in English
2616 * @return Somehow translated block time
2617 * @see LanguageFi.php for example implementation
2619 function translateBlockExpiry( $str ) {
2620 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2622 if ( $scBlockExpiryOptions == '-' ) {
2626 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2627 if ( strpos( $option, ':' ) === false ) {
2630 list( $show, $value ) = explode( ':', $option );
2631 if ( strcmp( $str, $value ) == 0 ) {
2632 return htmlspecialchars( trim( $show ) );
2640 * languages like Chinese need to be segmented in order for the diff
2643 * @param $text String
2646 function segmentForDiff( $text ) {
2651 * and unsegment to show the result
2653 * @param $text String
2656 function unsegmentForDiff( $text ) {
2660 # convert text to all supported variants
2661 function autoConvertToAllVariants( $text ) {
2662 return $this->mConverter
->autoConvertToAllVariants( $text );
2665 # convert text to different variants of a language.
2666 function convert( $text ) {
2667 return $this->mConverter
->convert( $text );
2670 # Convert a Title object to a string in the preferred variant
2671 function convertTitle( $title ) {
2672 return $this->mConverter
->convertTitle( $title );
2675 # Check if this is a language with variants
2676 function hasVariants() {
2677 return sizeof( $this->getVariants() ) > 1;
2680 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2681 function armourMath( $text ) {
2682 return $this->mConverter
->armourMath( $text );
2686 * Perform output conversion on a string, and encode for safe HTML output.
2687 * @param $text String text to be converted
2688 * @param $isTitle Bool whether this conversion is for the article title
2690 * @todo this should get integrated somewhere sane
2692 function convertHtml( $text, $isTitle = false ) {
2693 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2696 function convertCategoryKey( $key ) {
2697 return $this->mConverter
->convertCategoryKey( $key );
2701 * Get the list of variants supported by this language
2702 * see sample implementation in LanguageZh.php
2704 * @return array an array of language codes
2706 function getVariants() {
2707 return $this->mConverter
->getVariants();
2710 function getPreferredVariant() {
2711 return $this->mConverter
->getPreferredVariant();
2714 function getDefaultVariant() {
2715 return $this->mConverter
->getDefaultVariant();
2718 function getURLVariant() {
2719 return $this->mConverter
->getURLVariant();
2723 * If a language supports multiple variants, it is
2724 * possible that non-existing link in one variant
2725 * actually exists in another variant. this function
2726 * tries to find it. See e.g. LanguageZh.php
2728 * @param $link String: the name of the link
2729 * @param $nt Mixed: the title object of the link
2730 * @param $ignoreOtherCond Boolean: to disable other conditions when
2731 * we need to transclude a template or update a category's link
2732 * @return null the input parameters may be modified upon return
2734 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2735 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2739 * If a language supports multiple variants, converts text
2740 * into an array of all possible variants of the text:
2741 * 'variant' => text in that variant
2743 * @deprecated Use autoConvertToAllVariants()
2745 function convertLinkToAllVariants( $text ) {
2746 return $this->mConverter
->convertLinkToAllVariants( $text );
2750 * returns language specific options used by User::getPageRenderHash()
2751 * for example, the preferred language variant
2755 function getExtraHashOptions() {
2756 return $this->mConverter
->getExtraHashOptions();
2760 * For languages that support multiple variants, the title of an
2761 * article may be displayed differently in different variants. this
2762 * function returns the apporiate title defined in the body of the article.
2766 function getParsedTitle() {
2767 return $this->mConverter
->getParsedTitle();
2771 * Enclose a string with the "no conversion" tag. This is used by
2772 * various functions in the Parser
2774 * @param $text String: text to be tagged for no conversion
2776 * @return string the tagged text
2778 function markNoConversion( $text, $noParse = false ) {
2779 return $this->mConverter
->markNoConversion( $text, $noParse );
2783 * A regular expression to match legal word-trailing characters
2784 * which should be merged onto a link of the form [[foo]]bar.
2788 function linkTrail() {
2789 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2792 function getLangObj() {
2797 * Get the RFC 3066 code for this language object
2799 function getCode() {
2800 return $this->mCode
;
2803 function setCode( $code ) {
2804 $this->mCode
= $code;
2808 * Get the name of a file for a certain language code
2809 * @param $prefix string Prepend this to the filename
2810 * @param $code string Language code
2811 * @param $suffix string Append this to the filename
2812 * @return string $prefix . $mangledCode . $suffix
2814 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2815 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2819 * Get the language code from a file name. Inverse of getFileName()
2820 * @param $filename string $prefix . $languageCode . $suffix
2821 * @param $prefix string Prefix before the language code
2822 * @param $suffix string Suffix after the language code
2823 * @return Language code, or false if $prefix or $suffix isn't found
2825 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2827 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2828 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2829 if ( !count( $m ) ) {
2832 return str_replace( '_', '-', strtolower( $m[1] ) );
2835 static function getMessagesFileName( $code ) {
2837 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2840 static function getClassFileName( $code ) {
2842 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2846 * Get the fallback for a given language
2848 static function getFallbackFor( $code ) {
2849 if ( $code === 'en' ) {
2853 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2858 * Get all messages for a given language
2859 * WARNING: this may take a long time
2861 static function getMessagesFor( $code ) {
2862 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2866 * Get a message for a given language
2868 static function getMessageFor( $key, $code ) {
2869 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2872 function fixVariableInNamespace( $talk ) {
2873 if ( strpos( $talk, '$1' ) === false ) {
2877 global $wgMetaNamespace;
2878 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2880 # Allow grammar transformations
2881 # Allowing full message-style parsing would make simple requests
2882 # such as action=raw much more expensive than they need to be.
2883 # This will hopefully cover most cases.
2884 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2885 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2886 return str_replace( ' ', '_', $talk );
2889 function replaceGrammarInNamespace( $m ) {
2890 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2893 static function getCaseMaps() {
2894 static $wikiUpperChars, $wikiLowerChars;
2895 if ( isset( $wikiUpperChars ) ) {
2896 return array( $wikiUpperChars, $wikiLowerChars );
2899 wfProfileIn( __METHOD__
);
2900 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2901 if ( $arr === false ) {
2902 throw new MWException(
2903 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2905 $wikiUpperChars = $arr['wikiUpperChars'];
2906 $wikiLowerChars = $arr['wikiLowerChars'];
2907 wfProfileOut( __METHOD__
);
2908 return array( $wikiUpperChars, $wikiLowerChars );
2911 function formatTimePeriod( $seconds ) {
2912 if ( round( $seconds * 10 ) < 100 ) {
2913 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2914 } elseif ( round( $seconds ) < 60 ) {
2915 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2916 } elseif ( round( $seconds ) < 3600 ) {
2917 $minutes = floor( $seconds / 60 );
2918 $secondsPart = round( fmod( $seconds, 60 ) );
2919 if ( $secondsPart == 60 ) {
2923 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2924 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2926 $hours = floor( $seconds / 3600 );
2927 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2928 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2929 if ( $secondsPart == 60 ) {
2933 if ( $minutes == 60 ) {
2937 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2938 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2939 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2943 function formatBitrate( $bps ) {
2944 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2946 return $this->formatNum( $bps ) . $units[0];
2948 $unitIndex = floor( log10( $bps ) / 3 );
2949 $mantissa = $bps / pow( 1000, $unitIndex );
2950 if ( $mantissa < 10 ) {
2951 $mantissa = round( $mantissa, 1 );
2953 $mantissa = round( $mantissa );
2955 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2959 * Format a size in bytes for output, using an appropriate
2960 * unit (B, KB, MB or GB) according to the magnitude in question
2962 * @param $size Size to format
2963 * @return string Plain text (not HTML)
2965 function formatSize( $size ) {
2966 // For small sizes no decimal places necessary
2968 if ( $size > 1024 ) {
2969 $size = $size / 1024;
2970 if ( $size > 1024 ) {
2971 $size = $size / 1024;
2972 // For MB and bigger two decimal places are smarter
2974 if ( $size > 1024 ) {
2975 $size = $size / 1024;
2976 $msg = 'size-gigabytes';
2978 $msg = 'size-megabytes';
2981 $msg = 'size-kilobytes';
2984 $msg = 'size-bytes';
2986 $size = round( $size, $round );
2987 $text = $this->getMessageFromDB( $msg );
2988 return str_replace( '$1', $this->formatNum( $size ), $text );
2992 * Get the conversion rule title, if any.
2994 function getConvRuleTitle() {
2995 return $this->mConverter
->getConvRuleTitle();