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 );
1263 // Add days of the past months of this year
1264 for ( $i = 0; $i < $gm; $i++
) {
1265 $gDayNo +
= self
::$GREG_DAYS[$i];
1269 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1273 // Days passed in current month
1276 $jDayNo = $gDayNo - 79;
1278 $jNp = floor( $jDayNo / 12053 );
1281 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1284 if ( $jDayNo >= 366 ) {
1285 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1286 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1289 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1290 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1296 return array( $jy, $jm, $jd );
1300 * Converting Gregorian dates to Hijri dates.
1302 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1304 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1310 private static function tsToHijri( $ts ) {
1311 $year = substr( $ts, 0, 4 );
1312 $month = substr( $ts, 4, 2 );
1313 $day = substr( $ts, 6, 2 );
1321 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1322 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1325 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1326 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1327 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1330 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1331 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1334 $zl = $zjd -1948440 +
10632;
1335 $zn = (int)( ( $zl - 1 ) / 10631 );
1336 $zl = $zl - 10631 * $zn +
354;
1337 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1338 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1339 $zm = (int)( ( 24 * $zl ) / 709 );
1340 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1341 $zy = 30 * $zn +
$zj - 30;
1343 return array( $zy, $zm, $zd );
1347 * Converting Gregorian dates to Hebrew dates.
1349 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1350 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1351 * to translate the relevant functions into PHP and release them under
1354 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1355 * and Adar II is 14. In a non-leap year, Adar is 6.
1361 private static function tsToHebrew( $ts ) {
1363 $year = substr( $ts, 0, 4 );
1364 $month = substr( $ts, 4, 2 );
1365 $day = substr( $ts, 6, 2 );
1367 # Calculate Hebrew year
1368 $hebrewYear = $year +
3760;
1370 # Month number when September = 1, August = 12
1372 if ( $month > 12 ) {
1379 # Calculate day of year from 1 September
1381 for ( $i = 1; $i < $month; $i++
) {
1385 # Check if the year is leap
1386 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1389 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1396 # Calculate the start of the Hebrew year
1397 $start = self
::hebrewYearStart( $hebrewYear );
1399 # Calculate next year's start
1400 if ( $dayOfYear <= $start ) {
1401 # Day is before the start of the year - it is the previous year
1403 $nextStart = $start;
1407 # Add days since previous year's 1 September
1409 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1413 # Start of the new (previous) year
1414 $start = self
::hebrewYearStart( $hebrewYear );
1417 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1420 # Calculate Hebrew day of year
1421 $hebrewDayOfYear = $dayOfYear - $start;
1423 # Difference between year's days
1424 $diff = $nextStart - $start;
1425 # Add 12 (or 13 for leap years) days to ignore the difference between
1426 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1427 # difference is only about the year type
1428 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1434 # Check the year pattern, and is leap year
1435 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1436 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1437 # and non-leap years
1438 $yearPattern = $diff %
30;
1439 # Check if leap year
1440 $isLeap = $diff >= 30;
1442 # Calculate day in the month from number of day in the Hebrew year
1443 # Don't check Adar - if the day is not in Adar, we will stop before;
1444 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1445 $hebrewDay = $hebrewDayOfYear;
1448 while ( $hebrewMonth <= 12 ) {
1449 # Calculate days in this month
1450 if ( $isLeap && $hebrewMonth == 6 ) {
1451 # Adar in a leap year
1453 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1455 if ( $hebrewDay <= $days ) {
1459 # Subtract the days of Adar I
1460 $hebrewDay -= $days;
1463 if ( $hebrewDay <= $days ) {
1469 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1470 # Cheshvan in a complete year (otherwise as the rule below)
1472 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1473 # Kislev in an incomplete year (otherwise as the rule below)
1476 # Odd months have 30 days, even have 29
1477 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1479 if ( $hebrewDay <= $days ) {
1480 # In the current month
1483 # Subtract the days of the current month
1484 $hebrewDay -= $days;
1485 # Try in the next month
1490 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1494 * This calculates the Hebrew year start, as days since 1 September.
1495 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1496 * Used for Hebrew date.
1502 private static function hebrewYearStart( $year ) {
1503 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1504 $b = intval( ( $year - 1 ) %
4 );
1505 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1509 $Mar = intval( $m );
1515 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1516 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1518 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1520 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1524 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1529 * Algorithm to convert Gregorian dates to Thai solar dates,
1530 * Minguo dates or Minguo dates.
1532 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1533 * http://en.wikipedia.org/wiki/Minguo_calendar
1534 * http://en.wikipedia.org/wiki/Japanese_era_name
1536 * @param $ts String: 14-character timestamp
1537 * @param $cName String: calender name
1538 * @return Array: converted year, month, day
1540 private static function tsToYear( $ts, $cName ) {
1541 $gy = substr( $ts, 0, 4 );
1542 $gm = substr( $ts, 4, 2 );
1543 $gd = substr( $ts, 6, 2 );
1545 if ( !strcmp( $cName, 'thai' ) ) {
1547 # Add 543 years to the Gregorian calendar
1548 # Months and days are identical
1549 $gy_offset = $gy +
543;
1550 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1552 # Deduct 1911 years from the Gregorian calendar
1553 # Months and days are identical
1554 $gy_offset = $gy - 1911;
1555 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1556 # Nengō dates up to Meiji period
1557 # Deduct years from the Gregorian calendar
1558 # depending on the nengo periods
1559 # Months and days are identical
1560 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1562 $gy_gannen = $gy - 1868 +
1;
1563 $gy_offset = $gy_gannen;
1564 if ( $gy_gannen == 1 ) {
1567 $gy_offset = '明治' . $gy_offset;
1569 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1570 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1571 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1572 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1573 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1577 $gy_gannen = $gy - 1912 +
1;
1578 $gy_offset = $gy_gannen;
1579 if ( $gy_gannen == 1 ) {
1582 $gy_offset = '大正' . $gy_offset;
1584 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1585 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1586 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1590 $gy_gannen = $gy - 1926 +
1;
1591 $gy_offset = $gy_gannen;
1592 if ( $gy_gannen == 1 ) {
1595 $gy_offset = '昭和' . $gy_offset;
1598 $gy_gannen = $gy - 1989 +
1;
1599 $gy_offset = $gy_gannen;
1600 if ( $gy_gannen == 1 ) {
1603 $gy_offset = '平成' . $gy_offset;
1609 return array( $gy_offset, $gm, $gd );
1613 * Roman number formatting up to 3000
1619 static function romanNumeral( $num ) {
1620 static $table = array(
1621 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1622 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1623 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1624 array( '', 'M', 'MM', 'MMM' )
1627 $num = intval( $num );
1628 if ( $num > 3000 ||
$num <= 0 ) {
1633 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1634 if ( $num >= $pow10 ) {
1635 $s .= $table[$i][floor( $num / $pow10 )];
1637 $num = $num %
$pow10;
1643 * Hebrew Gematria number formatting up to 9999
1649 static function hebrewNumeral( $num ) {
1650 static $table = array(
1651 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1652 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1653 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1654 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1657 $num = intval( $num );
1658 if ( $num > 9999 ||
$num <= 0 ) {
1663 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1664 if ( $num >= $pow10 ) {
1665 if ( $num == 15 ||
$num == 16 ) {
1666 $s .= $table[0][9] . $table[0][$num - 9];
1669 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1670 if ( $pow10 == 1000 ) {
1675 $num = $num %
$pow10;
1677 if ( strlen( $s ) == 2 ) {
1680 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1681 $str .= substr( $s, strlen( $s ) - 2, 2 );
1683 $start = substr( $str, 0, strlen( $str ) - 2 );
1684 $end = substr( $str, strlen( $str ) - 2 );
1687 $str = $start . 'ך';
1690 $str = $start . 'ם';
1693 $str = $start . 'ן';
1696 $str = $start . 'ף';
1699 $str = $start . 'ץ';
1706 * This is meant to be used by time(), date(), and timeanddate() to get
1707 * the date preference they're supposed to use, it should be used in
1711 * function timeanddate([...], $format = true) {
1712 * $datePreference = $this->dateFormat($format);
1717 * @param $usePrefs Mixed: if true, the user's preference is used
1718 * if false, the site/language default is used
1719 * if int/string, assumed to be a format.
1722 function dateFormat( $usePrefs = true ) {
1725 if ( is_bool( $usePrefs ) ) {
1727 $datePreference = $wgUser->getDatePreference();
1729 $datePreference = (string)User
::getDefaultOption( 'date' );
1732 $datePreference = (string)$usePrefs;
1736 if ( $datePreference == '' ) {
1740 return $datePreference;
1744 * Get a format string for a given type and preference
1745 * @param $type string May be date, time or both
1746 * @param $pref string The format name as it appears in Messages*.php
1750 function getDateFormatString( $type, $pref ) {
1751 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1752 if ( $pref == 'default' ) {
1753 $pref = $this->getDefaultDateFormat();
1754 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1756 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1757 if ( is_null( $df ) ) {
1758 $pref = $this->getDefaultDateFormat();
1759 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1762 $this->dateFormatStrings
[$type][$pref] = $df;
1764 return $this->dateFormatStrings
[$type][$pref];
1768 * @param $ts Mixed: the time format which needs to be turned into a
1769 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1770 * @param $adj Bool: whether to adjust the time output according to the
1771 * user configured offset ($timecorrection)
1772 * @param $format Mixed: true to use user's date format preference
1773 * @param $timecorrection String|bool the time offset as returned by
1774 * validateTimeZone() in Special:Preferences
1777 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1778 $ts = wfTimestamp( TS_MW
, $ts );
1780 $ts = $this->userAdjust( $ts, $timecorrection );
1782 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1783 return $this->sprintfDate( $df, $ts );
1787 * @param $ts Mixed: the time format which needs to be turned into a
1788 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1789 * @param $adj Bool: whether to adjust the time output according to the
1790 * user configured offset ($timecorrection)
1791 * @param $format Mixed: true to use user's date format preference
1792 * @param $timecorrection String|bool the time offset as returned by
1793 * validateTimeZone() in Special:Preferences
1796 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1797 $ts = wfTimestamp( TS_MW
, $ts );
1799 $ts = $this->userAdjust( $ts, $timecorrection );
1801 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1802 return $this->sprintfDate( $df, $ts );
1806 * @param $ts Mixed: the time format which needs to be turned into a
1807 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1808 * @param $adj Bool: whether to adjust the time output according to the
1809 * user configured offset ($timecorrection)
1810 * @param $format Mixed: what format to return, if it's false output the
1811 * default one (default true)
1812 * @param $timecorrection String|bool the time offset as returned by
1813 * validateTimeZone() in Special:Preferences
1816 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1817 $ts = wfTimestamp( TS_MW
, $ts );
1819 $ts = $this->userAdjust( $ts, $timecorrection );
1821 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1822 return $this->sprintfDate( $df, $ts );
1826 * @param $key string
1827 * @return array|null
1829 function getMessage( $key ) {
1830 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1836 function getAllMessages() {
1837 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1846 function iconv( $in, $out, $string ) {
1847 # This is a wrapper for iconv in all languages except esperanto,
1848 # which does some nasty x-conversions beforehand
1850 # Even with //IGNORE iconv can whine about illegal characters in
1851 # *input* string. We just ignore those too.
1852 # REF: http://bugs.php.net/bug.php?id=37166
1853 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1854 wfSuppressWarnings();
1855 $text = iconv( $in, $out . '//IGNORE', $string );
1856 wfRestoreWarnings();
1860 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1863 * @param $matches array
1864 * @return mixed|string
1866 function ucwordbreaksCallbackAscii( $matches ) {
1867 return $this->ucfirst( $matches[1] );
1871 * @param $matches array
1874 function ucwordbreaksCallbackMB( $matches ) {
1875 return mb_strtoupper( $matches[0] );
1879 * @param $matches array
1882 function ucCallback( $matches ) {
1883 list( $wikiUpperChars ) = self
::getCaseMaps();
1884 return strtr( $matches[1], $wikiUpperChars );
1888 * @param $matches array
1891 function lcCallback( $matches ) {
1892 list( , $wikiLowerChars ) = self
::getCaseMaps();
1893 return strtr( $matches[1], $wikiLowerChars );
1897 * @param $matches array
1900 function ucwordsCallbackMB( $matches ) {
1901 return mb_strtoupper( $matches[0] );
1905 * @param $matches array
1908 function ucwordsCallbackWiki( $matches ) {
1909 list( $wikiUpperChars ) = self
::getCaseMaps();
1910 return strtr( $matches[0], $wikiUpperChars );
1914 * Make a string's first character uppercase
1916 * @param $str string
1920 function ucfirst( $str ) {
1922 if ( $o < 96 ) { // if already uppercase...
1924 } elseif ( $o < 128 ) {
1925 return ucfirst( $str ); // use PHP's ucfirst()
1927 // fall back to more complex logic in case of multibyte strings
1928 return $this->uc( $str, true );
1933 * Convert a string to uppercase
1935 * @param $str string
1936 * @param $first bool
1940 function uc( $str, $first = false ) {
1941 if ( function_exists( 'mb_strtoupper' ) ) {
1943 if ( $this->isMultibyte( $str ) ) {
1944 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1946 return ucfirst( $str );
1949 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1952 if ( $this->isMultibyte( $str ) ) {
1953 $x = $first ?
'^' : '';
1954 return preg_replace_callback(
1955 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1956 array( $this, 'ucCallback' ),
1960 return $first ?
ucfirst( $str ) : strtoupper( $str );
1966 * @param $str string
1967 * @return mixed|string
1969 function lcfirst( $str ) {
1972 return strval( $str );
1973 } elseif ( $o >= 128 ) {
1974 return $this->lc( $str, true );
1975 } elseif ( $o > 96 ) {
1978 $str[0] = strtolower( $str[0] );
1984 * @param $str string
1985 * @param $first bool
1986 * @return mixed|string
1988 function lc( $str, $first = false ) {
1989 if ( function_exists( 'mb_strtolower' ) ) {
1991 if ( $this->isMultibyte( $str ) ) {
1992 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1994 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1997 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2000 if ( $this->isMultibyte( $str ) ) {
2001 $x = $first ?
'^' : '';
2002 return preg_replace_callback(
2003 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2004 array( $this, 'lcCallback' ),
2008 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2014 * @param $str string
2017 function isMultibyte( $str ) {
2018 return (bool)preg_match( '/[\x80-\xff]/', $str );
2022 * @param $str string
2023 * @return mixed|string
2025 function ucwords( $str ) {
2026 if ( $this->isMultibyte( $str ) ) {
2027 $str = $this->lc( $str );
2029 // regexp to find first letter in each word (i.e. after each space)
2030 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2032 // function to use to capitalize a single char
2033 if ( function_exists( 'mb_strtoupper' ) ) {
2034 return preg_replace_callback(
2036 array( $this, 'ucwordsCallbackMB' ),
2040 return preg_replace_callback(
2042 array( $this, 'ucwordsCallbackWiki' ),
2047 return ucwords( strtolower( $str ) );
2052 * capitalize words at word breaks
2054 * @param $str string
2057 function ucwordbreaks( $str ) {
2058 if ( $this->isMultibyte( $str ) ) {
2059 $str = $this->lc( $str );
2061 // since \b doesn't work for UTF-8, we explicitely define word break chars
2062 $breaks = "[ \-\(\)\}\{\.,\?!]";
2064 // find first letter after word break
2065 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2067 if ( function_exists( 'mb_strtoupper' ) ) {
2068 return preg_replace_callback(
2070 array( $this, 'ucwordbreaksCallbackMB' ),
2074 return preg_replace_callback(
2076 array( $this, 'ucwordsCallbackWiki' ),
2081 return preg_replace_callback(
2082 '/\b([\w\x80-\xff]+)\b/',
2083 array( $this, 'ucwordbreaksCallbackAscii' ),
2090 * Return a case-folded representation of $s
2092 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2093 * and $s2 are the same except for the case of their characters. It is not
2094 * necessary for the value returned to make sense when displayed.
2096 * Do *not* perform any other normalisation in this function. If a caller
2097 * uses this function when it should be using a more general normalisation
2098 * function, then fix the caller.
2104 function caseFold( $s ) {
2105 return $this->uc( $s );
2112 function checkTitleEncoding( $s ) {
2113 if ( is_array( $s ) ) {
2114 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2116 # Check for non-UTF-8 URLs
2117 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2122 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2123 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2128 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2134 function fallback8bitEncoding() {
2135 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2139 * Most writing systems use whitespace to break up words.
2140 * Some languages such as Chinese don't conventionally do this,
2141 * which requires special handling when breaking up words for
2146 function hasWordBreaks() {
2151 * Some languages such as Chinese require word segmentation,
2152 * Specify such segmentation when overridden in derived class.
2154 * @param $string String
2157 function segmentByWord( $string ) {
2162 * Some languages have special punctuation need to be normalized.
2163 * Make such changes here.
2165 * @param $string String
2168 function normalizeForSearch( $string ) {
2169 return self
::convertDoubleWidth( $string );
2173 * convert double-width roman characters to single-width.
2174 * range: ff00-ff5f ~= 0020-007f
2176 * @param $string string
2180 protected static function convertDoubleWidth( $string ) {
2181 static $full = null;
2182 static $half = null;
2184 if ( $full === null ) {
2185 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2186 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2187 $full = str_split( $fullWidth, 3 );
2188 $half = str_split( $halfWidth );
2191 $string = str_replace( $full, $half, $string );
2196 * @param $string string
2197 * @param $pattern string
2200 protected static function insertSpace( $string, $pattern ) {
2201 $string = preg_replace( $pattern, " $1 ", $string );
2202 $string = preg_replace( '/ +/', ' ', $string );
2207 * @param $termsArray array
2210 function convertForSearchResult( $termsArray ) {
2211 # some languages, e.g. Chinese, need to do a conversion
2212 # in order for search results to be displayed correctly
2217 * Get the first character of a string.
2222 function firstChar( $s ) {
2225 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2226 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2231 if ( isset( $matches[1] ) ) {
2232 if ( strlen( $matches[1] ) != 3 ) {
2236 // Break down Hangul syllables to grab the first jamo
2237 $code = utf8ToCodepoint( $matches[1] );
2238 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2240 } elseif ( $code < 0xb098 ) {
2241 return "\xe3\x84\xb1";
2242 } elseif ( $code < 0xb2e4 ) {
2243 return "\xe3\x84\xb4";
2244 } elseif ( $code < 0xb77c ) {
2245 return "\xe3\x84\xb7";
2246 } elseif ( $code < 0xb9c8 ) {
2247 return "\xe3\x84\xb9";
2248 } elseif ( $code < 0xbc14 ) {
2249 return "\xe3\x85\x81";
2250 } elseif ( $code < 0xc0ac ) {
2251 return "\xe3\x85\x82";
2252 } elseif ( $code < 0xc544 ) {
2253 return "\xe3\x85\x85";
2254 } elseif ( $code < 0xc790 ) {
2255 return "\xe3\x85\x87";
2256 } elseif ( $code < 0xcc28 ) {
2257 return "\xe3\x85\x88";
2258 } elseif ( $code < 0xce74 ) {
2259 return "\xe3\x85\x8a";
2260 } elseif ( $code < 0xd0c0 ) {
2261 return "\xe3\x85\x8b";
2262 } elseif ( $code < 0xd30c ) {
2263 return "\xe3\x85\x8c";
2264 } elseif ( $code < 0xd558 ) {
2265 return "\xe3\x85\x8d";
2267 return "\xe3\x85\x8e";
2274 function initEncoding() {
2275 # Some languages may have an alternate char encoding option
2276 # (Esperanto X-coding, Japanese furigana conversion, etc)
2277 # If this language is used as the primary content language,
2278 # an override to the defaults can be set here on startup.
2285 function recodeForEdit( $s ) {
2286 # For some languages we'll want to explicitly specify
2287 # which characters make it into the edit box raw
2288 # or are converted in some way or another.
2289 global $wgEditEncoding;
2290 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2293 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2301 function recodeInput( $s ) {
2302 # Take the previous into account.
2303 global $wgEditEncoding;
2304 if ( $wgEditEncoding != '' ) {
2305 $enc = $wgEditEncoding;
2309 if ( $enc == 'UTF-8' ) {
2312 return $this->iconv( $enc, 'UTF-8', $s );
2317 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2318 * also cleans up certain backwards-compatible sequences, converting them
2319 * to the modern Unicode equivalent.
2321 * This is language-specific for performance reasons only.
2327 function normalize( $s ) {
2328 global $wgAllUnicodeFixes;
2329 $s = UtfNormal
::cleanUp( $s );
2330 if ( $wgAllUnicodeFixes ) {
2331 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2332 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2339 * Transform a string using serialized data stored in the given file (which
2340 * must be in the serialized subdirectory of $IP). The file contains pairs
2341 * mapping source characters to destination characters.
2343 * The data is cached in process memory. This will go faster if you have the
2344 * FastStringSearch extension.
2346 * @param $file string
2347 * @param $string string
2351 function transformUsingPairFile( $file, $string ) {
2352 if ( !isset( $this->transformData
[$file] ) ) {
2353 $data = wfGetPrecompiledData( $file );
2354 if ( $data === false ) {
2355 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2357 $this->transformData
[$file] = new ReplacementArray( $data );
2359 return $this->transformData
[$file]->replace( $string );
2363 * For right-to-left language support
2368 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2372 * Return the correct HTML 'dir' attribute value for this language.
2376 return $this->isRTL() ?
'rtl' : 'ltr';
2380 * Return 'left' or 'right' as appropriate alignment for line-start
2381 * for this language's text direction.
2383 * Should be equivalent to CSS3 'start' text-align value....
2387 function alignStart() {
2388 return $this->isRTL() ?
'right' : 'left';
2392 * Return 'right' or 'left' as appropriate alignment for line-end
2393 * for this language's text direction.
2395 * Should be equivalent to CSS3 'end' text-align value....
2399 function alignEnd() {
2400 return $this->isRTL() ?
'left' : 'right';
2404 * A hidden direction mark (LRM or RLM), depending on the language direction
2406 * @param $opposite Boolean Get the direction mark opposite to your language
2409 function getDirMark( $opposite = false ) {
2410 $rtl = "\xE2\x80\x8F";
2411 $ltr = "\xE2\x80\x8E";
2412 if( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2413 return $this->isRTL() ?
$rtl : $ltr;
2419 function capitalizeAllNouns() {
2420 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2424 * An arrow, depending on the language direction
2428 function getArrow() {
2429 return $this->isRTL() ?
'←' : '→';
2433 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2437 function linkPrefixExtension() {
2438 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2444 function getMagicWords() {
2445 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2448 protected function doMagicHook() {
2449 if ( $this->mMagicHookDone
) {
2452 $this->mMagicHookDone
= true;
2453 wfProfileIn( 'LanguageGetMagic' );
2454 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2455 wfProfileOut( 'LanguageGetMagic' );
2459 * Fill a MagicWord object with data from here
2463 function getMagic( $mw ) {
2464 $this->doMagicHook();
2466 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2467 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2469 $magicWords = $this->getMagicWords();
2470 if ( isset( $magicWords[$mw->mId
] ) ) {
2471 $rawEntry = $magicWords[$mw->mId
];
2477 if ( !is_array( $rawEntry ) ) {
2478 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2480 $mw->mCaseSensitive
= $rawEntry[0];
2481 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2486 * Add magic words to the extension array
2488 * @param $newWords array
2490 function addMagicWordsByLang( $newWords ) {
2491 $fallbackChain = $this->getFallbackLanguages();
2492 $fallbackChain = array_reverse( $fallbackChain );
2493 foreach ( $fallbackChain as $code ) {
2494 if ( isset( $newWords[$code] ) ) {
2495 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2501 * Get special page names, as an associative array
2502 * case folded alias => real name
2504 function getSpecialPageAliases() {
2505 // Cache aliases because it may be slow to load them
2506 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2508 $this->mExtendedSpecialPageAliases
=
2509 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2510 wfRunHooks( 'LanguageGetSpecialPageAliases',
2511 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2514 return $this->mExtendedSpecialPageAliases
;
2518 * Italic is unsuitable for some languages
2520 * @param $text String: the text to be emphasized.
2523 function emphasize( $text ) {
2524 return "<em>$text</em>";
2528 * Normally we output all numbers in plain en_US style, that is
2529 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2530 * point twohundredthirtyfive. However this is not suitable for all
2531 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2532 * Icelandic just want to use commas instead of dots, and dots instead
2533 * of commas like "293.291,235".
2535 * An example of this function being called:
2537 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2540 * See LanguageGu.php for the Gujarati implementation and
2541 * $separatorTransformTable on MessageIs.php for
2542 * the , => . and . => , implementation.
2544 * @todo check if it's viable to use localeconv() for the decimal
2546 * @param $number Mixed: the string to be formatted, should be an integer
2547 * or a floating point number.
2548 * @param $nocommafy Bool: set to true for special numbers like dates
2551 function formatNum( $number, $nocommafy = false ) {
2552 global $wgTranslateNumerals;
2553 if ( !$nocommafy ) {
2554 $number = $this->commafy( $number );
2555 $s = $this->separatorTransformTable();
2557 $number = strtr( $number, $s );
2561 if ( $wgTranslateNumerals ) {
2562 $s = $this->digitTransformTable();
2564 $number = strtr( $number, $s );
2572 * @param $number string
2575 function parseFormattedNumber( $number ) {
2576 $s = $this->digitTransformTable();
2578 $number = strtr( $number, array_flip( $s ) );
2581 $s = $this->separatorTransformTable();
2583 $number = strtr( $number, array_flip( $s ) );
2586 $number = strtr( $number, array( ',' => '' ) );
2591 * Adds commas to a given number
2596 function commafy( $_ ) {
2597 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2603 function digitTransformTable() {
2604 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2610 function separatorTransformTable() {
2611 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2615 * Take a list of strings and build a locale-friendly comma-separated
2616 * list, using the local comma-separator message.
2617 * The last two strings are chained with an "and".
2622 function listToText( $l ) {
2624 $m = count( $l ) - 1;
2626 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2628 for ( $i = $m; $i >= 0; $i-- ) {
2631 } elseif ( $i == $m - 1 ) {
2632 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2634 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2642 * Take a list of strings and build a locale-friendly comma-separated
2643 * list, using the local comma-separator message.
2644 * @param $list array of strings to put in a comma list
2647 function commaList( $list ) {
2652 array( 'parsemag', 'escapenoentities', 'language' => $this )
2658 * Take a list of strings and build a locale-friendly semicolon-separated
2659 * list, using the local semicolon-separator message.
2660 * @param $list array of strings to put in a semicolon list
2663 function semicolonList( $list ) {
2667 'semicolon-separator',
2668 array( 'parsemag', 'escapenoentities', 'language' => $this )
2674 * Same as commaList, but separate it with the pipe instead.
2675 * @param $list array of strings to put in a pipe list
2678 function pipeList( $list ) {
2683 array( 'escapenoentities', 'language' => $this )
2689 * Truncate a string to a specified length in bytes, appending an optional
2690 * string (e.g. for ellipses)
2692 * The database offers limited byte lengths for some columns in the database;
2693 * multi-byte character sets mean we need to ensure that only whole characters
2694 * are included, otherwise broken characters can be passed to the user
2696 * If $length is negative, the string will be truncated from the beginning
2698 * @param $string String to truncate
2699 * @param $length Int: maximum length (including ellipses)
2700 * @param $ellipsis String to append to the truncated text
2701 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2702 * $adjustLength was introduced in 1.18, before that behaved as if false.
2705 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2706 # Use the localized ellipsis character
2707 if ( $ellipsis == '...' ) {
2708 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2710 # Check if there is no need to truncate
2711 if ( $length == 0 ) {
2712 return $ellipsis; // convention
2713 } elseif ( strlen( $string ) <= abs( $length ) ) {
2714 return $string; // no need to truncate
2716 $stringOriginal = $string;
2717 # If ellipsis length is >= $length then we can't apply $adjustLength
2718 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2719 $string = $ellipsis; // this can be slightly unexpected
2720 # Otherwise, truncate and add ellipsis...
2722 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2723 if ( $length > 0 ) {
2724 $length -= $eLength;
2725 $string = substr( $string, 0, $length ); // xyz...
2726 $string = $this->removeBadCharLast( $string );
2727 $string = $string . $ellipsis;
2729 $length +
= $eLength;
2730 $string = substr( $string, $length ); // ...xyz
2731 $string = $this->removeBadCharFirst( $string );
2732 $string = $ellipsis . $string;
2735 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2736 # This check is *not* redundant if $adjustLength, due to the single case where
2737 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2738 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2741 return $stringOriginal;
2746 * Remove bytes that represent an incomplete Unicode character
2747 * at the end of string (e.g. bytes of the char are missing)
2749 * @param $string String
2752 protected function removeBadCharLast( $string ) {
2753 if ( $string != '' ) {
2754 $char = ord( $string[strlen( $string ) - 1] );
2756 if ( $char >= 0xc0 ) {
2757 # We got the first byte only of a multibyte char; remove it.
2758 $string = substr( $string, 0, -1 );
2759 } elseif ( $char >= 0x80 &&
2760 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2761 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2763 # We chopped in the middle of a character; remove it
2771 * Remove bytes that represent an incomplete Unicode character
2772 * at the start of string (e.g. bytes of the char are missing)
2774 * @param $string String
2777 protected function removeBadCharFirst( $string ) {
2778 if ( $string != '' ) {
2779 $char = ord( $string[0] );
2780 if ( $char >= 0x80 && $char < 0xc0 ) {
2781 # We chopped in the middle of a character; remove the whole thing
2782 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2789 * Truncate a string of valid HTML to a specified length in bytes,
2790 * appending an optional string (e.g. for ellipses), and return valid HTML
2792 * This is only intended for styled/linked text, such as HTML with
2793 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2794 * Also, this will not detect things like "display:none" CSS.
2796 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2798 * @param string $text HTML string to truncate
2799 * @param int $length (zero/positive) Maximum length (including ellipses)
2800 * @param string $ellipsis String to append to the truncated text
2803 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2804 # Use the localized ellipsis character
2805 if ( $ellipsis == '...' ) {
2806 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2808 # Check if there is clearly no need to truncate
2809 if ( $length <= 0 ) {
2810 return $ellipsis; // no text shown, nothing to format (convention)
2811 } elseif ( strlen( $text ) <= $length ) {
2812 return $text; // string short enough even *with* HTML (short-circuit)
2815 $dispLen = 0; // innerHTML legth so far
2816 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2817 $tagType = 0; // 0-open, 1-close
2818 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2819 $entityState = 0; // 0-not entity, 1-entity
2820 $tag = $ret = ''; // accumulated tag name, accumulated result string
2821 $openTags = array(); // open tag stack
2822 $maybeState = null; // possible truncation state
2824 $textLen = strlen( $text );
2825 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2826 for ( $pos = 0; true; ++
$pos ) {
2827 # Consider truncation once the display length has reached the maximim.
2828 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2829 # Check that we're not in the middle of a bracket/entity...
2830 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2831 if ( !$testingEllipsis ) {
2832 $testingEllipsis = true;
2833 # Save where we are; we will truncate here unless there turn out to
2834 # be so few remaining characters that truncation is not necessary.
2835 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2836 $maybeState = array( $ret, $openTags ); // save state
2838 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2839 # String in fact does need truncation, the truncation point was OK.
2840 list( $ret, $openTags ) = $maybeState; // reload state
2841 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2842 $ret .= $ellipsis; // add ellipsis
2846 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2848 # Read the next char...
2850 $lastCh = $pos ?
$text[$pos - 1] : '';
2851 $ret .= $ch; // add to result string
2853 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2854 $entityState = 0; // for bad HTML
2855 $bracketState = 1; // tag started (checking for backslash)
2856 } elseif ( $ch == '>' ) {
2857 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2858 $entityState = 0; // for bad HTML
2859 $bracketState = 0; // out of brackets
2860 } elseif ( $bracketState == 1 ) {
2862 $tagType = 1; // close tag (e.g. "</span>")
2864 $tagType = 0; // open tag (e.g. "<span>")
2867 $bracketState = 2; // building tag name
2868 } elseif ( $bracketState == 2 ) {
2872 // Name found (e.g. "<a href=..."), add on tag attributes...
2873 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2875 } elseif ( $bracketState == 0 ) {
2876 if ( $entityState ) {
2879 $dispLen++
; // entity is one displayed char
2882 if ( $neLength == 0 && !$maybeState ) {
2883 // Save state without $ch. We want to *hit* the first
2884 // display char (to get tags) but not *use* it if truncating.
2885 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2888 $entityState = 1; // entity found, (e.g. " ")
2890 $dispLen++
; // this char is displayed
2891 // Add the next $max display text chars after this in one swoop...
2892 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2893 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2894 $dispLen +
= $skipped;
2900 // Close the last tag if left unclosed by bad HTML
2901 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2902 while ( count( $openTags ) > 0 ) {
2903 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2909 * truncateHtml() helper function
2910 * like strcspn() but adds the skipped chars to $ret
2919 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2920 if ( $len === null ) {
2921 $len = -1; // -1 means "no limit" for strcspn
2922 } elseif ( $len < 0 ) {
2926 if ( $start < strlen( $text ) ) {
2927 $skipCount = strcspn( $text, $search, $start, $len );
2928 $ret .= substr( $text, $start, $skipCount );
2934 * truncateHtml() helper function
2935 * (a) push or pop $tag from $openTags as needed
2936 * (b) clear $tag value
2937 * @param String &$tag Current HTML tag name we are looking at
2938 * @param int $tagType (0-open tag, 1-close tag)
2939 * @param char $lastCh Character before the '>' that ended this tag
2940 * @param array &$openTags Open tag stack (not accounting for $tag)
2942 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2943 $tag = ltrim( $tag );
2945 if ( $tagType == 0 && $lastCh != '/' ) {
2946 $openTags[] = $tag; // tag opened (didn't close itself)
2947 } elseif ( $tagType == 1 ) {
2948 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2949 array_pop( $openTags ); // tag closed
2957 * Grammatical transformations, needed for inflected languages
2958 * Invoked by putting {{grammar:case|word}} in a message
2960 * @param $word string
2961 * @param $case string
2964 function convertGrammar( $word, $case ) {
2965 global $wgGrammarForms;
2966 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2967 return $wgGrammarForms[$this->getCode()][$case][$word];
2973 * Provides an alternative text depending on specified gender.
2974 * Usage {{gender:username|masculine|feminine|neutral}}.
2975 * username is optional, in which case the gender of current user is used,
2976 * but only in (some) interface messages; otherwise default gender is used.
2977 * If second or third parameter are not specified, masculine is used.
2978 * These details may be overriden per language.
2980 * @param $gender string
2981 * @param $forms array
2985 function gender( $gender, $forms ) {
2986 if ( !count( $forms ) ) {
2989 $forms = $this->preConvertPlural( $forms, 2 );
2990 if ( $gender === 'male' ) {
2993 if ( $gender === 'female' ) {
2996 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3000 * Plural form transformations, needed for some languages.
3001 * For example, there are 3 form of plural in Russian and Polish,
3002 * depending on "count mod 10". See [[w:Plural]]
3003 * For English it is pretty simple.
3005 * Invoked by putting {{plural:count|wordform1|wordform2}}
3006 * or {{plural:count|wordform1|wordform2|wordform3}}
3008 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3010 * @param $count Integer: non-localized number
3011 * @param $forms Array: different plural forms
3012 * @return string Correct form of plural for $count in this language
3014 function convertPlural( $count, $forms ) {
3015 if ( !count( $forms ) ) {
3018 $forms = $this->preConvertPlural( $forms, 2 );
3020 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3024 * Checks that convertPlural was given an array and pads it to requested
3025 * amount of forms by copying the last one.
3027 * @param $count Integer: How many forms should there be at least
3028 * @param $forms Array of forms given to convertPlural
3029 * @return array Padded array of forms or an exception if not an array
3031 protected function preConvertPlural( /* Array */ $forms, $count ) {
3032 while ( count( $forms ) < $count ) {
3033 $forms[] = $forms[count( $forms ) - 1];
3039 * This translates the duration ("1 week", "4 days", etc)
3040 * as well as the expiry time (which is an absolute timestamp).
3041 * @param $str String: the validated block duration in English
3042 * @return Somehow translated block duration
3043 * @see LanguageFi.php for example implementation
3045 function translateBlockExpiry( $str ) {
3046 $duration = SpecialBlock
::getSuggestedDurations( $this );
3047 foreach( $duration as $show => $value ){
3048 if ( strcmp( $str, $value ) == 0 ) {
3049 return htmlspecialchars( trim( $show ) );
3053 // Since usually only infinite or indefinite is only on list, so try
3054 // equivalents if still here.
3055 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3056 if ( in_array( $str, $indefs ) ) {
3057 foreach( $indefs as $val ) {
3058 $show = array_search( $val, $duration, true );
3059 if ( $show !== false ) {
3060 return htmlspecialchars( trim( $show ) );
3064 // If no duration is given, but a timestamp, display that
3065 return ( strtotime( $str ) ?
$this->timeanddate( strtotime( $str ) ) : $str );
3069 * languages like Chinese need to be segmented in order for the diff
3072 * @param $text String
3075 function segmentForDiff( $text ) {
3080 * and unsegment to show the result
3082 * @param $text String
3085 function unsegmentForDiff( $text ) {
3090 * convert text to all supported variants
3092 * @param $text string
3095 function autoConvertToAllVariants( $text ) {
3096 return $this->mConverter
->autoConvertToAllVariants( $text );
3100 * convert text to different variants of a language.
3102 * @param $text string
3105 function convert( $text ) {
3106 return $this->mConverter
->convert( $text );
3111 * Convert a Title object to a string in the preferred variant
3113 * @param $title Title
3116 function convertTitle( $title ) {
3117 return $this->mConverter
->convertTitle( $title );
3121 * Check if this is a language with variants
3125 function hasVariants() {
3126 return sizeof( $this->getVariants() ) > 1;
3130 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3132 * @param $text string
3135 function armourMath( $text ) {
3136 return $this->mConverter
->armourMath( $text );
3140 * Perform output conversion on a string, and encode for safe HTML output.
3141 * @param $text String text to be converted
3142 * @param $isTitle Bool whether this conversion is for the article title
3144 * @todo this should get integrated somewhere sane
3146 function convertHtml( $text, $isTitle = false ) {
3147 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3151 * @param $key string
3154 function convertCategoryKey( $key ) {
3155 return $this->mConverter
->convertCategoryKey( $key );
3159 * Get the list of variants supported by this language
3160 * see sample implementation in LanguageZh.php
3162 * @return array an array of language codes
3164 function getVariants() {
3165 return $this->mConverter
->getVariants();
3171 function getPreferredVariant() {
3172 return $this->mConverter
->getPreferredVariant();
3178 function getDefaultVariant() {
3179 return $this->mConverter
->getDefaultVariant();
3185 function getURLVariant() {
3186 return $this->mConverter
->getURLVariant();
3190 * If a language supports multiple variants, it is
3191 * possible that non-existing link in one variant
3192 * actually exists in another variant. this function
3193 * tries to find it. See e.g. LanguageZh.php
3195 * @param $link String: the name of the link
3196 * @param $nt Mixed: the title object of the link
3197 * @param $ignoreOtherCond Boolean: to disable other conditions when
3198 * we need to transclude a template or update a category's link
3199 * @return null the input parameters may be modified upon return
3201 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3202 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3206 * If a language supports multiple variants, converts text
3207 * into an array of all possible variants of the text:
3208 * 'variant' => text in that variant
3210 * @deprecated since 1.17 Use autoConvertToAllVariants()
3212 * @param $text string
3216 function convertLinkToAllVariants( $text ) {
3217 return $this->mConverter
->convertLinkToAllVariants( $text );
3221 * returns language specific options used by User::getPageRenderHash()
3222 * for example, the preferred language variant
3226 function getExtraHashOptions() {
3227 return $this->mConverter
->getExtraHashOptions();
3231 * For languages that support multiple variants, the title of an
3232 * article may be displayed differently in different variants. this
3233 * function returns the apporiate title defined in the body of the article.
3237 function getParsedTitle() {
3238 return $this->mConverter
->getParsedTitle();
3242 * Enclose a string with the "no conversion" tag. This is used by
3243 * various functions in the Parser
3245 * @param $text String: text to be tagged for no conversion
3246 * @param $noParse bool
3247 * @return string the tagged text
3249 function markNoConversion( $text, $noParse = false ) {
3250 return $this->mConverter
->markNoConversion( $text, $noParse );
3254 * A regular expression to match legal word-trailing characters
3255 * which should be merged onto a link of the form [[foo]]bar.
3259 function linkTrail() {
3260 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3266 function getLangObj() {
3271 * Get the RFC 3066 code for this language object
3275 function getCode() {
3276 return $this->mCode
;
3280 * @param $code string
3282 function setCode( $code ) {
3283 $this->mCode
= $code;
3287 * Get the name of a file for a certain language code
3288 * @param $prefix string Prepend this to the filename
3289 * @param $code string Language code
3290 * @param $suffix string Append this to the filename
3291 * @return string $prefix . $mangledCode . $suffix
3293 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3294 // Protect against path traversal
3295 if ( !Language
::isValidCode( $code )
3296 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3298 throw new MWException( "Invalid language code \"$code\"" );
3301 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3305 * Get the language code from a file name. Inverse of getFileName()
3306 * @param $filename string $prefix . $languageCode . $suffix
3307 * @param $prefix string Prefix before the language code
3308 * @param $suffix string Suffix after the language code
3309 * @return string Language code, or false if $prefix or $suffix isn't found
3311 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3313 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3314 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3315 if ( !count( $m ) ) {
3318 return str_replace( '_', '-', strtolower( $m[1] ) );
3322 * @param $code string
3325 static function getMessagesFileName( $code ) {
3327 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3331 * @param $code string
3334 static function getClassFileName( $code ) {
3336 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3340 * Get the first fallback for a given language.
3342 * @param $code string
3344 * @return false|string
3346 static function getFallbackFor( $code ) {
3347 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3350 $fallbacks = self
::getFallbacksFor( $code );
3351 $first = array_shift( $fallbacks );
3357 * Get the ordered list of fallback languages.
3360 * @param $code string Language code
3363 static function getFallbacksFor( $code ) {
3364 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3367 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3368 $v = array_map( 'trim', explode( ',', $v ) );
3369 if ( $v[count( $v ) - 1] !== 'en' ) {
3377 * Get all messages for a given language
3378 * WARNING: this may take a long time. If you just need all message *keys*
3379 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3381 * @param $code string
3385 static function getMessagesFor( $code ) {
3386 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3390 * Get a message for a given language
3392 * @param $key string
3393 * @param $code string
3397 static function getMessageFor( $key, $code ) {
3398 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3402 * Get all message keys for a given language. This is a faster alternative to
3403 * array_keys( Language::getMessagesFor( $code ) )
3404 * @param $code string Language code
3405 * @return array of message keys (strings)
3407 static function getMessageKeysFor( $code ) {
3408 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3415 function fixVariableInNamespace( $talk ) {
3416 if ( strpos( $talk, '$1' ) === false ) {
3420 global $wgMetaNamespace;
3421 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3423 # Allow grammar transformations
3424 # Allowing full message-style parsing would make simple requests
3425 # such as action=raw much more expensive than they need to be.
3426 # This will hopefully cover most cases.
3427 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3428 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3429 return str_replace( ' ', '_', $talk );
3436 function replaceGrammarInNamespace( $m ) {
3437 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3441 * @throws MWException
3444 static function getCaseMaps() {
3445 static $wikiUpperChars, $wikiLowerChars;
3446 if ( isset( $wikiUpperChars ) ) {
3447 return array( $wikiUpperChars, $wikiLowerChars );
3450 wfProfileIn( __METHOD__
);
3451 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3452 if ( $arr === false ) {
3453 throw new MWException(
3454 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3456 $wikiUpperChars = $arr['wikiUpperChars'];
3457 $wikiLowerChars = $arr['wikiLowerChars'];
3458 wfProfileOut( __METHOD__
);
3459 return array( $wikiUpperChars, $wikiLowerChars );
3463 * Decode an expiry (block, protection, etc) which has come from the DB
3465 * @param $expiry String: Database expiry String
3466 * @param $format Bool|Int true to process using language functions, or TS_ constant
3467 * to return the expiry in a given timestamp
3470 public function formatExpiry( $expiry, $format = true ) {
3471 static $infinity, $infinityMsg;
3472 if( $infinity === null ){
3473 $infinityMsg = wfMessage( 'infiniteblock' );
3474 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3477 if ( $expiry == '' ||
$expiry == $infinity ) {
3478 return $format === true
3482 return $format === true
3483 ?
$this->timeanddate( $expiry )
3484 : wfTimestamp( $format, $expiry );
3490 * @param $seconds int|float
3491 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3492 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3493 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3496 function formatTimePeriod( $seconds, $format = false ) {
3497 if ( round( $seconds * 10 ) < 100 ) {
3498 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3499 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3500 } elseif ( round( $seconds ) < 60 ) {
3501 $s = $this->formatNum( round( $seconds ) );
3502 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3503 } elseif ( round( $seconds ) < 3600 ) {
3504 $minutes = floor( $seconds / 60 );
3505 $secondsPart = round( fmod( $seconds, 60 ) );
3506 if ( $secondsPart == 60 ) {
3510 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3512 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3513 } elseif ( round( $seconds ) <= 2*86400 ) {
3514 $hours = floor( $seconds / 3600 );
3515 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3516 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3517 if ( $secondsPart == 60 ) {
3521 if ( $minutes == 60 ) {
3525 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3527 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3528 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3529 $s .= ' ' . $this->formatNum( $secondsPart ) .
3530 $this->getMessageFromDB( 'seconds-abbrev' );
3533 $days = floor( $seconds / 86400 );
3534 if ( $format === 'avoidminutes' ) {
3535 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3536 if ( $hours == 24 ) {
3540 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3542 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3543 } elseif ( $format === 'avoidseconds' ) {
3544 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3545 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3546 if ( $minutes == 60 ) {
3550 if ( $hours == 24 ) {
3554 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3556 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3558 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3560 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3562 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3572 function formatBitrate( $bps ) {
3573 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3575 return $this->formatNum( $bps ) . $units[0];
3577 $unitIndex = floor( log10( $bps ) / 3 );
3578 $mantissa = $bps / pow( 1000, $unitIndex );
3579 if ( $mantissa < 10 ) {
3580 $mantissa = round( $mantissa, 1 );
3582 $mantissa = round( $mantissa );
3584 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3588 * Format a size in bytes for output, using an appropriate
3589 * unit (B, KB, MB or GB) according to the magnitude in question
3591 * @param $size int Size to format
3592 * @return string Plain text (not HTML)
3594 function formatSize( $size ) {
3595 // For small sizes no decimal places necessary
3597 if ( $size > 1024 ) {
3598 $size = $size / 1024;
3599 if ( $size > 1024 ) {
3600 $size = $size / 1024;
3601 // For MB and bigger two decimal places are smarter
3603 if ( $size > 1024 ) {
3604 $size = $size / 1024;
3605 $msg = 'size-gigabytes';
3607 $msg = 'size-megabytes';
3610 $msg = 'size-kilobytes';
3613 $msg = 'size-bytes';
3615 $size = round( $size, $round );
3616 $text = $this->getMessageFromDB( $msg );
3617 return str_replace( '$1', $this->formatNum( $size ), $text );
3621 * Get the conversion rule title, if any.
3625 function getConvRuleTitle() {
3626 return $this->mConverter
->getConvRuleTitle();