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 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
33 function __construct( $langobj ) { $this->mLang
= $langobj; }
34 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
35 function convert( $t ) { return $t; }
36 function convertTitle( $t ) { return $t->getPrefixedText(); }
37 function getVariants() { return array( $this->mLang
->getCode() ); }
38 function getPreferredVariant() { return $this->mLang
->getCode(); }
39 function getDefaultVariant() { return $this->mLang
->getCode(); }
40 function getURLVariant() { return ''; }
41 function getConvRuleTitle() { return false; }
42 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
43 function getExtraHashOptions() { return ''; }
44 function getParsedTitle() { return ''; }
45 function markNoConversion( $text, $noParse = false ) { return $text; }
46 function convertCategoryKey( $key ) { return $key; }
47 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
48 function armourMath( $text ) { return $text; }
52 * Internationalisation code
56 var $mConverter, $mVariants, $mCode, $mLoaded = false;
57 var $mMagicExtensions = array(), $mMagicHookDone = false;
59 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
60 var $dateFormatStrings = array();
61 var $mExtendedSpecialPageAliases;
64 * ReplacementArray object caches
66 var $transformData = array();
69 * @var LocalisationCache
71 static public $dataCache;
73 static public $mLangObjCache = array();
75 static public $mWeekdayMsgs = array(
76 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
80 static public $mWeekdayAbbrevMsgs = array(
81 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
84 static public $mMonthMsgs = array(
85 'january', 'february', 'march', 'april', 'may_long', 'june',
86 'july', 'august', 'september', 'october', 'november',
89 static public $mMonthGenMsgs = array(
90 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
91 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
94 static public $mMonthAbbrevMsgs = array(
95 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
96 'sep', 'oct', 'nov', 'dec'
99 static public $mIranianCalendarMonthMsgs = array(
100 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
101 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
102 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
103 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
106 static public $mHebrewCalendarMonthMsgs = array(
107 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
108 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
109 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
110 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
111 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
114 static public $mHebrewCalendarMonthGenMsgs = array(
115 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
116 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
117 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
118 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
119 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
122 static public $mHijriCalendarMonthMsgs = array(
123 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
124 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
125 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
126 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
130 * Get a cached language object for a given language code
131 * @param $code String
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
147 * @param $code String
150 protected static function newFromCode( $code ) {
151 // Protect against path traversal below
152 if ( !Language
::isValidCode( $code )
153 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
155 throw new MWException( "Invalid language code \"$code\"" );
158 if ( !Language
::isValidBuiltInCode( $code ) ) {
159 // It's not possible to customise this code with class files, so
160 // just return a Language object. This is to support uselang= hacks.
161 $lang = new Language
;
162 $lang->setCode( $code );
166 // Check if there is a language class for the code
167 $class = self
::classFromCode( $code );
168 self
::preloadLanguageClass( $class );
169 if ( MWInit
::classExists( $class ) ) {
174 // Keep trying the fallback list until we find an existing class
175 $fallbacks = Language
::getFallbacksFor( $code );
176 foreach ( $fallbacks as $fallbackCode ) {
177 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
178 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
181 $class = self
::classFromCode( $fallbackCode );
182 self
::preloadLanguageClass( $class );
183 if ( MWInit
::classExists( $class ) ) {
184 $lang = Language
::newFromCode( $fallbackCode );
185 $lang->setCode( $code );
190 throw new MWException( "Invalid fallback sequence for language '$code'" );
194 * Returns true if a language code string is of a valid form, whether or
195 * not it exists. This includes codes which are used solely for
196 * customisation via the MediaWiki namespace.
198 * @param $code string
202 public static function isValidCode( $code ) {
204 strcspn( $code, ":/\\\000" ) === strlen( $code )
205 && !preg_match( Title
::getTitleInvalidRegex(), $code );
209 * Returns true if a language code is of a valid form for the purposes of
210 * internal customisation of MediaWiki, via Messages*.php.
212 * @param $code string
217 public static function isValidBuiltInCode( $code ) {
218 return preg_match( '/^[a-z0-9-]+$/i', $code );
223 * @return String Name of the language class
225 public static function classFromCode( $code ) {
226 if ( $code == 'en' ) {
229 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
234 * Includes language class files
236 * @param $class Name of the language class
238 public static function preloadLanguageClass( $class ) {
241 if ( $class === 'Language' ) {
245 if ( !defined( 'MW_COMPILED' ) ) {
246 // Preload base classes to work around APC/PHP5 bug
247 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
248 include_once( "$IP/languages/classes/$class.deps.php" );
250 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
251 include_once( "$IP/languages/classes/$class.php" );
257 * Get the LocalisationCache instance
259 * @return LocalisationCache
261 public static function getLocalisationCache() {
262 if ( is_null( self
::$dataCache ) ) {
263 global $wgLocalisationCacheConf;
264 $class = $wgLocalisationCacheConf['class'];
265 self
::$dataCache = new $class( $wgLocalisationCacheConf );
267 return self
::$dataCache;
270 function __construct() {
271 $this->mConverter
= new FakeConverter( $this );
272 // Set the code to the name of the descendant
273 if ( get_class( $this ) == 'Language' ) {
276 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
278 self
::getLocalisationCache();
282 * Reduce memory usage
284 function __destruct() {
285 foreach ( $this as $name => $value ) {
286 unset( $this->$name );
291 * Hook which will be called if this is the content language.
292 * Descendants can use this to register hook functions or modify globals
294 function initContLang() { }
297 * Same as getFallbacksFor for current language.
299 * @deprecated in 1.19
301 function getFallbackLanguageCode() {
302 wfDeprecated( __METHOD__
);
303 return self
::getFallbackFor( $this->mCode
);
310 function getFallbackLanguages() {
311 return self
::getFallbacksFor( $this->mCode
);
315 * Exports $wgBookstoreListEn
318 function getBookstoreList() {
319 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
325 function getNamespaces() {
326 if ( is_null( $this->namespaceNames
) ) {
327 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
329 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
330 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
332 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
334 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
335 if ( $wgMetaNamespaceTalk ) {
336 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
338 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
339 $this->namespaceNames
[NS_PROJECT_TALK
] =
340 $this->fixVariableInNamespace( $talk );
343 # Sometimes a language will be localised but not actually exist on this wiki.
344 foreach( $this->namespaceNames
as $key => $text ) {
345 if ( !isset( $validNamespaces[$key] ) ) {
346 unset( $this->namespaceNames
[$key] );
350 # The above mixing may leave namespaces out of canonical order.
351 # Re-order by namespace ID number...
352 ksort( $this->namespaceNames
);
354 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
356 return $this->namespaceNames
;
360 * A convenience function that returns the same thing as
361 * getNamespaces() except with the array values changed to ' '
362 * where it found '_', useful for producing output to be displayed
363 * e.g. in <select> forms.
367 function getFormattedNamespaces() {
368 $ns = $this->getNamespaces();
369 foreach ( $ns as $k => $v ) {
370 $ns[$k] = strtr( $v, '_', ' ' );
376 * Get a namespace value by key
378 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
379 * echo $mw_ns; // prints 'MediaWiki'
382 * @param $index Int: the array key of the namespace to return
383 * @return mixed, string if the namespace value exists, otherwise false
385 function getNsText( $index ) {
386 $ns = $this->getNamespaces();
387 return isset( $ns[$index] ) ?
$ns[$index] : false;
391 * A convenience function that returns the same thing as
392 * getNsText() except with '_' changed to ' ', useful for
395 * @param $index string
399 function getFormattedNsText( $index ) {
400 $ns = $this->getNsText( $index );
401 return strtr( $ns, '_', ' ' );
405 * Returns gender-dependent namespace alias if available.
406 * @param $index Int: namespace index
407 * @param $gender String: gender key (male, female... )
411 function getGenderNsText( $index, $gender ) {
412 global $wgExtraGenderNamespaces;
414 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
415 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
419 * Whether this language makes distinguishes genders for example in
424 function needsGenderDistinction() {
425 global $wgExtraGenderNamespaces;
426 $aliases = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
427 return count( $aliases ) > 0;
431 * Get a namespace key by value, case insensitive.
432 * Only matches namespace names for the current language, not the
433 * canonical ones defined in Namespace.php.
435 * @param $text String
436 * @return mixed An integer if $text is a valid value otherwise false
438 function getLocalNsIndex( $text ) {
439 $lctext = $this->lc( $text );
440 $ids = $this->getNamespaceIds();
441 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
447 function getNamespaceAliases() {
448 if ( is_null( $this->namespaceAliases
) ) {
449 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
453 foreach ( $aliases as $name => $index ) {
454 if ( $index === NS_PROJECT_TALK
) {
455 unset( $aliases[$name] );
456 $name = $this->fixVariableInNamespace( $name );
457 $aliases[$name] = $index;
462 global $wgExtraGenderNamespaces;
463 $genders = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
464 foreach ( $genders as $index => $forms ) {
465 foreach ( $forms as $alias ) {
466 $aliases[$alias] = $index;
470 $this->namespaceAliases
= $aliases;
472 return $this->namespaceAliases
;
478 function getNamespaceIds() {
479 if ( is_null( $this->mNamespaceIds
) ) {
480 global $wgNamespaceAliases;
481 # Put namespace names and aliases into a hashtable.
482 # If this is too slow, then we should arrange it so that it is done
483 # before caching. The catch is that at pre-cache time, the above
484 # class-specific fixup hasn't been done.
485 $this->mNamespaceIds
= array();
486 foreach ( $this->getNamespaces() as $index => $name ) {
487 $this->mNamespaceIds
[$this->lc( $name )] = $index;
489 foreach ( $this->getNamespaceAliases() as $name => $index ) {
490 $this->mNamespaceIds
[$this->lc( $name )] = $index;
492 if ( $wgNamespaceAliases ) {
493 foreach ( $wgNamespaceAliases as $name => $index ) {
494 $this->mNamespaceIds
[$this->lc( $name )] = $index;
498 return $this->mNamespaceIds
;
503 * Get a namespace key by value, case insensitive. Canonical namespace
504 * names override custom ones defined for the current language.
506 * @param $text String
507 * @return mixed An integer if $text is a valid value otherwise false
509 function getNsIndex( $text ) {
510 $lctext = $this->lc( $text );
511 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
514 $ids = $this->getNamespaceIds();
515 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
519 * short names for language variants used for language conversion links.
521 * @param $code String
522 * @param $usemsg Use the "variantname-xyz" message if it exists
525 function getVariantname( $code, $usemsg = true ) {
526 $msg = "variantname-$code";
527 $codeArray = list( $rootCode ) = explode( '-', $code );
528 if( $usemsg && wfMessage( $msg )->exists() ) {
529 return $this->getMessageFromDB( $msg );
530 } elseif( $name = self
::getLanguageName( $code ) ) {
531 return $name; # if it's defined as a language name, show that
533 # otherwise, output the language code
539 * @param $name string
542 function specialPage( $name ) {
543 $aliases = $this->getSpecialPageAliases();
544 if ( isset( $aliases[$name][0] ) ) {
545 $name = $aliases[$name][0];
547 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
553 function getQuickbarSettings() {
555 $this->getMessage( 'qbsettings-none' ),
556 $this->getMessage( 'qbsettings-fixedleft' ),
557 $this->getMessage( 'qbsettings-fixedright' ),
558 $this->getMessage( 'qbsettings-floatingleft' ),
559 $this->getMessage( 'qbsettings-floatingright' ),
560 $this->getMessage( 'qbsettings-directionality' )
567 function getDatePreferences() {
568 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
574 function getDateFormats() {
575 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
579 * @return array|string
581 function getDefaultDateFormat() {
582 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
583 if ( $df === 'dmy or mdy' ) {
584 global $wgAmericanDates;
585 return $wgAmericanDates ?
'mdy' : 'dmy';
594 function getDatePreferenceMigrationMap() {
595 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
602 function getImageFile( $image ) {
603 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
609 function getExtraUserToggles() {
610 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
617 function getUserToggle( $tog ) {
618 return $this->getMessageFromDB( "tog-$tog" );
622 * Get language names, indexed by code.
623 * If $customisedOnly is true, only returns codes with a messages file
625 * @param $customisedOnly bool
629 public static function getLanguageNames( $customisedOnly = false ) {
630 global $wgExtraLanguageNames;
631 static $coreLanguageNames;
633 if ( $coreLanguageNames === null ) {
634 include( MWInit
::compiledPath( 'languages/Names.php' ) );
637 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
638 if ( !$customisedOnly ) {
644 $dir = opendir( "$IP/languages/messages" );
645 while ( false !== ( $file = readdir( $dir ) ) ) {
646 $code = self
::getCodeFromFileName( $file, 'Messages' );
647 if ( $code && isset( $allNames[$code] ) ) {
648 $names[$code] = $allNames[$code];
656 * Get translated language names. This is done on best effort and
657 * by default this is exactly the same as Language::getLanguageNames.
658 * The CLDR extension provides translated names.
659 * @param $code String Language code.
660 * @return Array language code => language name
663 public static function getTranslatedLanguageNames( $code ) {
665 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
667 foreach ( self
::getLanguageNames() as $code => $name ) {
668 if ( !isset( $names[$code] ) ) $names[$code] = $name;
675 * Get a message from the MediaWiki namespace.
677 * @param $msg String: message name
680 function getMessageFromDB( $msg ) {
681 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
685 * @param $code string
688 function getLanguageName( $code ) {
689 $names = self
::getLanguageNames();
690 if ( !array_key_exists( $code, $names ) ) {
693 return $names[$code];
700 function getMonthName( $key ) {
701 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
707 function getMonthNamesArray() {
708 $monthNames = array( '' );
709 for ( $i=1; $i < 13; $i++
) {
710 $monthNames[] = $this->getMonthName( $i );
719 function getMonthNameGen( $key ) {
720 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
727 function getMonthAbbreviation( $key ) {
728 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
734 function getMonthAbbreviationsArray() {
735 $monthNames = array( '' );
736 for ( $i=1; $i < 13; $i++
) {
737 $monthNames[] = $this->getMonthAbbreviation( $i );
746 function getWeekdayName( $key ) {
747 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
754 function getWeekdayAbbreviation( $key ) {
755 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
762 function getIranianCalendarMonthName( $key ) {
763 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
770 function getHebrewCalendarMonthName( $key ) {
771 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
778 function getHebrewCalendarMonthNameGen( $key ) {
779 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
786 function getHijriCalendarMonthName( $key ) {
787 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
791 * Used by date() and time() to adjust the time output.
793 * @param $ts Int the time in date('YmdHis') format
794 * @param $tz Mixed: adjust the time by this amount (default false, mean we
795 * get user timecorrection setting)
798 function userAdjust( $ts, $tz = false ) {
799 global $wgUser, $wgLocalTZoffset;
801 if ( $tz === false ) {
802 $tz = $wgUser->getOption( 'timecorrection' );
805 $data = explode( '|', $tz, 3 );
807 if ( $data[0] == 'ZoneInfo' ) {
808 wfSuppressWarnings();
809 $userTZ = timezone_open( $data[2] );
811 if ( $userTZ !== false ) {
812 $date = date_create( $ts, timezone_open( 'UTC' ) );
813 date_timezone_set( $date, $userTZ );
814 $date = date_format( $date, 'YmdHis' );
817 # Unrecognized timezone, default to 'Offset' with the stored offset.
822 if ( $data[0] == 'System' ||
$tz == '' ) {
823 # Global offset in minutes.
824 if ( isset( $wgLocalTZoffset ) ) {
825 $minDiff = $wgLocalTZoffset;
827 } elseif ( $data[0] == 'Offset' ) {
828 $minDiff = intval( $data[1] );
830 $data = explode( ':', $tz );
831 if ( count( $data ) == 2 ) {
832 $data[0] = intval( $data[0] );
833 $data[1] = intval( $data[1] );
834 $minDiff = abs( $data[0] ) * 60 +
$data[1];
835 if ( $data[0] < 0 ) {
836 $minDiff = -$minDiff;
839 $minDiff = intval( $data[0] ) * 60;
843 # No difference ? Return time unchanged
844 if ( 0 == $minDiff ) {
848 wfSuppressWarnings(); // E_STRICT system time bitching
849 # Generate an adjusted date; take advantage of the fact that mktime
850 # will normalize out-of-range values so we don't have to split $minDiff
851 # into hours and minutes.
853 (int)substr( $ts, 8, 2 ) ), # Hours
854 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
855 (int)substr( $ts, 12, 2 ), # Seconds
856 (int)substr( $ts, 4, 2 ), # Month
857 (int)substr( $ts, 6, 2 ), # Day
858 (int)substr( $ts, 0, 4 ) ); # Year
860 $date = date( 'YmdHis', $t );
867 * This is a workalike of PHP's date() function, but with better
868 * internationalisation, a reduced set of format characters, and a better
871 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
872 * PHP manual for definitions. There are a number of extensions, which
875 * xn Do not translate digits of the next numeric format character
876 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
877 * xr Use roman numerals for the next numeric format character
878 * xh Use hebrew numerals for the next numeric format character
880 * xg Genitive month name
882 * xij j (day number) in Iranian calendar
883 * xiF F (month name) in Iranian calendar
884 * xin n (month number) in Iranian calendar
885 * xiY Y (full year) in Iranian calendar
887 * xjj j (day number) in Hebrew calendar
888 * xjF F (month name) in Hebrew calendar
889 * xjt t (days in month) in Hebrew calendar
890 * xjx xg (genitive month name) in Hebrew calendar
891 * xjn n (month number) in Hebrew calendar
892 * xjY Y (full year) in Hebrew calendar
894 * xmj j (day number) in Hijri calendar
895 * xmF F (month name) in Hijri calendar
896 * xmn n (month number) in Hijri calendar
897 * xmY Y (full year) in Hijri calendar
899 * xkY Y (full year) in Thai solar calendar. Months and days are
900 * identical to the Gregorian calendar
901 * xoY Y (full year) in Minguo calendar or Juche year.
902 * Months and days are identical to the
904 * xtY Y (full year) in Japanese nengo. Months and days are
905 * identical to the Gregorian calendar
907 * Characters enclosed in double quotes will be considered literal (with
908 * the quotes themselves removed). Unmatched quotes will be considered
909 * literal quotes. Example:
911 * "The month is" F => The month is January
914 * Backslash escaping is also supported.
916 * Input timestamp is assumed to be pre-normalized to the desired local
919 * @param $format String
920 * @param $ts String: 14-character timestamp
923 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
927 function sprintfDate( $format, $ts ) {
940 for ( $p = 0; $p < strlen( $format ); $p++
) {
943 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
944 $code .= $format[++
$p];
947 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
948 $code .= $format[++
$p];
959 $rawToggle = !$rawToggle;
968 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
971 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
972 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
975 $num = substr( $ts, 6, 2 );
978 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
979 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
982 $num = intval( substr( $ts, 6, 2 ) );
986 $iranian = self
::tsToIranian( $ts );
992 $hijri = self
::tsToHijri( $ts );
998 $hebrew = self
::tsToHebrew( $ts );
1004 $unix = wfTimestamp( TS_UNIX
, $ts );
1006 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1010 $unix = wfTimestamp( TS_UNIX
, $ts );
1012 $w = gmdate( 'w', $unix );
1017 $unix = wfTimestamp( TS_UNIX
, $ts );
1019 $num = gmdate( 'w', $unix );
1023 $unix = wfTimestamp( TS_UNIX
, $ts );
1025 $num = gmdate( 'z', $unix );
1029 $unix = wfTimestamp( TS_UNIX
, $ts );
1031 $num = gmdate( 'W', $unix );
1034 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1038 $iranian = self
::tsToIranian( $ts );
1040 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1044 $hijri = self
::tsToHijri( $ts );
1046 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1050 $hebrew = self
::tsToHebrew( $ts );
1052 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1055 $num = substr( $ts, 4, 2 );
1058 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1061 $num = intval( substr( $ts, 4, 2 ) );
1065 $iranian = self
::tsToIranian( $ts );
1071 $hijri = self
::tsToHijri ( $ts );
1077 $hebrew = self
::tsToHebrew( $ts );
1083 $unix = wfTimestamp( TS_UNIX
, $ts );
1085 $num = gmdate( 't', $unix );
1089 $hebrew = self
::tsToHebrew( $ts );
1095 $unix = wfTimestamp( TS_UNIX
, $ts );
1097 $num = gmdate( 'L', $unix );
1101 $unix = wfTimestamp( TS_UNIX
, $ts );
1103 $num = date( 'o', $unix );
1106 $num = substr( $ts, 0, 4 );
1110 $iranian = self
::tsToIranian( $ts );
1116 $hijri = self
::tsToHijri( $ts );
1122 $hebrew = self
::tsToHebrew( $ts );
1128 $thai = self
::tsToYear( $ts, 'thai' );
1134 $minguo = self
::tsToYear( $ts, 'minguo' );
1140 $tenno = self
::tsToYear( $ts, 'tenno' );
1145 $num = substr( $ts, 2, 2 );
1148 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1151 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1154 $h = substr( $ts, 8, 2 );
1155 $num = $h %
12 ?
$h %
12 : 12;
1158 $num = intval( substr( $ts, 8, 2 ) );
1161 $h = substr( $ts, 8, 2 );
1162 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1165 $num = substr( $ts, 8, 2 );
1168 $num = substr( $ts, 10, 2 );
1171 $num = substr( $ts, 12, 2 );
1175 $unix = wfTimestamp( TS_UNIX
, $ts );
1177 $s .= gmdate( 'c', $unix );
1181 $unix = wfTimestamp( TS_UNIX
, $ts );
1183 $s .= gmdate( 'r', $unix );
1187 $unix = wfTimestamp( TS_UNIX
, $ts );
1192 # Backslash escaping
1193 if ( $p < strlen( $format ) - 1 ) {
1194 $s .= $format[++
$p];
1201 if ( $p < strlen( $format ) - 1 ) {
1202 $endQuote = strpos( $format, '"', $p +
1 );
1203 if ( $endQuote === false ) {
1204 # No terminating quote, assume literal "
1207 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1211 # Quote at end of string, assume literal "
1218 if ( $num !== false ) {
1219 if ( $rawToggle ||
$raw ) {
1222 } elseif ( $roman ) {
1223 $s .= self
::romanNumeral( $num );
1225 } elseif ( $hebrewNum ) {
1226 $s .= self
::hebrewNumeral( $num );
1229 $s .= $this->formatNum( $num, true );
1236 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1237 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1240 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1241 * Gregorian dates to Iranian dates. Originally written in C, it
1242 * is released under the terms of GNU Lesser General Public
1243 * License. Conversion to PHP was performed by Niklas Laxström.
1245 * Link: http://www.farsiweb.info/jalali/jalali.c
1251 private static function tsToIranian( $ts ) {
1252 $gy = substr( $ts, 0, 4 ) -1600;
1253 $gm = substr( $ts, 4, 2 ) -1;
1254 $gd = substr( $ts, 6, 2 ) -1;
1256 # Days passed from the beginning (including leap years)
1258 +
floor( ( $gy +
3 ) / 4 )
1259 - floor( ( $gy +
99 ) / 100 )
1260 +
floor( ( $gy +
399 ) / 400 );
1262 // Add days of the past months of this year
1263 for ( $i = 0; $i < $gm; $i++
) {
1264 $gDayNo +
= self
::$GREG_DAYS[$i];
1268 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1272 // Days passed in current month
1275 $jDayNo = $gDayNo - 79;
1277 $jNp = floor( $jDayNo / 12053 );
1280 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1283 if ( $jDayNo >= 366 ) {
1284 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1285 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1288 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1289 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1295 return array( $jy, $jm, $jd );
1299 * Converting Gregorian dates to Hijri dates.
1301 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1303 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1309 private static function tsToHijri( $ts ) {
1310 $year = substr( $ts, 0, 4 );
1311 $month = substr( $ts, 4, 2 );
1312 $day = substr( $ts, 6, 2 );
1320 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1321 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1324 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1325 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1326 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1329 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1330 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1333 $zl = $zjd -1948440 +
10632;
1334 $zn = (int)( ( $zl - 1 ) / 10631 );
1335 $zl = $zl - 10631 * $zn +
354;
1336 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1337 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1338 $zm = (int)( ( 24 * $zl ) / 709 );
1339 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1340 $zy = 30 * $zn +
$zj - 30;
1342 return array( $zy, $zm, $zd );
1346 * Converting Gregorian dates to Hebrew dates.
1348 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1349 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1350 * to translate the relevant functions into PHP and release them under
1353 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1354 * and Adar II is 14. In a non-leap year, Adar is 6.
1360 private static function tsToHebrew( $ts ) {
1362 $year = substr( $ts, 0, 4 );
1363 $month = substr( $ts, 4, 2 );
1364 $day = substr( $ts, 6, 2 );
1366 # Calculate Hebrew year
1367 $hebrewYear = $year +
3760;
1369 # Month number when September = 1, August = 12
1371 if ( $month > 12 ) {
1378 # Calculate day of year from 1 September
1380 for ( $i = 1; $i < $month; $i++
) {
1384 # Check if the year is leap
1385 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1388 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1395 # Calculate the start of the Hebrew year
1396 $start = self
::hebrewYearStart( $hebrewYear );
1398 # Calculate next year's start
1399 if ( $dayOfYear <= $start ) {
1400 # Day is before the start of the year - it is the previous year
1402 $nextStart = $start;
1406 # Add days since previous year's 1 September
1408 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1412 # Start of the new (previous) year
1413 $start = self
::hebrewYearStart( $hebrewYear );
1416 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1419 # Calculate Hebrew day of year
1420 $hebrewDayOfYear = $dayOfYear - $start;
1422 # Difference between year's days
1423 $diff = $nextStart - $start;
1424 # Add 12 (or 13 for leap years) days to ignore the difference between
1425 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1426 # difference is only about the year type
1427 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1433 # Check the year pattern, and is leap year
1434 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1435 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1436 # and non-leap years
1437 $yearPattern = $diff %
30;
1438 # Check if leap year
1439 $isLeap = $diff >= 30;
1441 # Calculate day in the month from number of day in the Hebrew year
1442 # Don't check Adar - if the day is not in Adar, we will stop before;
1443 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1444 $hebrewDay = $hebrewDayOfYear;
1447 while ( $hebrewMonth <= 12 ) {
1448 # Calculate days in this month
1449 if ( $isLeap && $hebrewMonth == 6 ) {
1450 # Adar in a leap year
1452 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1454 if ( $hebrewDay <= $days ) {
1458 # Subtract the days of Adar I
1459 $hebrewDay -= $days;
1462 if ( $hebrewDay <= $days ) {
1468 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1469 # Cheshvan in a complete year (otherwise as the rule below)
1471 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1472 # Kislev in an incomplete year (otherwise as the rule below)
1475 # Odd months have 30 days, even have 29
1476 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1478 if ( $hebrewDay <= $days ) {
1479 # In the current month
1482 # Subtract the days of the current month
1483 $hebrewDay -= $days;
1484 # Try in the next month
1489 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1493 * This calculates the Hebrew year start, as days since 1 September.
1494 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1495 * Used for Hebrew date.
1501 private static function hebrewYearStart( $year ) {
1502 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1503 $b = intval( ( $year - 1 ) %
4 );
1504 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1508 $Mar = intval( $m );
1514 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1515 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1517 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1519 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1523 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1528 * Algorithm to convert Gregorian dates to Thai solar dates,
1529 * Minguo dates or Minguo dates.
1531 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1532 * http://en.wikipedia.org/wiki/Minguo_calendar
1533 * http://en.wikipedia.org/wiki/Japanese_era_name
1535 * @param $ts String: 14-character timestamp
1536 * @param $cName String: calender name
1537 * @return Array: converted year, month, day
1539 private static function tsToYear( $ts, $cName ) {
1540 $gy = substr( $ts, 0, 4 );
1541 $gm = substr( $ts, 4, 2 );
1542 $gd = substr( $ts, 6, 2 );
1544 if ( !strcmp( $cName, 'thai' ) ) {
1546 # Add 543 years to the Gregorian calendar
1547 # Months and days are identical
1548 $gy_offset = $gy +
543;
1549 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1551 # Deduct 1911 years from the Gregorian calendar
1552 # Months and days are identical
1553 $gy_offset = $gy - 1911;
1554 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1555 # Nengō dates up to Meiji period
1556 # Deduct years from the Gregorian calendar
1557 # depending on the nengo periods
1558 # Months and days are identical
1559 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1561 $gy_gannen = $gy - 1868 +
1;
1562 $gy_offset = $gy_gannen;
1563 if ( $gy_gannen == 1 ) {
1566 $gy_offset = '明治' . $gy_offset;
1568 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1569 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1570 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1571 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1572 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1576 $gy_gannen = $gy - 1912 +
1;
1577 $gy_offset = $gy_gannen;
1578 if ( $gy_gannen == 1 ) {
1581 $gy_offset = '大正' . $gy_offset;
1583 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1584 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1585 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1589 $gy_gannen = $gy - 1926 +
1;
1590 $gy_offset = $gy_gannen;
1591 if ( $gy_gannen == 1 ) {
1594 $gy_offset = '昭和' . $gy_offset;
1597 $gy_gannen = $gy - 1989 +
1;
1598 $gy_offset = $gy_gannen;
1599 if ( $gy_gannen == 1 ) {
1602 $gy_offset = '平成' . $gy_offset;
1608 return array( $gy_offset, $gm, $gd );
1612 * Roman number formatting up to 3000
1618 static function romanNumeral( $num ) {
1619 static $table = array(
1620 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1621 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1622 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1623 array( '', 'M', 'MM', 'MMM' )
1626 $num = intval( $num );
1627 if ( $num > 3000 ||
$num <= 0 ) {
1632 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1633 if ( $num >= $pow10 ) {
1634 $s .= $table[$i][floor( $num / $pow10 )];
1636 $num = $num %
$pow10;
1642 * Hebrew Gematria number formatting up to 9999
1648 static function hebrewNumeral( $num ) {
1649 static $table = array(
1650 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1651 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1652 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1653 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1656 $num = intval( $num );
1657 if ( $num > 9999 ||
$num <= 0 ) {
1662 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1663 if ( $num >= $pow10 ) {
1664 if ( $num == 15 ||
$num == 16 ) {
1665 $s .= $table[0][9] . $table[0][$num - 9];
1668 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1669 if ( $pow10 == 1000 ) {
1674 $num = $num %
$pow10;
1676 if ( strlen( $s ) == 2 ) {
1679 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1680 $str .= substr( $s, strlen( $s ) - 2, 2 );
1682 $start = substr( $str, 0, strlen( $str ) - 2 );
1683 $end = substr( $str, strlen( $str ) - 2 );
1686 $str = $start . 'ך';
1689 $str = $start . 'ם';
1692 $str = $start . 'ן';
1695 $str = $start . 'ף';
1698 $str = $start . 'ץ';
1705 * This is meant to be used by time(), date(), and timeanddate() to get
1706 * the date preference they're supposed to use, it should be used in
1710 * function timeanddate([...], $format = true) {
1711 * $datePreference = $this->dateFormat($format);
1716 * @param $usePrefs Mixed: if true, the user's preference is used
1717 * if false, the site/language default is used
1718 * if int/string, assumed to be a format.
1721 function dateFormat( $usePrefs = true ) {
1724 if ( is_bool( $usePrefs ) ) {
1726 $datePreference = $wgUser->getDatePreference();
1728 $datePreference = (string)User
::getDefaultOption( 'date' );
1731 $datePreference = (string)$usePrefs;
1735 if ( $datePreference == '' ) {
1739 return $datePreference;
1743 * Get a format string for a given type and preference
1744 * @param $type string May be date, time or both
1745 * @param $pref string The format name as it appears in Messages*.php
1749 function getDateFormatString( $type, $pref ) {
1750 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1751 if ( $pref == 'default' ) {
1752 $pref = $this->getDefaultDateFormat();
1753 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1755 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1756 if ( is_null( $df ) ) {
1757 $pref = $this->getDefaultDateFormat();
1758 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1761 $this->dateFormatStrings
[$type][$pref] = $df;
1763 return $this->dateFormatStrings
[$type][$pref];
1767 * @param $ts Mixed: the time format which needs to be turned into a
1768 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1769 * @param $adj Bool: whether to adjust the time output according to the
1770 * user configured offset ($timecorrection)
1771 * @param $format Mixed: true to use user's date format preference
1772 * @param $timecorrection String|bool the time offset as returned by
1773 * validateTimeZone() in Special:Preferences
1776 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1777 $ts = wfTimestamp( TS_MW
, $ts );
1779 $ts = $this->userAdjust( $ts, $timecorrection );
1781 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1782 return $this->sprintfDate( $df, $ts );
1786 * @param $ts Mixed: the time format which needs to be turned into a
1787 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1788 * @param $adj Bool: whether to adjust the time output according to the
1789 * user configured offset ($timecorrection)
1790 * @param $format Mixed: true to use user's date format preference
1791 * @param $timecorrection String|bool the time offset as returned by
1792 * validateTimeZone() in Special:Preferences
1795 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1796 $ts = wfTimestamp( TS_MW
, $ts );
1798 $ts = $this->userAdjust( $ts, $timecorrection );
1800 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1801 return $this->sprintfDate( $df, $ts );
1805 * @param $ts Mixed: the time format which needs to be turned into a
1806 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1807 * @param $adj Bool: whether to adjust the time output according to the
1808 * user configured offset ($timecorrection)
1809 * @param $format Mixed: what format to return, if it's false output the
1810 * default one (default true)
1811 * @param $timecorrection String|bool the time offset as returned by
1812 * validateTimeZone() in Special:Preferences
1815 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1816 $ts = wfTimestamp( TS_MW
, $ts );
1818 $ts = $this->userAdjust( $ts, $timecorrection );
1820 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1821 return $this->sprintfDate( $df, $ts );
1825 * @param $key string
1826 * @return array|null
1828 function getMessage( $key ) {
1829 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1835 function getAllMessages() {
1836 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1845 function iconv( $in, $out, $string ) {
1846 # This is a wrapper for iconv in all languages except esperanto,
1847 # which does some nasty x-conversions beforehand
1849 # Even with //IGNORE iconv can whine about illegal characters in
1850 # *input* string. We just ignore those too.
1851 # REF: http://bugs.php.net/bug.php?id=37166
1852 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1853 wfSuppressWarnings();
1854 $text = iconv( $in, $out . '//IGNORE', $string );
1855 wfRestoreWarnings();
1859 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1862 * @param $matches array
1863 * @return mixed|string
1865 function ucwordbreaksCallbackAscii( $matches ) {
1866 return $this->ucfirst( $matches[1] );
1870 * @param $matches array
1873 function ucwordbreaksCallbackMB( $matches ) {
1874 return mb_strtoupper( $matches[0] );
1878 * @param $matches array
1881 function ucCallback( $matches ) {
1882 list( $wikiUpperChars ) = self
::getCaseMaps();
1883 return strtr( $matches[1], $wikiUpperChars );
1887 * @param $matches array
1890 function lcCallback( $matches ) {
1891 list( , $wikiLowerChars ) = self
::getCaseMaps();
1892 return strtr( $matches[1], $wikiLowerChars );
1896 * @param $matches array
1899 function ucwordsCallbackMB( $matches ) {
1900 return mb_strtoupper( $matches[0] );
1904 * @param $matches array
1907 function ucwordsCallbackWiki( $matches ) {
1908 list( $wikiUpperChars ) = self
::getCaseMaps();
1909 return strtr( $matches[0], $wikiUpperChars );
1913 * Make a string's first character uppercase
1915 * @param $str string
1919 function ucfirst( $str ) {
1921 if ( $o < 96 ) { // if already uppercase...
1923 } elseif ( $o < 128 ) {
1924 return ucfirst( $str ); // use PHP's ucfirst()
1926 // fall back to more complex logic in case of multibyte strings
1927 return $this->uc( $str, true );
1932 * Convert a string to uppercase
1934 * @param $str string
1935 * @param $first bool
1939 function uc( $str, $first = false ) {
1940 if ( function_exists( 'mb_strtoupper' ) ) {
1942 if ( $this->isMultibyte( $str ) ) {
1943 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1945 return ucfirst( $str );
1948 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1951 if ( $this->isMultibyte( $str ) ) {
1952 $x = $first ?
'^' : '';
1953 return preg_replace_callback(
1954 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1955 array( $this, 'ucCallback' ),
1959 return $first ?
ucfirst( $str ) : strtoupper( $str );
1965 * @param $str string
1966 * @return mixed|string
1968 function lcfirst( $str ) {
1971 return strval( $str );
1972 } elseif ( $o >= 128 ) {
1973 return $this->lc( $str, true );
1974 } elseif ( $o > 96 ) {
1977 $str[0] = strtolower( $str[0] );
1983 * @param $str string
1984 * @param $first bool
1985 * @return mixed|string
1987 function lc( $str, $first = false ) {
1988 if ( function_exists( 'mb_strtolower' ) ) {
1990 if ( $this->isMultibyte( $str ) ) {
1991 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1993 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1996 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1999 if ( $this->isMultibyte( $str ) ) {
2000 $x = $first ?
'^' : '';
2001 return preg_replace_callback(
2002 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2003 array( $this, 'lcCallback' ),
2007 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2013 * @param $str string
2016 function isMultibyte( $str ) {
2017 return (bool)preg_match( '/[\x80-\xff]/', $str );
2021 * @param $str string
2022 * @return mixed|string
2024 function ucwords( $str ) {
2025 if ( $this->isMultibyte( $str ) ) {
2026 $str = $this->lc( $str );
2028 // regexp to find first letter in each word (i.e. after each space)
2029 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2031 // function to use to capitalize a single char
2032 if ( function_exists( 'mb_strtoupper' ) ) {
2033 return preg_replace_callback(
2035 array( $this, 'ucwordsCallbackMB' ),
2039 return preg_replace_callback(
2041 array( $this, 'ucwordsCallbackWiki' ),
2046 return ucwords( strtolower( $str ) );
2051 * capitalize words at word breaks
2053 * @param $str string
2056 function ucwordbreaks( $str ) {
2057 if ( $this->isMultibyte( $str ) ) {
2058 $str = $this->lc( $str );
2060 // since \b doesn't work for UTF-8, we explicitely define word break chars
2061 $breaks = "[ \-\(\)\}\{\.,\?!]";
2063 // find first letter after word break
2064 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2066 if ( function_exists( 'mb_strtoupper' ) ) {
2067 return preg_replace_callback(
2069 array( $this, 'ucwordbreaksCallbackMB' ),
2073 return preg_replace_callback(
2075 array( $this, 'ucwordsCallbackWiki' ),
2080 return preg_replace_callback(
2081 '/\b([\w\x80-\xff]+)\b/',
2082 array( $this, 'ucwordbreaksCallbackAscii' ),
2089 * Return a case-folded representation of $s
2091 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2092 * and $s2 are the same except for the case of their characters. It is not
2093 * necessary for the value returned to make sense when displayed.
2095 * Do *not* perform any other normalisation in this function. If a caller
2096 * uses this function when it should be using a more general normalisation
2097 * function, then fix the caller.
2103 function caseFold( $s ) {
2104 return $this->uc( $s );
2111 function checkTitleEncoding( $s ) {
2112 if ( is_array( $s ) ) {
2113 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2115 # Check for non-UTF-8 URLs
2116 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2121 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2122 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2127 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2133 function fallback8bitEncoding() {
2134 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2138 * Most writing systems use whitespace to break up words.
2139 * Some languages such as Chinese don't conventionally do this,
2140 * which requires special handling when breaking up words for
2145 function hasWordBreaks() {
2150 * Some languages such as Chinese require word segmentation,
2151 * Specify such segmentation when overridden in derived class.
2153 * @param $string String
2156 function segmentByWord( $string ) {
2161 * Some languages have special punctuation need to be normalized.
2162 * Make such changes here.
2164 * @param $string String
2167 function normalizeForSearch( $string ) {
2168 return self
::convertDoubleWidth( $string );
2172 * convert double-width roman characters to single-width.
2173 * range: ff00-ff5f ~= 0020-007f
2175 * @param $string string
2179 protected static function convertDoubleWidth( $string ) {
2180 static $full = null;
2181 static $half = null;
2183 if ( $full === null ) {
2184 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2185 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2186 $full = str_split( $fullWidth, 3 );
2187 $half = str_split( $halfWidth );
2190 $string = str_replace( $full, $half, $string );
2195 * @param $string string
2196 * @param $pattern string
2199 protected static function insertSpace( $string, $pattern ) {
2200 $string = preg_replace( $pattern, " $1 ", $string );
2201 $string = preg_replace( '/ +/', ' ', $string );
2206 * @param $termsArray array
2209 function convertForSearchResult( $termsArray ) {
2210 # some languages, e.g. Chinese, need to do a conversion
2211 # in order for search results to be displayed correctly
2216 * Get the first character of a string.
2221 function firstChar( $s ) {
2224 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2225 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2230 if ( isset( $matches[1] ) ) {
2231 if ( strlen( $matches[1] ) != 3 ) {
2235 // Break down Hangul syllables to grab the first jamo
2236 $code = utf8ToCodepoint( $matches[1] );
2237 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2239 } elseif ( $code < 0xb098 ) {
2240 return "\xe3\x84\xb1";
2241 } elseif ( $code < 0xb2e4 ) {
2242 return "\xe3\x84\xb4";
2243 } elseif ( $code < 0xb77c ) {
2244 return "\xe3\x84\xb7";
2245 } elseif ( $code < 0xb9c8 ) {
2246 return "\xe3\x84\xb9";
2247 } elseif ( $code < 0xbc14 ) {
2248 return "\xe3\x85\x81";
2249 } elseif ( $code < 0xc0ac ) {
2250 return "\xe3\x85\x82";
2251 } elseif ( $code < 0xc544 ) {
2252 return "\xe3\x85\x85";
2253 } elseif ( $code < 0xc790 ) {
2254 return "\xe3\x85\x87";
2255 } elseif ( $code < 0xcc28 ) {
2256 return "\xe3\x85\x88";
2257 } elseif ( $code < 0xce74 ) {
2258 return "\xe3\x85\x8a";
2259 } elseif ( $code < 0xd0c0 ) {
2260 return "\xe3\x85\x8b";
2261 } elseif ( $code < 0xd30c ) {
2262 return "\xe3\x85\x8c";
2263 } elseif ( $code < 0xd558 ) {
2264 return "\xe3\x85\x8d";
2266 return "\xe3\x85\x8e";
2273 function initEncoding() {
2274 # Some languages may have an alternate char encoding option
2275 # (Esperanto X-coding, Japanese furigana conversion, etc)
2276 # If this language is used as the primary content language,
2277 # an override to the defaults can be set here on startup.
2284 function recodeForEdit( $s ) {
2285 # For some languages we'll want to explicitly specify
2286 # which characters make it into the edit box raw
2287 # or are converted in some way or another.
2288 global $wgEditEncoding;
2289 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2292 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2300 function recodeInput( $s ) {
2301 # Take the previous into account.
2302 global $wgEditEncoding;
2303 if ( $wgEditEncoding != '' ) {
2304 $enc = $wgEditEncoding;
2308 if ( $enc == 'UTF-8' ) {
2311 return $this->iconv( $enc, 'UTF-8', $s );
2316 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2317 * also cleans up certain backwards-compatible sequences, converting them
2318 * to the modern Unicode equivalent.
2320 * This is language-specific for performance reasons only.
2326 function normalize( $s ) {
2327 global $wgAllUnicodeFixes;
2328 $s = UtfNormal
::cleanUp( $s );
2329 if ( $wgAllUnicodeFixes ) {
2330 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2331 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2338 * Transform a string using serialized data stored in the given file (which
2339 * must be in the serialized subdirectory of $IP). The file contains pairs
2340 * mapping source characters to destination characters.
2342 * The data is cached in process memory. This will go faster if you have the
2343 * FastStringSearch extension.
2345 * @param $file string
2346 * @param $string string
2350 function transformUsingPairFile( $file, $string ) {
2351 if ( !isset( $this->transformData
[$file] ) ) {
2352 $data = wfGetPrecompiledData( $file );
2353 if ( $data === false ) {
2354 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2356 $this->transformData
[$file] = new ReplacementArray( $data );
2358 return $this->transformData
[$file]->replace( $string );
2362 * For right-to-left language support
2367 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2371 * Return the correct HTML 'dir' attribute value for this language.
2375 return $this->isRTL() ?
'rtl' : 'ltr';
2379 * Return 'left' or 'right' as appropriate alignment for line-start
2380 * for this language's text direction.
2382 * Should be equivalent to CSS3 'start' text-align value....
2386 function alignStart() {
2387 return $this->isRTL() ?
'right' : 'left';
2391 * Return 'right' or 'left' as appropriate alignment for line-end
2392 * for this language's text direction.
2394 * Should be equivalent to CSS3 'end' text-align value....
2398 function alignEnd() {
2399 return $this->isRTL() ?
'left' : 'right';
2403 * A hidden direction mark (LRM or RLM), depending on the language direction
2405 * @param $opposite Boolean Get the direction mark opposite to your language
2408 function getDirMark( $opposite = false ) {
2409 $rtl = "\xE2\x80\x8F";
2410 $ltr = "\xE2\x80\x8E";
2411 if( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2412 return $this->isRTL() ?
$rtl : $ltr;
2418 function capitalizeAllNouns() {
2419 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2423 * An arrow, depending on the language direction
2427 function getArrow() {
2428 return $this->isRTL() ?
'←' : '→';
2432 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2436 function linkPrefixExtension() {
2437 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2443 function getMagicWords() {
2444 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2447 protected function doMagicHook() {
2448 if ( $this->mMagicHookDone
) {
2451 $this->mMagicHookDone
= true;
2452 wfProfileIn( 'LanguageGetMagic' );
2453 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2454 wfProfileOut( 'LanguageGetMagic' );
2458 * Fill a MagicWord object with data from here
2462 function getMagic( $mw ) {
2463 $this->doMagicHook();
2465 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2466 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2468 $magicWords = $this->getMagicWords();
2469 if ( isset( $magicWords[$mw->mId
] ) ) {
2470 $rawEntry = $magicWords[$mw->mId
];
2476 if ( !is_array( $rawEntry ) ) {
2477 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2479 $mw->mCaseSensitive
= $rawEntry[0];
2480 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2485 * Add magic words to the extension array
2487 * @param $newWords array
2489 function addMagicWordsByLang( $newWords ) {
2490 $fallbackChain = $this->getFallbackLanguages();
2491 $fallbackChain = array_reverse( $fallbackChain );
2492 foreach ( $fallbackChain as $code ) {
2493 if ( isset( $newWords[$code] ) ) {
2494 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2500 * Get special page names, as an associative array
2501 * case folded alias => real name
2503 function getSpecialPageAliases() {
2504 // Cache aliases because it may be slow to load them
2505 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2507 $this->mExtendedSpecialPageAliases
=
2508 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2509 wfRunHooks( 'LanguageGetSpecialPageAliases',
2510 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2513 return $this->mExtendedSpecialPageAliases
;
2517 * Italic is unsuitable for some languages
2519 * @param $text String: the text to be emphasized.
2522 function emphasize( $text ) {
2523 return "<em>$text</em>";
2527 * Normally we output all numbers in plain en_US style, that is
2528 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2529 * point twohundredthirtyfive. However this is not suitable for all
2530 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2531 * Icelandic just want to use commas instead of dots, and dots instead
2532 * of commas like "293.291,235".
2534 * An example of this function being called:
2536 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2539 * See LanguageGu.php for the Gujarati implementation and
2540 * $separatorTransformTable on MessageIs.php for
2541 * the , => . and . => , implementation.
2543 * @todo check if it's viable to use localeconv() for the decimal
2545 * @param $number Mixed: the string to be formatted, should be an integer
2546 * or a floating point number.
2547 * @param $nocommafy Bool: set to true for special numbers like dates
2550 function formatNum( $number, $nocommafy = false ) {
2551 global $wgTranslateNumerals;
2552 if ( !$nocommafy ) {
2553 $number = $this->commafy( $number );
2554 $s = $this->separatorTransformTable();
2556 $number = strtr( $number, $s );
2560 if ( $wgTranslateNumerals ) {
2561 $s = $this->digitTransformTable();
2563 $number = strtr( $number, $s );
2571 * @param $number string
2574 function parseFormattedNumber( $number ) {
2575 $s = $this->digitTransformTable();
2577 $number = strtr( $number, array_flip( $s ) );
2580 $s = $this->separatorTransformTable();
2582 $number = strtr( $number, array_flip( $s ) );
2585 $number = strtr( $number, array( ',' => '' ) );
2590 * Adds commas to a given number
2595 function commafy( $_ ) {
2596 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2602 function digitTransformTable() {
2603 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2609 function separatorTransformTable() {
2610 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2614 * Take a list of strings and build a locale-friendly comma-separated
2615 * list, using the local comma-separator message.
2616 * The last two strings are chained with an "and".
2621 function listToText( $l ) {
2623 $m = count( $l ) - 1;
2625 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2627 for ( $i = $m; $i >= 0; $i-- ) {
2630 } elseif ( $i == $m - 1 ) {
2631 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2633 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2641 * Take a list of strings and build a locale-friendly comma-separated
2642 * list, using the local comma-separator message.
2643 * @param $list array of strings to put in a comma list
2646 function commaList( $list ) {
2651 array( 'parsemag', 'escapenoentities', 'language' => $this )
2657 * Take a list of strings and build a locale-friendly semicolon-separated
2658 * list, using the local semicolon-separator message.
2659 * @param $list array of strings to put in a semicolon list
2662 function semicolonList( $list ) {
2666 'semicolon-separator',
2667 array( 'parsemag', 'escapenoentities', 'language' => $this )
2673 * Same as commaList, but separate it with the pipe instead.
2674 * @param $list array of strings to put in a pipe list
2677 function pipeList( $list ) {
2682 array( 'escapenoentities', 'language' => $this )
2688 * Truncate a string to a specified length in bytes, appending an optional
2689 * string (e.g. for ellipses)
2691 * The database offers limited byte lengths for some columns in the database;
2692 * multi-byte character sets mean we need to ensure that only whole characters
2693 * are included, otherwise broken characters can be passed to the user
2695 * If $length is negative, the string will be truncated from the beginning
2697 * @param $string String to truncate
2698 * @param $length Int: maximum length (including ellipses)
2699 * @param $ellipsis String to append to the truncated text
2700 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2701 * $adjustLength was introduced in 1.18, before that behaved as if false.
2704 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2705 # Use the localized ellipsis character
2706 if ( $ellipsis == '...' ) {
2707 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2709 # Check if there is no need to truncate
2710 if ( $length == 0 ) {
2711 return $ellipsis; // convention
2712 } elseif ( strlen( $string ) <= abs( $length ) ) {
2713 return $string; // no need to truncate
2715 $stringOriginal = $string;
2716 # If ellipsis length is >= $length then we can't apply $adjustLength
2717 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2718 $string = $ellipsis; // this can be slightly unexpected
2719 # Otherwise, truncate and add ellipsis...
2721 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2722 if ( $length > 0 ) {
2723 $length -= $eLength;
2724 $string = substr( $string, 0, $length ); // xyz...
2725 $string = $this->removeBadCharLast( $string );
2726 $string = $string . $ellipsis;
2728 $length +
= $eLength;
2729 $string = substr( $string, $length ); // ...xyz
2730 $string = $this->removeBadCharFirst( $string );
2731 $string = $ellipsis . $string;
2734 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2735 # This check is *not* redundant if $adjustLength, due to the single case where
2736 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2737 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2740 return $stringOriginal;
2745 * Remove bytes that represent an incomplete Unicode character
2746 * at the end of string (e.g. bytes of the char are missing)
2748 * @param $string String
2751 protected function removeBadCharLast( $string ) {
2752 if ( $string != '' ) {
2753 $char = ord( $string[strlen( $string ) - 1] );
2755 if ( $char >= 0xc0 ) {
2756 # We got the first byte only of a multibyte char; remove it.
2757 $string = substr( $string, 0, -1 );
2758 } elseif ( $char >= 0x80 &&
2759 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2760 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2762 # We chopped in the middle of a character; remove it
2770 * Remove bytes that represent an incomplete Unicode character
2771 * at the start of string (e.g. bytes of the char are missing)
2773 * @param $string String
2776 protected function removeBadCharFirst( $string ) {
2777 if ( $string != '' ) {
2778 $char = ord( $string[0] );
2779 if ( $char >= 0x80 && $char < 0xc0 ) {
2780 # We chopped in the middle of a character; remove the whole thing
2781 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2788 * Truncate a string of valid HTML to a specified length in bytes,
2789 * appending an optional string (e.g. for ellipses), and return valid HTML
2791 * This is only intended for styled/linked text, such as HTML with
2792 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2793 * Also, this will not detect things like "display:none" CSS.
2795 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2797 * @param string $text HTML string to truncate
2798 * @param int $length (zero/positive) Maximum length (including ellipses)
2799 * @param string $ellipsis String to append to the truncated text
2802 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2803 # Use the localized ellipsis character
2804 if ( $ellipsis == '...' ) {
2805 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2807 # Check if there is clearly no need to truncate
2808 if ( $length <= 0 ) {
2809 return $ellipsis; // no text shown, nothing to format (convention)
2810 } elseif ( strlen( $text ) <= $length ) {
2811 return $text; // string short enough even *with* HTML (short-circuit)
2814 $dispLen = 0; // innerHTML legth so far
2815 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2816 $tagType = 0; // 0-open, 1-close
2817 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2818 $entityState = 0; // 0-not entity, 1-entity
2819 $tag = $ret = ''; // accumulated tag name, accumulated result string
2820 $openTags = array(); // open tag stack
2821 $maybeState = null; // possible truncation state
2823 $textLen = strlen( $text );
2824 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2825 for ( $pos = 0; true; ++
$pos ) {
2826 # Consider truncation once the display length has reached the maximim.
2827 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2828 # Check that we're not in the middle of a bracket/entity...
2829 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2830 if ( !$testingEllipsis ) {
2831 $testingEllipsis = true;
2832 # Save where we are; we will truncate here unless there turn out to
2833 # be so few remaining characters that truncation is not necessary.
2834 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2835 $maybeState = array( $ret, $openTags ); // save state
2837 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2838 # String in fact does need truncation, the truncation point was OK.
2839 list( $ret, $openTags ) = $maybeState; // reload state
2840 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2841 $ret .= $ellipsis; // add ellipsis
2845 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2847 # Read the next char...
2849 $lastCh = $pos ?
$text[$pos - 1] : '';
2850 $ret .= $ch; // add to result string
2852 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2853 $entityState = 0; // for bad HTML
2854 $bracketState = 1; // tag started (checking for backslash)
2855 } elseif ( $ch == '>' ) {
2856 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2857 $entityState = 0; // for bad HTML
2858 $bracketState = 0; // out of brackets
2859 } elseif ( $bracketState == 1 ) {
2861 $tagType = 1; // close tag (e.g. "</span>")
2863 $tagType = 0; // open tag (e.g. "<span>")
2866 $bracketState = 2; // building tag name
2867 } elseif ( $bracketState == 2 ) {
2871 // Name found (e.g. "<a href=..."), add on tag attributes...
2872 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2874 } elseif ( $bracketState == 0 ) {
2875 if ( $entityState ) {
2878 $dispLen++
; // entity is one displayed char
2881 if ( $neLength == 0 && !$maybeState ) {
2882 // Save state without $ch. We want to *hit* the first
2883 // display char (to get tags) but not *use* it if truncating.
2884 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2887 $entityState = 1; // entity found, (e.g. " ")
2889 $dispLen++
; // this char is displayed
2890 // Add the next $max display text chars after this in one swoop...
2891 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2892 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2893 $dispLen +
= $skipped;
2899 // Close the last tag if left unclosed by bad HTML
2900 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2901 while ( count( $openTags ) > 0 ) {
2902 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2908 * truncateHtml() helper function
2909 * like strcspn() but adds the skipped chars to $ret
2918 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2919 if ( $len === null ) {
2920 $len = -1; // -1 means "no limit" for strcspn
2921 } elseif ( $len < 0 ) {
2925 if ( $start < strlen( $text ) ) {
2926 $skipCount = strcspn( $text, $search, $start, $len );
2927 $ret .= substr( $text, $start, $skipCount );
2933 * truncateHtml() helper function
2934 * (a) push or pop $tag from $openTags as needed
2935 * (b) clear $tag value
2936 * @param String &$tag Current HTML tag name we are looking at
2937 * @param int $tagType (0-open tag, 1-close tag)
2938 * @param char $lastCh Character before the '>' that ended this tag
2939 * @param array &$openTags Open tag stack (not accounting for $tag)
2941 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2942 $tag = ltrim( $tag );
2944 if ( $tagType == 0 && $lastCh != '/' ) {
2945 $openTags[] = $tag; // tag opened (didn't close itself)
2946 } elseif ( $tagType == 1 ) {
2947 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2948 array_pop( $openTags ); // tag closed
2956 * Grammatical transformations, needed for inflected languages
2957 * Invoked by putting {{grammar:case|word}} in a message
2959 * @param $word string
2960 * @param $case string
2963 function convertGrammar( $word, $case ) {
2964 global $wgGrammarForms;
2965 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2966 return $wgGrammarForms[$this->getCode()][$case][$word];
2972 * Provides an alternative text depending on specified gender.
2973 * Usage {{gender:username|masculine|feminine|neutral}}.
2974 * username is optional, in which case the gender of current user is used,
2975 * but only in (some) interface messages; otherwise default gender is used.
2976 * If second or third parameter are not specified, masculine is used.
2977 * These details may be overriden per language.
2979 * @param $gender string
2980 * @param $forms array
2984 function gender( $gender, $forms ) {
2985 if ( !count( $forms ) ) {
2988 $forms = $this->preConvertPlural( $forms, 2 );
2989 if ( $gender === 'male' ) {
2992 if ( $gender === 'female' ) {
2995 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2999 * Plural form transformations, needed for some languages.
3000 * For example, there are 3 form of plural in Russian and Polish,
3001 * depending on "count mod 10". See [[w:Plural]]
3002 * For English it is pretty simple.
3004 * Invoked by putting {{plural:count|wordform1|wordform2}}
3005 * or {{plural:count|wordform1|wordform2|wordform3}}
3007 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3009 * @param $count Integer: non-localized number
3010 * @param $forms Array: different plural forms
3011 * @return string Correct form of plural for $count in this language
3013 function convertPlural( $count, $forms ) {
3014 if ( !count( $forms ) ) {
3017 $forms = $this->preConvertPlural( $forms, 2 );
3019 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3023 * Checks that convertPlural was given an array and pads it to requested
3024 * amount of forms by copying the last one.
3026 * @param $count Integer: How many forms should there be at least
3027 * @param $forms Array of forms given to convertPlural
3028 * @return array Padded array of forms or an exception if not an array
3030 protected function preConvertPlural( /* Array */ $forms, $count ) {
3031 while ( count( $forms ) < $count ) {
3032 $forms[] = $forms[count( $forms ) - 1];
3038 * This translates the duration ("1 week", "4 days", etc)
3039 * as well as the expiry time (which is an absolute timestamp).
3040 * @param $str String: the validated block duration in English
3041 * @return Somehow translated block duration
3042 * @see LanguageFi.php for example implementation
3044 function translateBlockExpiry( $str ) {
3045 $duration = SpecialBlock
::getSuggestedDurations( $this );
3046 foreach( $duration as $show => $value ){
3047 if ( strcmp( $str, $value ) == 0 ) {
3048 return htmlspecialchars( trim( $show ) );
3052 // Since usually only infinite or indefinite is only on list, so try
3053 // equivalents if still here.
3054 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3055 if ( in_array( $str, $indefs ) ) {
3056 foreach( $indefs as $val ) {
3057 $show = array_search( $val, $duration, true );
3058 if ( $show !== false ) {
3059 return htmlspecialchars( trim( $show ) );
3063 // If no duration is given, but a timestamp, display that
3064 return ( strtotime( $str ) ?
$this->timeanddate( strtotime( $str ) ) : $str );
3068 * languages like Chinese need to be segmented in order for the diff
3071 * @param $text String
3074 function segmentForDiff( $text ) {
3079 * and unsegment to show the result
3081 * @param $text String
3084 function unsegmentForDiff( $text ) {
3089 * convert text to all supported variants
3091 * @param $text string
3094 function autoConvertToAllVariants( $text ) {
3095 return $this->mConverter
->autoConvertToAllVariants( $text );
3099 * convert text to different variants of a language.
3101 * @param $text string
3104 function convert( $text ) {
3105 return $this->mConverter
->convert( $text );
3110 * Convert a Title object to a string in the preferred variant
3112 * @param $title Title
3115 function convertTitle( $title ) {
3116 return $this->mConverter
->convertTitle( $title );
3120 * Check if this is a language with variants
3124 function hasVariants() {
3125 return sizeof( $this->getVariants() ) > 1;
3129 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3131 * @param $text string
3134 function armourMath( $text ) {
3135 return $this->mConverter
->armourMath( $text );
3139 * Perform output conversion on a string, and encode for safe HTML output.
3140 * @param $text String text to be converted
3141 * @param $isTitle Bool whether this conversion is for the article title
3143 * @todo this should get integrated somewhere sane
3145 function convertHtml( $text, $isTitle = false ) {
3146 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3150 * @param $key string
3153 function convertCategoryKey( $key ) {
3154 return $this->mConverter
->convertCategoryKey( $key );
3158 * Get the list of variants supported by this language
3159 * see sample implementation in LanguageZh.php
3161 * @return array an array of language codes
3163 function getVariants() {
3164 return $this->mConverter
->getVariants();
3170 function getPreferredVariant() {
3171 return $this->mConverter
->getPreferredVariant();
3177 function getDefaultVariant() {
3178 return $this->mConverter
->getDefaultVariant();
3184 function getURLVariant() {
3185 return $this->mConverter
->getURLVariant();
3189 * If a language supports multiple variants, it is
3190 * possible that non-existing link in one variant
3191 * actually exists in another variant. this function
3192 * tries to find it. See e.g. LanguageZh.php
3194 * @param $link String: the name of the link
3195 * @param $nt Mixed: the title object of the link
3196 * @param $ignoreOtherCond Boolean: to disable other conditions when
3197 * we need to transclude a template or update a category's link
3198 * @return null the input parameters may be modified upon return
3200 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3201 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3205 * If a language supports multiple variants, converts text
3206 * into an array of all possible variants of the text:
3207 * 'variant' => text in that variant
3209 * @deprecated since 1.17 Use autoConvertToAllVariants()
3211 * @param $text string
3215 function convertLinkToAllVariants( $text ) {
3216 return $this->mConverter
->convertLinkToAllVariants( $text );
3220 * returns language specific options used by User::getPageRenderHash()
3221 * for example, the preferred language variant
3225 function getExtraHashOptions() {
3226 return $this->mConverter
->getExtraHashOptions();
3230 * For languages that support multiple variants, the title of an
3231 * article may be displayed differently in different variants. this
3232 * function returns the apporiate title defined in the body of the article.
3236 function getParsedTitle() {
3237 return $this->mConverter
->getParsedTitle();
3241 * Enclose a string with the "no conversion" tag. This is used by
3242 * various functions in the Parser
3244 * @param $text String: text to be tagged for no conversion
3245 * @param $noParse bool
3246 * @return string the tagged text
3248 function markNoConversion( $text, $noParse = false ) {
3249 return $this->mConverter
->markNoConversion( $text, $noParse );
3253 * A regular expression to match legal word-trailing characters
3254 * which should be merged onto a link of the form [[foo]]bar.
3258 function linkTrail() {
3259 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3265 function getLangObj() {
3270 * Get the RFC 3066 code for this language object
3274 function getCode() {
3275 return $this->mCode
;
3279 * @param $code string
3281 function setCode( $code ) {
3282 $this->mCode
= $code;
3286 * Get the name of a file for a certain language code
3287 * @param $prefix string Prepend this to the filename
3288 * @param $code string Language code
3289 * @param $suffix string Append this to the filename
3290 * @return string $prefix . $mangledCode . $suffix
3292 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3293 // Protect against path traversal
3294 if ( !Language
::isValidCode( $code )
3295 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3297 throw new MWException( "Invalid language code \"$code\"" );
3300 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3304 * Get the language code from a file name. Inverse of getFileName()
3305 * @param $filename string $prefix . $languageCode . $suffix
3306 * @param $prefix string Prefix before the language code
3307 * @param $suffix string Suffix after the language code
3308 * @return string Language code, or false if $prefix or $suffix isn't found
3310 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3312 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3313 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3314 if ( !count( $m ) ) {
3317 return str_replace( '_', '-', strtolower( $m[1] ) );
3321 * @param $code string
3324 static function getMessagesFileName( $code ) {
3326 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3330 * @param $code string
3333 static function getClassFileName( $code ) {
3335 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3339 * Get the first fallback for a given language.
3341 * @param $code string
3343 * @return false|string
3345 static function getFallbackFor( $code ) {
3346 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3349 $fallbacks = self
::getFallbacksFor( $code );
3350 $first = array_shift( $fallbacks );
3356 * Get the ordered list of fallback languages.
3359 * @param $code string Language code
3362 static function getFallbacksFor( $code ) {
3363 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3366 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3367 $v = array_map( 'trim', explode( ',', $v ) );
3368 if ( $v[count( $v ) - 1] !== 'en' ) {
3376 * Get all messages for a given language
3377 * WARNING: this may take a long time. If you just need all message *keys*
3378 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3380 * @param $code string
3384 static function getMessagesFor( $code ) {
3385 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3389 * Get a message for a given language
3391 * @param $key string
3392 * @param $code string
3396 static function getMessageFor( $key, $code ) {
3397 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3401 * Get all message keys for a given language. This is a faster alternative to
3402 * array_keys( Language::getMessagesFor( $code ) )
3403 * @param $code string Language code
3404 * @return array of message keys (strings)
3406 static function getMessageKeysFor( $code ) {
3407 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3414 function fixVariableInNamespace( $talk ) {
3415 if ( strpos( $talk, '$1' ) === false ) {
3419 global $wgMetaNamespace;
3420 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3422 # Allow grammar transformations
3423 # Allowing full message-style parsing would make simple requests
3424 # such as action=raw much more expensive than they need to be.
3425 # This will hopefully cover most cases.
3426 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3427 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3428 return str_replace( ' ', '_', $talk );
3435 function replaceGrammarInNamespace( $m ) {
3436 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3440 * @throws MWException
3443 static function getCaseMaps() {
3444 static $wikiUpperChars, $wikiLowerChars;
3445 if ( isset( $wikiUpperChars ) ) {
3446 return array( $wikiUpperChars, $wikiLowerChars );
3449 wfProfileIn( __METHOD__
);
3450 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3451 if ( $arr === false ) {
3452 throw new MWException(
3453 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3455 $wikiUpperChars = $arr['wikiUpperChars'];
3456 $wikiLowerChars = $arr['wikiLowerChars'];
3457 wfProfileOut( __METHOD__
);
3458 return array( $wikiUpperChars, $wikiLowerChars );
3462 * Decode an expiry (block, protection, etc) which has come from the DB
3464 * @param $expiry String: Database expiry String
3465 * @param $format Bool|Int true to process using language functions, or TS_ constant
3466 * to return the expiry in a given timestamp
3469 public function formatExpiry( $expiry, $format = true ) {
3470 static $infinity, $infinityMsg;
3471 if( $infinity === null ){
3472 $infinityMsg = wfMessage( 'infiniteblock' );
3473 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3476 if ( $expiry == '' ||
$expiry == $infinity ) {
3477 return $format === true
3481 return $format === true
3482 ?
$this->timeanddate( $expiry )
3483 : wfTimestamp( $format, $expiry );
3489 * @param $seconds int|float
3490 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3491 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3492 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3495 function formatTimePeriod( $seconds, $format = false ) {
3496 if ( round( $seconds * 10 ) < 100 ) {
3497 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3498 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3499 } elseif ( round( $seconds ) < 60 ) {
3500 $s = $this->formatNum( round( $seconds ) );
3501 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3502 } elseif ( round( $seconds ) < 3600 ) {
3503 $minutes = floor( $seconds / 60 );
3504 $secondsPart = round( fmod( $seconds, 60 ) );
3505 if ( $secondsPart == 60 ) {
3509 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3511 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3512 } elseif ( round( $seconds ) <= 2*86400 ) {
3513 $hours = floor( $seconds / 3600 );
3514 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3515 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3516 if ( $secondsPart == 60 ) {
3520 if ( $minutes == 60 ) {
3524 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3526 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3527 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3528 $s .= ' ' . $this->formatNum( $secondsPart ) .
3529 $this->getMessageFromDB( 'seconds-abbrev' );
3532 $days = floor( $seconds / 86400 );
3533 if ( $format === 'avoidminutes' ) {
3534 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3535 if ( $hours == 24 ) {
3539 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3541 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3542 } elseif ( $format === 'avoidseconds' ) {
3543 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3544 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3545 if ( $minutes == 60 ) {
3549 if ( $hours == 24 ) {
3553 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3555 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3557 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3559 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3561 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3571 function formatBitrate( $bps ) {
3572 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3574 return $this->formatNum( $bps ) . $units[0];
3576 $unitIndex = floor( log10( $bps ) / 3 );
3577 $mantissa = $bps / pow( 1000, $unitIndex );
3578 if ( $mantissa < 10 ) {
3579 $mantissa = round( $mantissa, 1 );
3581 $mantissa = round( $mantissa );
3583 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3587 * Format a size in bytes for output, using an appropriate
3588 * unit (B, KB, MB or GB) according to the magnitude in question
3590 * @param $size int Size to format
3591 * @return string Plain text (not HTML)
3593 function formatSize( $size ) {
3594 // For small sizes no decimal places necessary
3596 if ( $size > 1024 ) {
3597 $size = $size / 1024;
3598 if ( $size > 1024 ) {
3599 $size = $size / 1024;
3600 // For MB and bigger two decimal places are smarter
3602 if ( $size > 1024 ) {
3603 $size = $size / 1024;
3604 $msg = 'size-gigabytes';
3606 $msg = 'size-megabytes';
3609 $msg = 'size-kilobytes';
3612 $msg = 'size-bytes';
3614 $size = round( $size, $round );
3615 $text = $this->getMessageFromDB( $msg );
3616 return str_replace( '$1', $this->formatNum( $size ), $text );
3620 * Get the conversion rule title, if any.
3624 function getConvRuleTitle() {
3625 return $this->mConverter
->getConvRuleTitle();