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
58 * @var LanguageConverter
62 var $mVariants, $mCode, $mLoaded = false;
63 var $mMagicExtensions = array(), $mMagicHookDone = false;
64 private $mHtmlCode = null;
66 var $dateFormatStrings = array();
67 var $mExtendedSpecialPageAliases;
69 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
72 * ReplacementArray object caches
74 var $transformData = array();
77 * @var LocalisationCache
79 static public $dataCache;
81 static public $mLangObjCache = array();
83 static public $mWeekdayMsgs = array(
84 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
88 static public $mWeekdayAbbrevMsgs = array(
89 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
92 static public $mMonthMsgs = array(
93 'january', 'february', 'march', 'april', 'may_long', 'june',
94 'july', 'august', 'september', 'october', 'november',
97 static public $mMonthGenMsgs = array(
98 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
99 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
102 static public $mMonthAbbrevMsgs = array(
103 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
104 'sep', 'oct', 'nov', 'dec'
107 static public $mIranianCalendarMonthMsgs = array(
108 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
109 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
110 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
111 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
114 static public $mHebrewCalendarMonthMsgs = array(
115 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
116 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
117 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
118 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
119 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
122 static public $mHebrewCalendarMonthGenMsgs = array(
123 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
124 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
125 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
126 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
127 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
130 static public $mHijriCalendarMonthMsgs = array(
131 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
132 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
133 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
134 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
138 * Get a cached language object for a given language code
139 * @param $code String
142 static function factory( $code ) {
143 if ( !isset( self
::$mLangObjCache[$code] ) ) {
144 if ( count( self
::$mLangObjCache ) > 10 ) {
145 // Don't keep a billion objects around, that's stupid.
146 self
::$mLangObjCache = array();
148 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
150 return self
::$mLangObjCache[$code];
154 * Create a language object for a given language code
155 * @param $code String
158 protected static function newFromCode( $code ) {
159 // Protect against path traversal below
160 if ( !Language
::isValidCode( $code )
161 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
163 throw new MWException( "Invalid language code \"$code\"" );
166 if ( !Language
::isValidBuiltInCode( $code ) ) {
167 // It's not possible to customise this code with class files, so
168 // just return a Language object. This is to support uselang= hacks.
169 $lang = new Language
;
170 $lang->setCode( $code );
174 // Check if there is a language class for the code
175 $class = self
::classFromCode( $code );
176 self
::preloadLanguageClass( $class );
177 if ( MWInit
::classExists( $class ) ) {
182 // Keep trying the fallback list until we find an existing class
183 $fallbacks = Language
::getFallbacksFor( $code );
184 foreach ( $fallbacks as $fallbackCode ) {
185 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
186 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
189 $class = self
::classFromCode( $fallbackCode );
190 self
::preloadLanguageClass( $class );
191 if ( MWInit
::classExists( $class ) ) {
192 $lang = Language
::newFromCode( $fallbackCode );
193 $lang->setCode( $code );
198 throw new MWException( "Invalid fallback sequence for language '$code'" );
202 * Returns true if a language code string is of a valid form, whether or
203 * not it exists. This includes codes which are used solely for
204 * customisation via the MediaWiki namespace.
206 * @param $code string
210 public static function isValidCode( $code ) {
212 strcspn( $code, ":/\\\000" ) === strlen( $code )
213 && !preg_match( Title
::getTitleInvalidRegex(), $code );
217 * Returns true if a language code is of a valid form for the purposes of
218 * internal customisation of MediaWiki, via Messages*.php.
220 * @param $code string
225 public static function isValidBuiltInCode( $code ) {
226 return preg_match( '/^[a-z0-9-]+$/i', $code );
231 * @return String Name of the language class
233 public static function classFromCode( $code ) {
234 if ( $code == 'en' ) {
237 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
242 * Includes language class files
244 * @param $class string Name of the language class
246 public static function preloadLanguageClass( $class ) {
249 if ( $class === 'Language' ) {
253 if ( !defined( 'MW_COMPILED' ) ) {
254 // Preload base classes to work around APC/PHP5 bug
255 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
256 include_once( "$IP/languages/classes/$class.deps.php" );
258 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
259 include_once( "$IP/languages/classes/$class.php" );
265 * Get the LocalisationCache instance
267 * @return LocalisationCache
269 public static function getLocalisationCache() {
270 if ( is_null( self
::$dataCache ) ) {
271 global $wgLocalisationCacheConf;
272 $class = $wgLocalisationCacheConf['class'];
273 self
::$dataCache = new $class( $wgLocalisationCacheConf );
275 return self
::$dataCache;
278 function __construct() {
279 $this->mConverter
= new FakeConverter( $this );
280 // Set the code to the name of the descendant
281 if ( get_class( $this ) == 'Language' ) {
284 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
286 self
::getLocalisationCache();
290 * Reduce memory usage
292 function __destruct() {
293 foreach ( $this as $name => $value ) {
294 unset( $this->$name );
299 * Hook which will be called if this is the content language.
300 * Descendants can use this to register hook functions or modify globals
302 function initContLang() { }
305 * Same as getFallbacksFor for current language.
307 * @deprecated in 1.19
309 function getFallbackLanguageCode() {
310 wfDeprecated( __METHOD__
);
311 return self
::getFallbackFor( $this->mCode
);
318 function getFallbackLanguages() {
319 return self
::getFallbacksFor( $this->mCode
);
323 * Exports $wgBookstoreListEn
326 function getBookstoreList() {
327 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
333 public function getNamespaces() {
334 if ( is_null( $this->namespaceNames
) ) {
335 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
337 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
338 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
340 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
342 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
343 if ( $wgMetaNamespaceTalk ) {
344 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
346 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
347 $this->namespaceNames
[NS_PROJECT_TALK
] =
348 $this->fixVariableInNamespace( $talk );
351 # Sometimes a language will be localised but not actually exist on this wiki.
352 foreach ( $this->namespaceNames
as $key => $text ) {
353 if ( !isset( $validNamespaces[$key] ) ) {
354 unset( $this->namespaceNames
[$key] );
358 # The above mixing may leave namespaces out of canonical order.
359 # Re-order by namespace ID number...
360 ksort( $this->namespaceNames
);
362 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
364 return $this->namespaceNames
;
368 * Arbitrarily set all of the namespace names at once. Mainly used for testing
369 * @param $namespaces Array of namespaces (id => name)
371 public function setNamespaces( array $namespaces ) {
372 $this->namespaceNames
= $namespaces;
376 * A convenience function that returns the same thing as
377 * getNamespaces() except with the array values changed to ' '
378 * where it found '_', useful for producing output to be displayed
379 * e.g. in <select> forms.
383 function getFormattedNamespaces() {
384 $ns = $this->getNamespaces();
385 foreach ( $ns as $k => $v ) {
386 $ns[$k] = strtr( $v, '_', ' ' );
392 * Get a namespace value by key
394 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
395 * echo $mw_ns; // prints 'MediaWiki'
398 * @param $index Int: the array key of the namespace to return
399 * @return mixed, string if the namespace value exists, otherwise false
401 function getNsText( $index ) {
402 $ns = $this->getNamespaces();
403 return isset( $ns[$index] ) ?
$ns[$index] : false;
407 * A convenience function that returns the same thing as
408 * getNsText() except with '_' changed to ' ', useful for
411 * @param $index string
415 function getFormattedNsText( $index ) {
416 $ns = $this->getNsText( $index );
417 return strtr( $ns, '_', ' ' );
421 * Returns gender-dependent namespace alias if available.
422 * @param $index Int: namespace index
423 * @param $gender String: gender key (male, female... )
427 function getGenderNsText( $index, $gender ) {
428 global $wgExtraGenderNamespaces;
430 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
431 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
435 * Whether this language makes distinguishes genders for example in
440 function needsGenderDistinction() {
441 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
442 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
443 // $wgExtraGenderNamespaces overrides everything
445 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
446 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
447 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
450 // Check what is in i18n files
451 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
452 return count( $aliases ) > 0;
457 * Get a namespace key by value, case insensitive.
458 * Only matches namespace names for the current language, not the
459 * canonical ones defined in Namespace.php.
461 * @param $text String
462 * @return mixed An integer if $text is a valid value otherwise false
464 function getLocalNsIndex( $text ) {
465 $lctext = $this->lc( $text );
466 $ids = $this->getNamespaceIds();
467 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
473 function getNamespaceAliases() {
474 if ( is_null( $this->namespaceAliases
) ) {
475 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
479 foreach ( $aliases as $name => $index ) {
480 if ( $index === NS_PROJECT_TALK
) {
481 unset( $aliases[$name] );
482 $name = $this->fixVariableInNamespace( $name );
483 $aliases[$name] = $index;
488 global $wgExtraGenderNamespaces;
489 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
490 foreach ( $genders as $index => $forms ) {
491 foreach ( $forms as $alias ) {
492 $aliases[$alias] = $index;
496 $this->namespaceAliases
= $aliases;
498 return $this->namespaceAliases
;
504 function getNamespaceIds() {
505 if ( is_null( $this->mNamespaceIds
) ) {
506 global $wgNamespaceAliases;
507 # Put namespace names and aliases into a hashtable.
508 # If this is too slow, then we should arrange it so that it is done
509 # before caching. The catch is that at pre-cache time, the above
510 # class-specific fixup hasn't been done.
511 $this->mNamespaceIds
= array();
512 foreach ( $this->getNamespaces() as $index => $name ) {
513 $this->mNamespaceIds
[$this->lc( $name )] = $index;
515 foreach ( $this->getNamespaceAliases() as $name => $index ) {
516 $this->mNamespaceIds
[$this->lc( $name )] = $index;
518 if ( $wgNamespaceAliases ) {
519 foreach ( $wgNamespaceAliases as $name => $index ) {
520 $this->mNamespaceIds
[$this->lc( $name )] = $index;
524 return $this->mNamespaceIds
;
528 * Get a namespace key by value, case insensitive. Canonical namespace
529 * names override custom ones defined for the current language.
531 * @param $text String
532 * @return mixed An integer if $text is a valid value otherwise false
534 function getNsIndex( $text ) {
535 $lctext = $this->lc( $text );
536 $ns = MWNamespace
::getCanonicalIndex( $lctext );
537 if ( $ns !== null ) {
540 $ids = $this->getNamespaceIds();
541 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
545 * short names for language variants used for language conversion links.
547 * @param $code String
548 * @param $usemsg bool Use the "variantname-xyz" message if it exists
551 function getVariantname( $code, $usemsg = true ) {
552 $msg = "variantname-$code";
553 list( $rootCode ) = explode( '-', $code );
554 if ( $usemsg && wfMessage( $msg )->exists() ) {
555 return $this->getMessageFromDB( $msg );
557 $name = self
::getLanguageName( $code );
559 return $name; # if it's defined as a language name, show that
561 # otherwise, output the language code
567 * @param $name string
570 function specialPage( $name ) {
571 $aliases = $this->getSpecialPageAliases();
572 if ( isset( $aliases[$name][0] ) ) {
573 $name = $aliases[$name][0];
575 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
581 function getQuickbarSettings() {
583 $this->getMessage( 'qbsettings-none' ),
584 $this->getMessage( 'qbsettings-fixedleft' ),
585 $this->getMessage( 'qbsettings-fixedright' ),
586 $this->getMessage( 'qbsettings-floatingleft' ),
587 $this->getMessage( 'qbsettings-floatingright' ),
588 $this->getMessage( 'qbsettings-directionality' )
595 function getDatePreferences() {
596 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
602 function getDateFormats() {
603 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
607 * @return array|string
609 function getDefaultDateFormat() {
610 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
611 if ( $df === 'dmy or mdy' ) {
612 global $wgAmericanDates;
613 return $wgAmericanDates ?
'mdy' : 'dmy';
622 function getDatePreferenceMigrationMap() {
623 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
630 function getImageFile( $image ) {
631 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
637 function getExtraUserToggles() {
638 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
645 function getUserToggle( $tog ) {
646 return $this->getMessageFromDB( "tog-$tog" );
650 * Get native language names, indexed by code.
651 * Only those defined in MediaWiki, no other data like CLDR.
652 * If $customisedOnly is true, only returns codes with a messages file
654 * @param $customisedOnly bool
658 public static function getLanguageNames( $customisedOnly = false ) {
659 global $wgExtraLanguageNames;
660 static $coreLanguageNames;
662 if ( $coreLanguageNames === null ) {
663 include( MWInit
::compiledPath( 'languages/Names.php' ) );
666 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
667 if ( !$customisedOnly ) {
672 // We do this using a foreach over the codes instead of a directory
673 // loop so that messages files in extensions will work correctly.
674 foreach ( $allNames as $code => $value ) {
675 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
676 $names[$code] = $allNames[$code];
683 * Get translated language names. This is done on best effort and
684 * by default this is exactly the same as Language::getLanguageNames.
685 * The CLDR extension provides translated names.
686 * @param $code String Language code.
687 * @return Array language code => language name
690 public static function getTranslatedLanguageNames( $code ) {
692 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
694 foreach ( self
::getLanguageNames() as $code => $name ) {
695 if ( !isset( $names[$code] ) ) $names[$code] = $name;
702 * Get a message from the MediaWiki namespace.
704 * @param $msg String: message name
707 function getMessageFromDB( $msg ) {
708 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
712 * Get the native language name of $code.
713 * Only if defined in MediaWiki, no other data like CLDR.
714 * @param $code string
717 function getLanguageName( $code ) {
718 $names = self
::getLanguageNames();
719 if ( !array_key_exists( $code, $names ) ) {
722 return $names[$code];
729 function getMonthName( $key ) {
730 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
736 function getMonthNamesArray() {
737 $monthNames = array( '' );
738 for ( $i = 1; $i < 13; $i++
) {
739 $monthNames[] = $this->getMonthName( $i );
748 function getMonthNameGen( $key ) {
749 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
756 function getMonthAbbreviation( $key ) {
757 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
763 function getMonthAbbreviationsArray() {
764 $monthNames = array( '' );
765 for ( $i = 1; $i < 13; $i++
) {
766 $monthNames[] = $this->getMonthAbbreviation( $i );
775 function getWeekdayName( $key ) {
776 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
783 function getWeekdayAbbreviation( $key ) {
784 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
791 function getIranianCalendarMonthName( $key ) {
792 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
799 function getHebrewCalendarMonthName( $key ) {
800 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
807 function getHebrewCalendarMonthNameGen( $key ) {
808 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
815 function getHijriCalendarMonthName( $key ) {
816 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
820 * This is a workalike of PHP's date() function, but with better
821 * internationalisation, a reduced set of format characters, and a better
824 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
825 * PHP manual for definitions. There are a number of extensions, which
828 * xn Do not translate digits of the next numeric format character
829 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
830 * xr Use roman numerals for the next numeric format character
831 * xh Use hebrew numerals for the next numeric format character
833 * xg Genitive month name
835 * xij j (day number) in Iranian calendar
836 * xiF F (month name) in Iranian calendar
837 * xin n (month number) in Iranian calendar
838 * xiy y (two digit year) in Iranian calendar
839 * xiY Y (full year) in Iranian calendar
841 * xjj j (day number) in Hebrew calendar
842 * xjF F (month name) in Hebrew calendar
843 * xjt t (days in month) in Hebrew calendar
844 * xjx xg (genitive month name) in Hebrew calendar
845 * xjn n (month number) in Hebrew calendar
846 * xjY Y (full year) in Hebrew calendar
848 * xmj j (day number) in Hijri calendar
849 * xmF F (month name) in Hijri calendar
850 * xmn n (month number) in Hijri calendar
851 * xmY Y (full year) in Hijri calendar
853 * xkY Y (full year) in Thai solar calendar. Months and days are
854 * identical to the Gregorian calendar
855 * xoY Y (full year) in Minguo calendar or Juche year.
856 * Months and days are identical to the
858 * xtY Y (full year) in Japanese nengo. Months and days are
859 * identical to the Gregorian calendar
861 * Characters enclosed in double quotes will be considered literal (with
862 * the quotes themselves removed). Unmatched quotes will be considered
863 * literal quotes. Example:
865 * "The month is" F => The month is January
868 * Backslash escaping is also supported.
870 * Input timestamp is assumed to be pre-normalized to the desired local
873 * @param $format String
874 * @param $ts String: 14-character timestamp
877 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
881 function sprintfDate( $format, $ts ) {
894 for ( $p = 0; $p < strlen( $format ); $p++
) {
897 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
898 $code .= $format[++
$p];
901 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
902 $code .= $format[++
$p];
913 $rawToggle = !$rawToggle;
922 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
925 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
926 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
929 $num = substr( $ts, 6, 2 );
932 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
933 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
936 $num = intval( substr( $ts, 6, 2 ) );
940 $iranian = self
::tsToIranian( $ts );
946 $hijri = self
::tsToHijri( $ts );
952 $hebrew = self
::tsToHebrew( $ts );
958 $unix = wfTimestamp( TS_UNIX
, $ts );
960 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
964 $unix = wfTimestamp( TS_UNIX
, $ts );
966 $w = gmdate( 'w', $unix );
971 $unix = wfTimestamp( TS_UNIX
, $ts );
973 $num = gmdate( 'w', $unix );
977 $unix = wfTimestamp( TS_UNIX
, $ts );
979 $num = gmdate( 'z', $unix );
983 $unix = wfTimestamp( TS_UNIX
, $ts );
985 $num = gmdate( 'W', $unix );
988 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
992 $iranian = self
::tsToIranian( $ts );
994 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
998 $hijri = self
::tsToHijri( $ts );
1000 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1004 $hebrew = self
::tsToHebrew( $ts );
1006 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1009 $num = substr( $ts, 4, 2 );
1012 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1015 $num = intval( substr( $ts, 4, 2 ) );
1019 $iranian = self
::tsToIranian( $ts );
1025 $hijri = self
::tsToHijri ( $ts );
1031 $hebrew = self
::tsToHebrew( $ts );
1037 $unix = wfTimestamp( TS_UNIX
, $ts );
1039 $num = gmdate( 't', $unix );
1043 $hebrew = self
::tsToHebrew( $ts );
1049 $unix = wfTimestamp( TS_UNIX
, $ts );
1051 $num = gmdate( 'L', $unix );
1055 $unix = wfTimestamp( TS_UNIX
, $ts );
1057 $num = gmdate( 'o', $unix );
1060 $num = substr( $ts, 0, 4 );
1064 $iranian = self
::tsToIranian( $ts );
1070 $hijri = self
::tsToHijri( $ts );
1076 $hebrew = self
::tsToHebrew( $ts );
1082 $thai = self
::tsToYear( $ts, 'thai' );
1088 $minguo = self
::tsToYear( $ts, 'minguo' );
1094 $tenno = self
::tsToYear( $ts, 'tenno' );
1099 $num = substr( $ts, 2, 2 );
1103 $iranian = self
::tsToIranian( $ts );
1105 $num = substr( $iranian[0], -2 );
1108 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1111 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1114 $h = substr( $ts, 8, 2 );
1115 $num = $h %
12 ?
$h %
12 : 12;
1118 $num = intval( substr( $ts, 8, 2 ) );
1121 $h = substr( $ts, 8, 2 );
1122 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1125 $num = substr( $ts, 8, 2 );
1128 $num = substr( $ts, 10, 2 );
1131 $num = substr( $ts, 12, 2 );
1135 $unix = wfTimestamp( TS_UNIX
, $ts );
1137 $s .= gmdate( 'c', $unix );
1141 $unix = wfTimestamp( TS_UNIX
, $ts );
1143 $s .= gmdate( 'r', $unix );
1147 $unix = wfTimestamp( TS_UNIX
, $ts );
1152 # Backslash escaping
1153 if ( $p < strlen( $format ) - 1 ) {
1154 $s .= $format[++
$p];
1161 if ( $p < strlen( $format ) - 1 ) {
1162 $endQuote = strpos( $format, '"', $p +
1 );
1163 if ( $endQuote === false ) {
1164 # No terminating quote, assume literal "
1167 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1171 # Quote at end of string, assume literal "
1178 if ( $num !== false ) {
1179 if ( $rawToggle ||
$raw ) {
1182 } elseif ( $roman ) {
1183 $s .= self
::romanNumeral( $num );
1185 } elseif ( $hebrewNum ) {
1186 $s .= self
::hebrewNumeral( $num );
1189 $s .= $this->formatNum( $num, true );
1196 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1197 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1200 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1201 * Gregorian dates to Iranian dates. Originally written in C, it
1202 * is released under the terms of GNU Lesser General Public
1203 * License. Conversion to PHP was performed by Niklas Laxström.
1205 * Link: http://www.farsiweb.info/jalali/jalali.c
1211 private static function tsToIranian( $ts ) {
1212 $gy = substr( $ts, 0, 4 ) -1600;
1213 $gm = substr( $ts, 4, 2 ) -1;
1214 $gd = substr( $ts, 6, 2 ) -1;
1216 # Days passed from the beginning (including leap years)
1218 +
floor( ( $gy +
3 ) / 4 )
1219 - floor( ( $gy +
99 ) / 100 )
1220 +
floor( ( $gy +
399 ) / 400 );
1222 // Add days of the past months of this year
1223 for ( $i = 0; $i < $gm; $i++
) {
1224 $gDayNo +
= self
::$GREG_DAYS[$i];
1228 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1232 // Days passed in current month
1233 $gDayNo +
= (int)$gd;
1235 $jDayNo = $gDayNo - 79;
1237 $jNp = floor( $jDayNo / 12053 );
1240 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1243 if ( $jDayNo >= 366 ) {
1244 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1245 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1248 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1249 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1255 return array( $jy, $jm, $jd );
1259 * Converting Gregorian dates to Hijri dates.
1261 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1263 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1269 private static function tsToHijri( $ts ) {
1270 $year = substr( $ts, 0, 4 );
1271 $month = substr( $ts, 4, 2 );
1272 $day = substr( $ts, 6, 2 );
1280 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1281 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1284 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1285 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1286 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1289 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1290 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1293 $zl = $zjd -1948440 +
10632;
1294 $zn = (int)( ( $zl - 1 ) / 10631 );
1295 $zl = $zl - 10631 * $zn +
354;
1296 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1297 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1298 $zm = (int)( ( 24 * $zl ) / 709 );
1299 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1300 $zy = 30 * $zn +
$zj - 30;
1302 return array( $zy, $zm, $zd );
1306 * Converting Gregorian dates to Hebrew dates.
1308 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1309 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1310 * to translate the relevant functions into PHP and release them under
1313 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1314 * and Adar II is 14. In a non-leap year, Adar is 6.
1320 private static function tsToHebrew( $ts ) {
1322 $year = substr( $ts, 0, 4 );
1323 $month = substr( $ts, 4, 2 );
1324 $day = substr( $ts, 6, 2 );
1326 # Calculate Hebrew year
1327 $hebrewYear = $year +
3760;
1329 # Month number when September = 1, August = 12
1331 if ( $month > 12 ) {
1338 # Calculate day of year from 1 September
1340 for ( $i = 1; $i < $month; $i++
) {
1344 # Check if the year is leap
1345 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1348 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1355 # Calculate the start of the Hebrew year
1356 $start = self
::hebrewYearStart( $hebrewYear );
1358 # Calculate next year's start
1359 if ( $dayOfYear <= $start ) {
1360 # Day is before the start of the year - it is the previous year
1362 $nextStart = $start;
1366 # Add days since previous year's 1 September
1368 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1372 # Start of the new (previous) year
1373 $start = self
::hebrewYearStart( $hebrewYear );
1376 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1379 # Calculate Hebrew day of year
1380 $hebrewDayOfYear = $dayOfYear - $start;
1382 # Difference between year's days
1383 $diff = $nextStart - $start;
1384 # Add 12 (or 13 for leap years) days to ignore the difference between
1385 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1386 # difference is only about the year type
1387 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1393 # Check the year pattern, and is leap year
1394 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1395 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1396 # and non-leap years
1397 $yearPattern = $diff %
30;
1398 # Check if leap year
1399 $isLeap = $diff >= 30;
1401 # Calculate day in the month from number of day in the Hebrew year
1402 # Don't check Adar - if the day is not in Adar, we will stop before;
1403 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1404 $hebrewDay = $hebrewDayOfYear;
1407 while ( $hebrewMonth <= 12 ) {
1408 # Calculate days in this month
1409 if ( $isLeap && $hebrewMonth == 6 ) {
1410 # Adar in a leap year
1412 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1414 if ( $hebrewDay <= $days ) {
1418 # Subtract the days of Adar I
1419 $hebrewDay -= $days;
1422 if ( $hebrewDay <= $days ) {
1428 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1429 # Cheshvan in a complete year (otherwise as the rule below)
1431 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1432 # Kislev in an incomplete year (otherwise as the rule below)
1435 # Odd months have 30 days, even have 29
1436 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1438 if ( $hebrewDay <= $days ) {
1439 # In the current month
1442 # Subtract the days of the current month
1443 $hebrewDay -= $days;
1444 # Try in the next month
1449 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1453 * This calculates the Hebrew year start, as days since 1 September.
1454 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1455 * Used for Hebrew date.
1461 private static function hebrewYearStart( $year ) {
1462 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1463 $b = intval( ( $year - 1 ) %
4 );
1464 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1468 $Mar = intval( $m );
1474 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1475 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1477 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1479 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1483 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1488 * Algorithm to convert Gregorian dates to Thai solar dates,
1489 * Minguo dates or Minguo dates.
1491 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1492 * http://en.wikipedia.org/wiki/Minguo_calendar
1493 * http://en.wikipedia.org/wiki/Japanese_era_name
1495 * @param $ts String: 14-character timestamp
1496 * @param $cName String: calender name
1497 * @return Array: converted year, month, day
1499 private static function tsToYear( $ts, $cName ) {
1500 $gy = substr( $ts, 0, 4 );
1501 $gm = substr( $ts, 4, 2 );
1502 $gd = substr( $ts, 6, 2 );
1504 if ( !strcmp( $cName, 'thai' ) ) {
1506 # Add 543 years to the Gregorian calendar
1507 # Months and days are identical
1508 $gy_offset = $gy +
543;
1509 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1511 # Deduct 1911 years from the Gregorian calendar
1512 # Months and days are identical
1513 $gy_offset = $gy - 1911;
1514 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1515 # Nengō dates up to Meiji period
1516 # Deduct years from the Gregorian calendar
1517 # depending on the nengo periods
1518 # Months and days are identical
1519 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1521 $gy_gannen = $gy - 1868 +
1;
1522 $gy_offset = $gy_gannen;
1523 if ( $gy_gannen == 1 ) {
1526 $gy_offset = '明治' . $gy_offset;
1528 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1529 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1530 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1531 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1532 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1536 $gy_gannen = $gy - 1912 +
1;
1537 $gy_offset = $gy_gannen;
1538 if ( $gy_gannen == 1 ) {
1541 $gy_offset = '大正' . $gy_offset;
1543 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1544 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1545 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1549 $gy_gannen = $gy - 1926 +
1;
1550 $gy_offset = $gy_gannen;
1551 if ( $gy_gannen == 1 ) {
1554 $gy_offset = '昭和' . $gy_offset;
1557 $gy_gannen = $gy - 1989 +
1;
1558 $gy_offset = $gy_gannen;
1559 if ( $gy_gannen == 1 ) {
1562 $gy_offset = '平成' . $gy_offset;
1568 return array( $gy_offset, $gm, $gd );
1572 * Roman number formatting up to 3000
1578 static function romanNumeral( $num ) {
1579 static $table = array(
1580 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1581 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1582 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1583 array( '', 'M', 'MM', 'MMM' )
1586 $num = intval( $num );
1587 if ( $num > 3000 ||
$num <= 0 ) {
1592 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1593 if ( $num >= $pow10 ) {
1594 $s .= $table[$i][(int)floor( $num / $pow10 )];
1596 $num = $num %
$pow10;
1602 * Hebrew Gematria number formatting up to 9999
1608 static function hebrewNumeral( $num ) {
1609 static $table = array(
1610 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1611 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1612 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1613 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1616 $num = intval( $num );
1617 if ( $num > 9999 ||
$num <= 0 ) {
1622 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1623 if ( $num >= $pow10 ) {
1624 if ( $num == 15 ||
$num == 16 ) {
1625 $s .= $table[0][9] . $table[0][$num - 9];
1628 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1629 if ( $pow10 == 1000 ) {
1634 $num = $num %
$pow10;
1636 if ( strlen( $s ) == 2 ) {
1639 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1640 $str .= substr( $s, strlen( $s ) - 2, 2 );
1642 $start = substr( $str, 0, strlen( $str ) - 2 );
1643 $end = substr( $str, strlen( $str ) - 2 );
1646 $str = $start . 'ך';
1649 $str = $start . 'ם';
1652 $str = $start . 'ן';
1655 $str = $start . 'ף';
1658 $str = $start . 'ץ';
1665 * Used by date() and time() to adjust the time output.
1667 * @param $ts Int the time in date('YmdHis') format
1668 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1669 * get user timecorrection setting)
1672 function userAdjust( $ts, $tz = false ) {
1673 global $wgUser, $wgLocalTZoffset;
1675 if ( $tz === false ) {
1676 $tz = $wgUser->getOption( 'timecorrection' );
1679 $data = explode( '|', $tz, 3 );
1681 if ( $data[0] == 'ZoneInfo' ) {
1682 wfSuppressWarnings();
1683 $userTZ = timezone_open( $data[2] );
1684 wfRestoreWarnings();
1685 if ( $userTZ !== false ) {
1686 $date = date_create( $ts, timezone_open( 'UTC' ) );
1687 date_timezone_set( $date, $userTZ );
1688 $date = date_format( $date, 'YmdHis' );
1691 # Unrecognized timezone, default to 'Offset' with the stored offset.
1692 $data[0] = 'Offset';
1696 if ( $data[0] == 'System' ||
$tz == '' ) {
1697 # Global offset in minutes.
1698 if ( isset( $wgLocalTZoffset ) ) {
1699 $minDiff = $wgLocalTZoffset;
1701 } elseif ( $data[0] == 'Offset' ) {
1702 $minDiff = intval( $data[1] );
1704 $data = explode( ':', $tz );
1705 if ( count( $data ) == 2 ) {
1706 $data[0] = intval( $data[0] );
1707 $data[1] = intval( $data[1] );
1708 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1709 if ( $data[0] < 0 ) {
1710 $minDiff = -$minDiff;
1713 $minDiff = intval( $data[0] ) * 60;
1717 # No difference ? Return time unchanged
1718 if ( 0 == $minDiff ) {
1722 wfSuppressWarnings(); // E_STRICT system time bitching
1723 # Generate an adjusted date; take advantage of the fact that mktime
1724 # will normalize out-of-range values so we don't have to split $minDiff
1725 # into hours and minutes.
1727 (int)substr( $ts, 8, 2 ) ), # Hours
1728 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1729 (int)substr( $ts, 12, 2 ), # Seconds
1730 (int)substr( $ts, 4, 2 ), # Month
1731 (int)substr( $ts, 6, 2 ), # Day
1732 (int)substr( $ts, 0, 4 ) ); # Year
1734 $date = date( 'YmdHis', $t );
1735 wfRestoreWarnings();
1741 * This is meant to be used by time(), date(), and timeanddate() to get
1742 * the date preference they're supposed to use, it should be used in
1746 * function timeanddate([...], $format = true) {
1747 * $datePreference = $this->dateFormat($format);
1752 * @param $usePrefs Mixed: if true, the user's preference is used
1753 * if false, the site/language default is used
1754 * if int/string, assumed to be a format.
1757 function dateFormat( $usePrefs = true ) {
1760 if ( is_bool( $usePrefs ) ) {
1762 $datePreference = $wgUser->getDatePreference();
1764 $datePreference = (string)User
::getDefaultOption( 'date' );
1767 $datePreference = (string)$usePrefs;
1771 if ( $datePreference == '' ) {
1775 return $datePreference;
1779 * Get a format string for a given type and preference
1780 * @param $type string May be date, time or both
1781 * @param $pref string The format name as it appears in Messages*.php
1785 function getDateFormatString( $type, $pref ) {
1786 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1787 if ( $pref == 'default' ) {
1788 $pref = $this->getDefaultDateFormat();
1789 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1791 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1792 if ( is_null( $df ) ) {
1793 $pref = $this->getDefaultDateFormat();
1794 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1797 $this->dateFormatStrings
[$type][$pref] = $df;
1799 return $this->dateFormatStrings
[$type][$pref];
1803 * @param $ts Mixed: the time format which needs to be turned into a
1804 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1805 * @param $adj Bool: whether to adjust the time output according to the
1806 * user configured offset ($timecorrection)
1807 * @param $format Mixed: true to use user's date format preference
1808 * @param $timecorrection String|bool the time offset as returned by
1809 * validateTimeZone() in Special:Preferences
1812 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1813 $ts = wfTimestamp( TS_MW
, $ts );
1815 $ts = $this->userAdjust( $ts, $timecorrection );
1817 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1818 return $this->sprintfDate( $df, $ts );
1822 * @param $ts Mixed: the time format which needs to be turned into a
1823 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1824 * @param $adj Bool: whether to adjust the time output according to the
1825 * user configured offset ($timecorrection)
1826 * @param $format Mixed: true to use user's date format preference
1827 * @param $timecorrection String|bool the time offset as returned by
1828 * validateTimeZone() in Special:Preferences
1831 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1832 $ts = wfTimestamp( TS_MW
, $ts );
1834 $ts = $this->userAdjust( $ts, $timecorrection );
1836 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1837 return $this->sprintfDate( $df, $ts );
1841 * @param $ts Mixed: the time format which needs to be turned into a
1842 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1843 * @param $adj Bool: whether to adjust the time output according to the
1844 * user configured offset ($timecorrection)
1845 * @param $format Mixed: what format to return, if it's false output the
1846 * default one (default true)
1847 * @param $timecorrection String|bool the time offset as returned by
1848 * validateTimeZone() in Special:Preferences
1851 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1852 $ts = wfTimestamp( TS_MW
, $ts );
1854 $ts = $this->userAdjust( $ts, $timecorrection );
1856 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1857 return $this->sprintfDate( $df, $ts );
1861 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1863 * @param $type String: can be 'date', 'time' or 'both'
1864 * @param $ts Mixed: the time format which needs to be turned into a
1865 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1866 * @param $user User object used to get preferences for timezone and format
1867 * @param $options Array, can contain the following keys:
1868 * - 'timecorrection': time correction, can have the following values:
1869 * - true: use user's preference
1870 * - false: don't use time correction
1871 * - integer: value of time correction in minutes
1872 * - 'format': format to use, can have the following values:
1873 * - true: use user's preference
1874 * - false: use default preference
1875 * - string: format to use
1879 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1880 $ts = wfTimestamp( TS_MW
, $ts );
1881 $options +
= array( 'timecorrection' => true, 'format' => true );
1882 if ( $options['timecorrection'] !== false ) {
1883 if ( $options['timecorrection'] === true ) {
1884 $offset = $user->getOption( 'timecorrection' );
1886 $offset = $options['timecorrection'];
1888 $ts = $this->userAdjust( $ts, $offset );
1890 if ( $options['format'] === true ) {
1891 $format = $user->getDatePreference();
1893 $format = $options['format'];
1895 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1896 return $this->sprintfDate( $df, $ts );
1900 * Get the formatted date for the given timestamp and formatted for
1903 * @param $ts Mixed: the time format which needs to be turned into a
1904 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1905 * @param $user User object used to get preferences for timezone and format
1906 * @param $options Array, can contain the following keys:
1907 * - 'timecorrection': time correction, can have the following values:
1908 * - true: use user's preference
1909 * - false: don't use time correction
1910 * - integer: value of time correction in minutes
1911 * - 'format': format to use, can have the following values:
1912 * - true: use user's preference
1913 * - false: use default preference
1914 * - string: format to use
1918 public function userDate( $ts, User
$user, array $options = array() ) {
1919 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1923 * Get the formatted time for the given timestamp and formatted for
1926 * @param $ts Mixed: the time format which needs to be turned into a
1927 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1928 * @param $user User object used to get preferences for timezone and format
1929 * @param $options Array, can contain the following keys:
1930 * - 'timecorrection': time correction, can have the following values:
1931 * - true: use user's preference
1932 * - false: don't use time correction
1933 * - integer: value of time correction in minutes
1934 * - 'format': format to use, can have the following values:
1935 * - true: use user's preference
1936 * - false: use default preference
1937 * - string: format to use
1941 public function userTime( $ts, User
$user, array $options = array() ) {
1942 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1946 * Get the formatted date and time for the given timestamp and formatted for
1949 * @param $ts Mixed: the time format which needs to be turned into a
1950 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1951 * @param $user User object used to get preferences for timezone and format
1952 * @param $options Array, can contain the following keys:
1953 * - 'timecorrection': time correction, can have the following values:
1954 * - true: use user's preference
1955 * - false: don't use time correction
1956 * - integer: value of time correction in minutes
1957 * - 'format': format to use, can have the following values:
1958 * - true: use user's preference
1959 * - false: use default preference
1960 * - string: format to use
1964 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
1965 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
1969 * @param $key string
1970 * @return array|null
1972 function getMessage( $key ) {
1973 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1979 function getAllMessages() {
1980 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1989 function iconv( $in, $out, $string ) {
1990 # This is a wrapper for iconv in all languages except esperanto,
1991 # which does some nasty x-conversions beforehand
1993 # Even with //IGNORE iconv can whine about illegal characters in
1994 # *input* string. We just ignore those too.
1995 # REF: http://bugs.php.net/bug.php?id=37166
1996 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1997 wfSuppressWarnings();
1998 $text = iconv( $in, $out . '//IGNORE', $string );
1999 wfRestoreWarnings();
2003 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2006 * @param $matches array
2007 * @return mixed|string
2009 function ucwordbreaksCallbackAscii( $matches ) {
2010 return $this->ucfirst( $matches[1] );
2014 * @param $matches array
2017 function ucwordbreaksCallbackMB( $matches ) {
2018 return mb_strtoupper( $matches[0] );
2022 * @param $matches array
2025 function ucCallback( $matches ) {
2026 list( $wikiUpperChars ) = self
::getCaseMaps();
2027 return strtr( $matches[1], $wikiUpperChars );
2031 * @param $matches array
2034 function lcCallback( $matches ) {
2035 list( , $wikiLowerChars ) = self
::getCaseMaps();
2036 return strtr( $matches[1], $wikiLowerChars );
2040 * @param $matches array
2043 function ucwordsCallbackMB( $matches ) {
2044 return mb_strtoupper( $matches[0] );
2048 * @param $matches array
2051 function ucwordsCallbackWiki( $matches ) {
2052 list( $wikiUpperChars ) = self
::getCaseMaps();
2053 return strtr( $matches[0], $wikiUpperChars );
2057 * Make a string's first character uppercase
2059 * @param $str string
2063 function ucfirst( $str ) {
2065 if ( $o < 96 ) { // if already uppercase...
2067 } elseif ( $o < 128 ) {
2068 return ucfirst( $str ); // use PHP's ucfirst()
2070 // fall back to more complex logic in case of multibyte strings
2071 return $this->uc( $str, true );
2076 * Convert a string to uppercase
2078 * @param $str string
2079 * @param $first bool
2083 function uc( $str, $first = false ) {
2084 if ( function_exists( 'mb_strtoupper' ) ) {
2086 if ( $this->isMultibyte( $str ) ) {
2087 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2089 return ucfirst( $str );
2092 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2095 if ( $this->isMultibyte( $str ) ) {
2096 $x = $first ?
'^' : '';
2097 return preg_replace_callback(
2098 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2099 array( $this, 'ucCallback' ),
2103 return $first ?
ucfirst( $str ) : strtoupper( $str );
2109 * @param $str string
2110 * @return mixed|string
2112 function lcfirst( $str ) {
2115 return strval( $str );
2116 } elseif ( $o >= 128 ) {
2117 return $this->lc( $str, true );
2118 } elseif ( $o > 96 ) {
2121 $str[0] = strtolower( $str[0] );
2127 * @param $str string
2128 * @param $first bool
2129 * @return mixed|string
2131 function lc( $str, $first = false ) {
2132 if ( function_exists( 'mb_strtolower' ) ) {
2134 if ( $this->isMultibyte( $str ) ) {
2135 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2137 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2140 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2143 if ( $this->isMultibyte( $str ) ) {
2144 $x = $first ?
'^' : '';
2145 return preg_replace_callback(
2146 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2147 array( $this, 'lcCallback' ),
2151 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2157 * @param $str string
2160 function isMultibyte( $str ) {
2161 return (bool)preg_match( '/[\x80-\xff]/', $str );
2165 * @param $str string
2166 * @return mixed|string
2168 function ucwords( $str ) {
2169 if ( $this->isMultibyte( $str ) ) {
2170 $str = $this->lc( $str );
2172 // regexp to find first letter in each word (i.e. after each space)
2173 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2175 // function to use to capitalize a single char
2176 if ( function_exists( 'mb_strtoupper' ) ) {
2177 return preg_replace_callback(
2179 array( $this, 'ucwordsCallbackMB' ),
2183 return preg_replace_callback(
2185 array( $this, 'ucwordsCallbackWiki' ),
2190 return ucwords( strtolower( $str ) );
2195 * capitalize words at word breaks
2197 * @param $str string
2200 function ucwordbreaks( $str ) {
2201 if ( $this->isMultibyte( $str ) ) {
2202 $str = $this->lc( $str );
2204 // since \b doesn't work for UTF-8, we explicitely define word break chars
2205 $breaks = "[ \-\(\)\}\{\.,\?!]";
2207 // find first letter after word break
2208 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2210 if ( function_exists( 'mb_strtoupper' ) ) {
2211 return preg_replace_callback(
2213 array( $this, 'ucwordbreaksCallbackMB' ),
2217 return preg_replace_callback(
2219 array( $this, 'ucwordsCallbackWiki' ),
2224 return preg_replace_callback(
2225 '/\b([\w\x80-\xff]+)\b/',
2226 array( $this, 'ucwordbreaksCallbackAscii' ),
2233 * Return a case-folded representation of $s
2235 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2236 * and $s2 are the same except for the case of their characters. It is not
2237 * necessary for the value returned to make sense when displayed.
2239 * Do *not* perform any other normalisation in this function. If a caller
2240 * uses this function when it should be using a more general normalisation
2241 * function, then fix the caller.
2247 function caseFold( $s ) {
2248 return $this->uc( $s );
2255 function checkTitleEncoding( $s ) {
2256 if ( is_array( $s ) ) {
2257 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2259 # Check for non-UTF-8 URLs
2260 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2265 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2266 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2271 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2277 function fallback8bitEncoding() {
2278 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2282 * Most writing systems use whitespace to break up words.
2283 * Some languages such as Chinese don't conventionally do this,
2284 * which requires special handling when breaking up words for
2289 function hasWordBreaks() {
2294 * Some languages such as Chinese require word segmentation,
2295 * Specify such segmentation when overridden in derived class.
2297 * @param $string String
2300 function segmentByWord( $string ) {
2305 * Some languages have special punctuation need to be normalized.
2306 * Make such changes here.
2308 * @param $string String
2311 function normalizeForSearch( $string ) {
2312 return self
::convertDoubleWidth( $string );
2316 * convert double-width roman characters to single-width.
2317 * range: ff00-ff5f ~= 0020-007f
2319 * @param $string string
2323 protected static function convertDoubleWidth( $string ) {
2324 static $full = null;
2325 static $half = null;
2327 if ( $full === null ) {
2328 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2329 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2330 $full = str_split( $fullWidth, 3 );
2331 $half = str_split( $halfWidth );
2334 $string = str_replace( $full, $half, $string );
2339 * @param $string string
2340 * @param $pattern string
2343 protected static function insertSpace( $string, $pattern ) {
2344 $string = preg_replace( $pattern, " $1 ", $string );
2345 $string = preg_replace( '/ +/', ' ', $string );
2350 * @param $termsArray array
2353 function convertForSearchResult( $termsArray ) {
2354 # some languages, e.g. Chinese, need to do a conversion
2355 # in order for search results to be displayed correctly
2360 * Get the first character of a string.
2365 function firstChar( $s ) {
2368 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2369 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2374 if ( isset( $matches[1] ) ) {
2375 if ( strlen( $matches[1] ) != 3 ) {
2379 // Break down Hangul syllables to grab the first jamo
2380 $code = utf8ToCodepoint( $matches[1] );
2381 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2383 } elseif ( $code < 0xb098 ) {
2384 return "\xe3\x84\xb1";
2385 } elseif ( $code < 0xb2e4 ) {
2386 return "\xe3\x84\xb4";
2387 } elseif ( $code < 0xb77c ) {
2388 return "\xe3\x84\xb7";
2389 } elseif ( $code < 0xb9c8 ) {
2390 return "\xe3\x84\xb9";
2391 } elseif ( $code < 0xbc14 ) {
2392 return "\xe3\x85\x81";
2393 } elseif ( $code < 0xc0ac ) {
2394 return "\xe3\x85\x82";
2395 } elseif ( $code < 0xc544 ) {
2396 return "\xe3\x85\x85";
2397 } elseif ( $code < 0xc790 ) {
2398 return "\xe3\x85\x87";
2399 } elseif ( $code < 0xcc28 ) {
2400 return "\xe3\x85\x88";
2401 } elseif ( $code < 0xce74 ) {
2402 return "\xe3\x85\x8a";
2403 } elseif ( $code < 0xd0c0 ) {
2404 return "\xe3\x85\x8b";
2405 } elseif ( $code < 0xd30c ) {
2406 return "\xe3\x85\x8c";
2407 } elseif ( $code < 0xd558 ) {
2408 return "\xe3\x85\x8d";
2410 return "\xe3\x85\x8e";
2417 function initEncoding() {
2418 # Some languages may have an alternate char encoding option
2419 # (Esperanto X-coding, Japanese furigana conversion, etc)
2420 # If this language is used as the primary content language,
2421 # an override to the defaults can be set here on startup.
2428 function recodeForEdit( $s ) {
2429 # For some languages we'll want to explicitly specify
2430 # which characters make it into the edit box raw
2431 # or are converted in some way or another.
2432 global $wgEditEncoding;
2433 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2436 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2444 function recodeInput( $s ) {
2445 # Take the previous into account.
2446 global $wgEditEncoding;
2447 if ( $wgEditEncoding != '' ) {
2448 $enc = $wgEditEncoding;
2452 if ( $enc == 'UTF-8' ) {
2455 return $this->iconv( $enc, 'UTF-8', $s );
2460 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2461 * also cleans up certain backwards-compatible sequences, converting them
2462 * to the modern Unicode equivalent.
2464 * This is language-specific for performance reasons only.
2470 function normalize( $s ) {
2471 global $wgAllUnicodeFixes;
2472 $s = UtfNormal
::cleanUp( $s );
2473 if ( $wgAllUnicodeFixes ) {
2474 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2475 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2482 * Transform a string using serialized data stored in the given file (which
2483 * must be in the serialized subdirectory of $IP). The file contains pairs
2484 * mapping source characters to destination characters.
2486 * The data is cached in process memory. This will go faster if you have the
2487 * FastStringSearch extension.
2489 * @param $file string
2490 * @param $string string
2494 function transformUsingPairFile( $file, $string ) {
2495 if ( !isset( $this->transformData
[$file] ) ) {
2496 $data = wfGetPrecompiledData( $file );
2497 if ( $data === false ) {
2498 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2500 $this->transformData
[$file] = new ReplacementArray( $data );
2502 return $this->transformData
[$file]->replace( $string );
2506 * For right-to-left language support
2511 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2515 * Return the correct HTML 'dir' attribute value for this language.
2519 return $this->isRTL() ?
'rtl' : 'ltr';
2523 * Return 'left' or 'right' as appropriate alignment for line-start
2524 * for this language's text direction.
2526 * Should be equivalent to CSS3 'start' text-align value....
2530 function alignStart() {
2531 return $this->isRTL() ?
'right' : 'left';
2535 * Return 'right' or 'left' as appropriate alignment for line-end
2536 * for this language's text direction.
2538 * Should be equivalent to CSS3 'end' text-align value....
2542 function alignEnd() {
2543 return $this->isRTL() ?
'left' : 'right';
2547 * A hidden direction mark (LRM or RLM), depending on the language direction
2549 * @param $opposite Boolean Get the direction mark opposite to your language
2552 function getDirMark( $opposite = false ) {
2553 $rtl = "\xE2\x80\x8F";
2554 $ltr = "\xE2\x80\x8E";
2555 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2556 return $this->isRTL() ?
$rtl : $ltr;
2562 function capitalizeAllNouns() {
2563 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2567 * An arrow, depending on the language direction
2571 function getArrow() {
2572 return $this->isRTL() ?
'←' : '→';
2576 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2580 function linkPrefixExtension() {
2581 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2587 function getMagicWords() {
2588 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2591 protected function doMagicHook() {
2592 if ( $this->mMagicHookDone
) {
2595 $this->mMagicHookDone
= true;
2596 wfProfileIn( 'LanguageGetMagic' );
2597 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2598 wfProfileOut( 'LanguageGetMagic' );
2602 * Fill a MagicWord object with data from here
2606 function getMagic( $mw ) {
2607 $this->doMagicHook();
2609 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2610 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2612 $magicWords = $this->getMagicWords();
2613 if ( isset( $magicWords[$mw->mId
] ) ) {
2614 $rawEntry = $magicWords[$mw->mId
];
2620 if ( !is_array( $rawEntry ) ) {
2621 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2623 $mw->mCaseSensitive
= $rawEntry[0];
2624 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2629 * Add magic words to the extension array
2631 * @param $newWords array
2633 function addMagicWordsByLang( $newWords ) {
2634 $fallbackChain = $this->getFallbackLanguages();
2635 $fallbackChain = array_reverse( $fallbackChain );
2636 foreach ( $fallbackChain as $code ) {
2637 if ( isset( $newWords[$code] ) ) {
2638 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2644 * Get special page names, as an associative array
2645 * case folded alias => real name
2647 function getSpecialPageAliases() {
2648 // Cache aliases because it may be slow to load them
2649 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2651 $this->mExtendedSpecialPageAliases
=
2652 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2653 wfRunHooks( 'LanguageGetSpecialPageAliases',
2654 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2657 return $this->mExtendedSpecialPageAliases
;
2661 * Italic is unsuitable for some languages
2663 * @param $text String: the text to be emphasized.
2666 function emphasize( $text ) {
2667 return "<em>$text</em>";
2671 * Normally we output all numbers in plain en_US style, that is
2672 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2673 * point twohundredthirtyfive. However this is not suitable for all
2674 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2675 * Icelandic just want to use commas instead of dots, and dots instead
2676 * of commas like "293.291,235".
2678 * An example of this function being called:
2680 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2683 * See LanguageGu.php for the Gujarati implementation and
2684 * $separatorTransformTable on MessageIs.php for
2685 * the , => . and . => , implementation.
2687 * @todo check if it's viable to use localeconv() for the decimal
2689 * @param $number Mixed: the string to be formatted, should be an integer
2690 * or a floating point number.
2691 * @param $nocommafy Bool: set to true for special numbers like dates
2694 public function formatNum( $number, $nocommafy = false ) {
2695 global $wgTranslateNumerals;
2696 if ( !$nocommafy ) {
2697 $number = $this->commafy( $number );
2698 $s = $this->separatorTransformTable();
2700 $number = strtr( $number, $s );
2704 if ( $wgTranslateNumerals ) {
2705 $s = $this->digitTransformTable();
2707 $number = strtr( $number, $s );
2715 * @param $number string
2718 function parseFormattedNumber( $number ) {
2719 $s = $this->digitTransformTable();
2721 $number = strtr( $number, array_flip( $s ) );
2724 $s = $this->separatorTransformTable();
2726 $number = strtr( $number, array_flip( $s ) );
2729 $number = strtr( $number, array( ',' => '' ) );
2734 * Adds commas to a given number
2739 function commafy( $_ ) {
2740 $digitGroupingPattern = $this->digitGroupingPattern();
2741 if ( $_ === null ) {
2745 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2746 // default grouping is at thousands, use the same for ###,###,### pattern too.
2747 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2749 // Ref: http://cldr.unicode.org/translation/number-patterns
2751 if ( intval( $_ ) < 0 ) {
2752 // For negative numbers apply the algorithm like positive number and add sign.
2754 $_ = substr( $_, 1 );
2756 $numberpart = array();
2757 $decimalpart = array();
2758 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2759 preg_match( "/\d+/", $_, $numberpart );
2760 preg_match( "/\.\d*/", $_, $decimalpart );
2761 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2762 if ( $groupedNumber === $_ ) {
2763 // the string does not have any number part. Eg: .12345
2764 return $sign . $groupedNumber;
2766 $start = $end = strlen( $numberpart[0] );
2767 while ( $start > 0 ) {
2768 $match = $matches[0][$numMatches -1] ;
2769 $matchLen = strlen( $match );
2770 $start = $end - $matchLen;
2774 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2776 if ( $numMatches > 1 ) {
2777 // use the last pattern for the rest of the number
2781 $groupedNumber = "," . $groupedNumber;
2784 return $sign . $groupedNumber;
2790 function digitGroupingPattern() {
2791 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2797 function digitTransformTable() {
2798 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2804 function separatorTransformTable() {
2805 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2809 * Take a list of strings and build a locale-friendly comma-separated
2810 * list, using the local comma-separator message.
2811 * The last two strings are chained with an "and".
2816 function listToText( array $l ) {
2818 $m = count( $l ) - 1;
2820 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2822 for ( $i = $m; $i >= 0; $i-- ) {
2825 } elseif ( $i == $m - 1 ) {
2826 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2828 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2836 * Take a list of strings and build a locale-friendly comma-separated
2837 * list, using the local comma-separator message.
2838 * @param $list array of strings to put in a comma list
2841 function commaList( array $list ) {
2845 array( 'parsemag', 'escapenoentities', 'language' => $this )
2852 * Take a list of strings and build a locale-friendly semicolon-separated
2853 * list, using the local semicolon-separator message.
2854 * @param $list array of strings to put in a semicolon list
2857 function semicolonList( array $list ) {
2860 'semicolon-separator',
2861 array( 'parsemag', 'escapenoentities', 'language' => $this )
2868 * Same as commaList, but separate it with the pipe instead.
2869 * @param $list array of strings to put in a pipe list
2872 function pipeList( array $list ) {
2876 array( 'escapenoentities', 'language' => $this )
2883 * Truncate a string to a specified length in bytes, appending an optional
2884 * string (e.g. for ellipses)
2886 * The database offers limited byte lengths for some columns in the database;
2887 * multi-byte character sets mean we need to ensure that only whole characters
2888 * are included, otherwise broken characters can be passed to the user
2890 * If $length is negative, the string will be truncated from the beginning
2892 * @param $string String to truncate
2893 * @param $length Int: maximum length (including ellipses)
2894 * @param $ellipsis String to append to the truncated text
2895 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2896 * $adjustLength was introduced in 1.18, before that behaved as if false.
2899 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2900 # Use the localized ellipsis character
2901 if ( $ellipsis == '...' ) {
2902 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2904 # Check if there is no need to truncate
2905 if ( $length == 0 ) {
2906 return $ellipsis; // convention
2907 } elseif ( strlen( $string ) <= abs( $length ) ) {
2908 return $string; // no need to truncate
2910 $stringOriginal = $string;
2911 # If ellipsis length is >= $length then we can't apply $adjustLength
2912 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2913 $string = $ellipsis; // this can be slightly unexpected
2914 # Otherwise, truncate and add ellipsis...
2916 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2917 if ( $length > 0 ) {
2918 $length -= $eLength;
2919 $string = substr( $string, 0, $length ); // xyz...
2920 $string = $this->removeBadCharLast( $string );
2921 $string = $string . $ellipsis;
2923 $length +
= $eLength;
2924 $string = substr( $string, $length ); // ...xyz
2925 $string = $this->removeBadCharFirst( $string );
2926 $string = $ellipsis . $string;
2929 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2930 # This check is *not* redundant if $adjustLength, due to the single case where
2931 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2932 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2935 return $stringOriginal;
2940 * Remove bytes that represent an incomplete Unicode character
2941 * at the end of string (e.g. bytes of the char are missing)
2943 * @param $string String
2946 protected function removeBadCharLast( $string ) {
2947 if ( $string != '' ) {
2948 $char = ord( $string[strlen( $string ) - 1] );
2950 if ( $char >= 0xc0 ) {
2951 # We got the first byte only of a multibyte char; remove it.
2952 $string = substr( $string, 0, -1 );
2953 } elseif ( $char >= 0x80 &&
2954 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2955 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2957 # We chopped in the middle of a character; remove it
2965 * Remove bytes that represent an incomplete Unicode character
2966 * at the start of string (e.g. bytes of the char are missing)
2968 * @param $string String
2971 protected function removeBadCharFirst( $string ) {
2972 if ( $string != '' ) {
2973 $char = ord( $string[0] );
2974 if ( $char >= 0x80 && $char < 0xc0 ) {
2975 # We chopped in the middle of a character; remove the whole thing
2976 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2983 * Truncate a string of valid HTML to a specified length in bytes,
2984 * appending an optional string (e.g. for ellipses), and return valid HTML
2986 * This is only intended for styled/linked text, such as HTML with
2987 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2988 * Also, this will not detect things like "display:none" CSS.
2990 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2992 * @param string $text HTML string to truncate
2993 * @param int $length (zero/positive) Maximum length (including ellipses)
2994 * @param string $ellipsis String to append to the truncated text
2997 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2998 # Use the localized ellipsis character
2999 if ( $ellipsis == '...' ) {
3000 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3002 # Check if there is clearly no need to truncate
3003 if ( $length <= 0 ) {
3004 return $ellipsis; // no text shown, nothing to format (convention)
3005 } elseif ( strlen( $text ) <= $length ) {
3006 return $text; // string short enough even *with* HTML (short-circuit)
3009 $dispLen = 0; // innerHTML legth so far
3010 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3011 $tagType = 0; // 0-open, 1-close
3012 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3013 $entityState = 0; // 0-not entity, 1-entity
3014 $tag = $ret = ''; // accumulated tag name, accumulated result string
3015 $openTags = array(); // open tag stack
3016 $maybeState = null; // possible truncation state
3018 $textLen = strlen( $text );
3019 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3020 for ( $pos = 0; true; ++
$pos ) {
3021 # Consider truncation once the display length has reached the maximim.
3022 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3023 # Check that we're not in the middle of a bracket/entity...
3024 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3025 if ( !$testingEllipsis ) {
3026 $testingEllipsis = true;
3027 # Save where we are; we will truncate here unless there turn out to
3028 # be so few remaining characters that truncation is not necessary.
3029 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3030 $maybeState = array( $ret, $openTags ); // save state
3032 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3033 # String in fact does need truncation, the truncation point was OK.
3034 list( $ret, $openTags ) = $maybeState; // reload state
3035 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3036 $ret .= $ellipsis; // add ellipsis
3040 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3042 # Read the next char...
3044 $lastCh = $pos ?
$text[$pos - 1] : '';
3045 $ret .= $ch; // add to result string
3047 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3048 $entityState = 0; // for bad HTML
3049 $bracketState = 1; // tag started (checking for backslash)
3050 } elseif ( $ch == '>' ) {
3051 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3052 $entityState = 0; // for bad HTML
3053 $bracketState = 0; // out of brackets
3054 } elseif ( $bracketState == 1 ) {
3056 $tagType = 1; // close tag (e.g. "</span>")
3058 $tagType = 0; // open tag (e.g. "<span>")
3061 $bracketState = 2; // building tag name
3062 } elseif ( $bracketState == 2 ) {
3066 // Name found (e.g. "<a href=..."), add on tag attributes...
3067 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3069 } elseif ( $bracketState == 0 ) {
3070 if ( $entityState ) {
3073 $dispLen++
; // entity is one displayed char
3076 if ( $neLength == 0 && !$maybeState ) {
3077 // Save state without $ch. We want to *hit* the first
3078 // display char (to get tags) but not *use* it if truncating.
3079 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3082 $entityState = 1; // entity found, (e.g. " ")
3084 $dispLen++
; // this char is displayed
3085 // Add the next $max display text chars after this in one swoop...
3086 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3087 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3088 $dispLen +
= $skipped;
3094 // Close the last tag if left unclosed by bad HTML
3095 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3096 while ( count( $openTags ) > 0 ) {
3097 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3103 * truncateHtml() helper function
3104 * like strcspn() but adds the skipped chars to $ret
3113 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3114 if ( $len === null ) {
3115 $len = -1; // -1 means "no limit" for strcspn
3116 } elseif ( $len < 0 ) {
3120 if ( $start < strlen( $text ) ) {
3121 $skipCount = strcspn( $text, $search, $start, $len );
3122 $ret .= substr( $text, $start, $skipCount );
3128 * truncateHtml() helper function
3129 * (a) push or pop $tag from $openTags as needed
3130 * (b) clear $tag value
3131 * @param &$tag string Current HTML tag name we are looking at
3132 * @param $tagType int (0-open tag, 1-close tag)
3133 * @param $lastCh char|string Character before the '>' that ended this tag
3134 * @param &$openTags array Open tag stack (not accounting for $tag)
3136 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3137 $tag = ltrim( $tag );
3139 if ( $tagType == 0 && $lastCh != '/' ) {
3140 $openTags[] = $tag; // tag opened (didn't close itself)
3141 } elseif ( $tagType == 1 ) {
3142 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3143 array_pop( $openTags ); // tag closed
3151 * Grammatical transformations, needed for inflected languages
3152 * Invoked by putting {{grammar:case|word}} in a message
3154 * @param $word string
3155 * @param $case string
3158 function convertGrammar( $word, $case ) {
3159 global $wgGrammarForms;
3160 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3161 return $wgGrammarForms[$this->getCode()][$case][$word];
3167 * Provides an alternative text depending on specified gender.
3168 * Usage {{gender:username|masculine|feminine|neutral}}.
3169 * username is optional, in which case the gender of current user is used,
3170 * but only in (some) interface messages; otherwise default gender is used.
3171 * If second or third parameter are not specified, masculine is used.
3172 * These details may be overriden per language.
3174 * @param $gender string
3175 * @param $forms array
3179 function gender( $gender, $forms ) {
3180 if ( !count( $forms ) ) {
3183 $forms = $this->preConvertPlural( $forms, 2 );
3184 if ( $gender === 'male' ) {
3187 if ( $gender === 'female' ) {
3190 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3194 * Plural form transformations, needed for some languages.
3195 * For example, there are 3 form of plural in Russian and Polish,
3196 * depending on "count mod 10". See [[w:Plural]]
3197 * For English it is pretty simple.
3199 * Invoked by putting {{plural:count|wordform1|wordform2}}
3200 * or {{plural:count|wordform1|wordform2|wordform3}}
3202 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3204 * @param $count Integer: non-localized number
3205 * @param $forms Array: different plural forms
3206 * @return string Correct form of plural for $count in this language
3208 function convertPlural( $count, $forms ) {
3209 if ( !count( $forms ) ) {
3212 $forms = $this->preConvertPlural( $forms, 2 );
3214 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3218 * Checks that convertPlural was given an array and pads it to requested
3219 * amount of forms by copying the last one.
3221 * @param $count Integer: How many forms should there be at least
3222 * @param $forms Array of forms given to convertPlural
3223 * @return array Padded array of forms or an exception if not an array
3225 protected function preConvertPlural( /* Array */ $forms, $count ) {
3226 while ( count( $forms ) < $count ) {
3227 $forms[] = $forms[count( $forms ) - 1];
3233 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3234 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3235 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3236 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3239 * @param $str String: the validated block duration in English
3240 * @return Somehow translated block duration
3241 * @see LanguageFi.php for example implementation
3243 function translateBlockExpiry( $str ) {
3244 $duration = SpecialBlock
::getSuggestedDurations( $this );
3245 foreach ( $duration as $show => $value ) {
3246 if ( strcmp( $str, $value ) == 0 ) {
3247 return htmlspecialchars( trim( $show ) );
3251 // Since usually only infinite or indefinite is only on list, so try
3252 // equivalents if still here.
3253 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3254 if ( in_array( $str, $indefs ) ) {
3255 foreach ( $indefs as $val ) {
3256 $show = array_search( $val, $duration, true );
3257 if ( $show !== false ) {
3258 return htmlspecialchars( trim( $show ) );
3262 // If all else fails, return the original string.
3267 * languages like Chinese need to be segmented in order for the diff
3270 * @param $text String
3273 public function segmentForDiff( $text ) {
3278 * and unsegment to show the result
3280 * @param $text String
3283 public function unsegmentForDiff( $text ) {
3288 * Return the LanguageConverter used in the Language
3289 * @return LanguageConverter
3291 public function getConverter() {
3292 return $this->mConverter
;
3296 * convert text to all supported variants
3298 * @param $text string
3301 public function autoConvertToAllVariants( $text ) {
3302 return $this->mConverter
->autoConvertToAllVariants( $text );
3306 * convert text to different variants of a language.
3308 * @param $text string
3311 public function convert( $text ) {
3312 return $this->mConverter
->convert( $text );
3316 * Convert a Title object to a string in the preferred variant
3318 * @param $title Title
3321 public function convertTitle( $title ) {
3322 return $this->mConverter
->convertTitle( $title );
3326 * Check if this is a language with variants
3330 public function hasVariants() {
3331 return sizeof( $this->getVariants() ) > 1;
3335 * Check if the language has the specific variant
3336 * @param $variant string
3339 public function hasVariant( $variant ) {
3340 return (bool)$this->mConverter
->validateVariant( $variant );
3344 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3346 * @param $text string
3349 public function armourMath( $text ) {
3350 return $this->mConverter
->armourMath( $text );
3354 * Perform output conversion on a string, and encode for safe HTML output.
3355 * @param $text String text to be converted
3356 * @param $isTitle Bool whether this conversion is for the article title
3358 * @todo this should get integrated somewhere sane
3360 public function convertHtml( $text, $isTitle = false ) {
3361 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3365 * @param $key string
3368 public function convertCategoryKey( $key ) {
3369 return $this->mConverter
->convertCategoryKey( $key );
3373 * Get the list of variants supported by this language
3374 * see sample implementation in LanguageZh.php
3376 * @return array an array of language codes
3378 public function getVariants() {
3379 return $this->mConverter
->getVariants();
3385 public function getPreferredVariant() {
3386 return $this->mConverter
->getPreferredVariant();
3392 public function getDefaultVariant() {
3393 return $this->mConverter
->getDefaultVariant();
3399 public function getURLVariant() {
3400 return $this->mConverter
->getURLVariant();
3404 * If a language supports multiple variants, it is
3405 * possible that non-existing link in one variant
3406 * actually exists in another variant. this function
3407 * tries to find it. See e.g. LanguageZh.php
3409 * @param $link String: the name of the link
3410 * @param $nt Mixed: the title object of the link
3411 * @param $ignoreOtherCond Boolean: to disable other conditions when
3412 * we need to transclude a template or update a category's link
3413 * @return null the input parameters may be modified upon return
3415 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3416 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3420 * If a language supports multiple variants, converts text
3421 * into an array of all possible variants of the text:
3422 * 'variant' => text in that variant
3424 * @deprecated since 1.17 Use autoConvertToAllVariants()
3426 * @param $text string
3430 public function convertLinkToAllVariants( $text ) {
3431 return $this->mConverter
->convertLinkToAllVariants( $text );
3435 * returns language specific options used by User::getPageRenderHash()
3436 * for example, the preferred language variant
3440 function getExtraHashOptions() {
3441 return $this->mConverter
->getExtraHashOptions();
3445 * For languages that support multiple variants, the title of an
3446 * article may be displayed differently in different variants. this
3447 * function returns the apporiate title defined in the body of the article.
3451 public function getParsedTitle() {
3452 return $this->mConverter
->getParsedTitle();
3456 * Enclose a string with the "no conversion" tag. This is used by
3457 * various functions in the Parser
3459 * @param $text String: text to be tagged for no conversion
3460 * @param $noParse bool
3461 * @return string the tagged text
3463 public function markNoConversion( $text, $noParse = false ) {
3464 return $this->mConverter
->markNoConversion( $text, $noParse );
3468 * A regular expression to match legal word-trailing characters
3469 * which should be merged onto a link of the form [[foo]]bar.
3473 public function linkTrail() {
3474 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3480 function getLangObj() {
3485 * Get the RFC 3066 code for this language object
3489 public function getCode() {
3490 return $this->mCode
;
3494 * Get the code in Bcp47 format which we can use
3495 * inside of html lang="" tags.
3499 public function getHtmlCode() {
3500 if ( is_null( $this->mHtmlCode
) ) {
3501 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3503 return $this->mHtmlCode
;
3507 * @param $code string
3509 public function setCode( $code ) {
3510 $this->mCode
= $code;
3511 // Ensure we don't leave an incorrect html code lying around
3512 $this->mHtmlCode
= null;
3516 * Get the name of a file for a certain language code
3517 * @param $prefix string Prepend this to the filename
3518 * @param $code string Language code
3519 * @param $suffix string Append this to the filename
3520 * @return string $prefix . $mangledCode . $suffix
3522 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3523 // Protect against path traversal
3524 if ( !Language
::isValidCode( $code )
3525 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3527 throw new MWException( "Invalid language code \"$code\"" );
3530 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3534 * Get the language code from a file name. Inverse of getFileName()
3535 * @param $filename string $prefix . $languageCode . $suffix
3536 * @param $prefix string Prefix before the language code
3537 * @param $suffix string Suffix after the language code
3538 * @return string Language code, or false if $prefix or $suffix isn't found
3540 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3542 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3543 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3544 if ( !count( $m ) ) {
3547 return str_replace( '_', '-', strtolower( $m[1] ) );
3551 * @param $code string
3554 public static function getMessagesFileName( $code ) {
3556 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3557 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3562 * @param $code string
3565 public static function getClassFileName( $code ) {
3567 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3571 * Get the first fallback for a given language.
3573 * @param $code string
3575 * @return false|string
3577 public static function getFallbackFor( $code ) {
3578 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3581 $fallbacks = self
::getFallbacksFor( $code );
3582 $first = array_shift( $fallbacks );
3588 * Get the ordered list of fallback languages.
3591 * @param $code string Language code
3594 public static function getFallbacksFor( $code ) {
3595 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3598 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3599 $v = array_map( 'trim', explode( ',', $v ) );
3600 if ( $v[count( $v ) - 1] !== 'en' ) {
3608 * Get all messages for a given language
3609 * WARNING: this may take a long time. If you just need all message *keys*
3610 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3612 * @param $code string
3616 public static function getMessagesFor( $code ) {
3617 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3621 * Get a message for a given language
3623 * @param $key string
3624 * @param $code string
3628 public static function getMessageFor( $key, $code ) {
3629 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3633 * Get all message keys for a given language. This is a faster alternative to
3634 * array_keys( Language::getMessagesFor( $code ) )
3637 * @param $code string Language code
3638 * @return array of message keys (strings)
3640 public static function getMessageKeysFor( $code ) {
3641 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3648 function fixVariableInNamespace( $talk ) {
3649 if ( strpos( $talk, '$1' ) === false ) {
3653 global $wgMetaNamespace;
3654 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3656 # Allow grammar transformations
3657 # Allowing full message-style parsing would make simple requests
3658 # such as action=raw much more expensive than they need to be.
3659 # This will hopefully cover most cases.
3660 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3661 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3662 return str_replace( ' ', '_', $talk );
3669 function replaceGrammarInNamespace( $m ) {
3670 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3674 * @throws MWException
3677 static function getCaseMaps() {
3678 static $wikiUpperChars, $wikiLowerChars;
3679 if ( isset( $wikiUpperChars ) ) {
3680 return array( $wikiUpperChars, $wikiLowerChars );
3683 wfProfileIn( __METHOD__
);
3684 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3685 if ( $arr === false ) {
3686 throw new MWException(
3687 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3689 $wikiUpperChars = $arr['wikiUpperChars'];
3690 $wikiLowerChars = $arr['wikiLowerChars'];
3691 wfProfileOut( __METHOD__
);
3692 return array( $wikiUpperChars, $wikiLowerChars );
3696 * Decode an expiry (block, protection, etc) which has come from the DB
3698 * @param $expiry String: Database expiry String
3699 * @param $format Bool|Int true to process using language functions, or TS_ constant
3700 * to return the expiry in a given timestamp
3703 public function formatExpiry( $expiry, $format = true ) {
3704 static $infinity, $infinityMsg;
3705 if ( $infinity === null ) {
3706 $infinityMsg = wfMessage( 'infiniteblock' );
3707 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3710 if ( $expiry == '' ||
$expiry == $infinity ) {
3711 return $format === true
3715 return $format === true
3716 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3717 : wfTimestamp( $format, $expiry );
3723 * @param $seconds int|float
3724 * @param $format Array Optional
3725 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3726 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3727 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3728 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3731 function formatTimePeriod( $seconds, $format = array() ) {
3732 if ( !is_array( $format ) ) {
3733 $format = array( 'avoid' => $format ); // For backwards compatibility
3735 if ( !isset( $format['avoid'] ) ) {
3736 $format['avoid'] = false;
3738 if ( !isset( $format['noabbrevs' ] ) ) {
3739 $format['noabbrevs'] = false;
3741 $secondsMsg = wfMessage(
3742 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3743 $minutesMsg = wfMessage(
3744 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3745 $hoursMsg = wfMessage(
3746 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3747 $daysMsg = wfMessage(
3748 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3750 if ( round( $seconds * 10 ) < 100 ) {
3751 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3752 $s = $secondsMsg->params( $s )->text();
3753 } elseif ( round( $seconds ) < 60 ) {
3754 $s = $this->formatNum( round( $seconds ) );
3755 $s = $secondsMsg->params( $s )->text();
3756 } elseif ( round( $seconds ) < 3600 ) {
3757 $minutes = floor( $seconds / 60 );
3758 $secondsPart = round( fmod( $seconds, 60 ) );
3759 if ( $secondsPart == 60 ) {
3763 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3765 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3766 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3767 $hours = floor( $seconds / 3600 );
3768 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3769 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3770 if ( $secondsPart == 60 ) {
3774 if ( $minutes == 60 ) {
3778 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3780 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3781 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3782 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3785 $days = floor( $seconds / 86400 );
3786 if ( $format['avoid'] === 'avoidminutes' ) {
3787 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3788 if ( $hours == 24 ) {
3792 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3794 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3795 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3796 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3797 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3798 if ( $minutes == 60 ) {
3802 if ( $hours == 24 ) {
3806 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3808 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3810 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3812 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3814 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3821 * Format a bitrate for output, using an appropriate
3822 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3824 * This use base 1000. For base 1024 use formatSize(), for another base
3825 * see formatComputingNumbers()
3830 function formatBitrate( $bps ) {
3831 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3835 * @param $size int Size of the unit
3836 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3837 * @param $messageKey string Message key to be uesd
3840 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3842 return str_replace( '$1', $this->formatNum( $size ),
3843 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3846 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3849 $maxIndex = count( $sizes ) - 1;
3850 while ( $size >= $boundary && $index < $maxIndex ) {
3855 // For small sizes no decimal places necessary
3858 // For MB and bigger two decimal places are smarter
3861 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3863 $size = round( $size, $round );
3864 $text = $this->getMessageFromDB( $msg );
3865 return str_replace( '$1', $this->formatNum( $size ), $text );
3869 * Format a size in bytes for output, using an appropriate
3870 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3872 * This method use base 1024. For base 1000 use formatBitrate(), for
3873 * another base see formatComputingNumbers()
3875 * @param $size int Size to format
3876 * @return string Plain text (not HTML)
3878 function formatSize( $size ) {
3879 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3883 * Make a list item, used by various special pages
3885 * @param $page String Page link
3886 * @param $details String Text between brackets
3887 * @param $oppositedm Boolean Add the direction mark opposite to your
3888 * language, to display text properly
3891 function specialList( $page, $details, $oppositedm = true ) {
3892 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3893 $this->getDirMark();
3894 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3895 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3896 return $page . $details;
3900 * Generate (prev x| next x) (20|50|100...) type links for paging
3902 * @param $title Title object to link
3903 * @param $offset Integer offset parameter
3904 * @param $limit Integer limit parameter
3905 * @param $query String optional URL query parameter string
3906 * @param $atend Bool optional param for specified if this is the last page
3909 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3910 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3912 # Make 'previous' link
3913 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3914 if ( $offset > 0 ) {
3915 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3916 $query, $prev, 'prevn-title', 'mw-prevlink' );
3918 $plink = htmlspecialchars( $prev );
3922 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3924 $nlink = htmlspecialchars( $next );
3926 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3927 $query, $next, 'prevn-title', 'mw-nextlink' );
3930 # Make links to set number of items per page
3931 $numLinks = array();
3932 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
3933 $numLinks[] = $this->numLink( $title, $offset, $num,
3934 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3937 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3938 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
3942 * Helper function for viewPrevNext() that generates links
3944 * @param $title Title object to link
3945 * @param $offset Integer offset parameter
3946 * @param $limit Integer limit parameter
3947 * @param $query Array extra query parameters
3948 * @param $link String text to use for the link; will be escaped
3949 * @param $tooltipMsg String name of the message to use as tooltip
3950 * @param $class String value of the "class" attribute of the link
3951 * @return String HTML fragment
3953 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
3954 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
3955 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3956 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
3957 'title' => $tooltip, 'class' => $class ), $link );
3961 * Get the conversion rule title, if any.
3965 public function getConvRuleTitle() {
3966 return $this->mConverter
->getConvRuleTitle();