3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
38 * Internationalisation code
43 * @var LanguageConverter
47 public $mVariants, $mCode, $mLoaded = false;
48 public $mMagicExtensions = array(), $mMagicHookDone = false;
49 private $mHtmlCode = null, $mParentLanguage = false;
51 public $dateFormatStrings = array();
52 public $mExtendedSpecialPageAliases;
54 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
57 * ReplacementArray object caches
59 public $transformData = array();
62 * @var LocalisationCache
64 static public $dataCache;
66 static public $mLangObjCache = array();
68 static public $mWeekdayMsgs = array(
69 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
73 static public $mWeekdayAbbrevMsgs = array(
74 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
77 static public $mMonthMsgs = array(
78 'january', 'february', 'march', 'april', 'may_long', 'june',
79 'july', 'august', 'september', 'october', 'november',
82 static public $mMonthGenMsgs = array(
83 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
84 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
87 static public $mMonthAbbrevMsgs = array(
88 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
89 'sep', 'oct', 'nov', 'dec'
92 static public $mIranianCalendarMonthMsgs = array(
93 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
94 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
95 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
96 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
99 static public $mHebrewCalendarMonthMsgs = array(
100 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
101 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
102 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
103 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
104 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
107 static public $mHebrewCalendarMonthGenMsgs = array(
108 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
109 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
110 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
111 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
112 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
115 static public $mHijriCalendarMonthMsgs = array(
116 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
117 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
118 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
119 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
126 static public $durationIntervals = array(
127 'millennia' => 31556952000,
128 'centuries' => 3155695200,
129 'decades' => 315569520,
130 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
139 * Cache for language fallbacks.
140 * @see Language::getFallbacksIncludingSiteLanguage
144 static private $fallbackLanguageCache = array();
147 * Cache for language names
148 * @var MapCacheLRU|null
150 static private $languageNameCache;
153 * Get a cached or new language object for a given language code
154 * @param string $code
157 static function factory( $code ) {
158 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
160 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
161 $code = $wgDummyLanguageCodes[$code];
164 // get the language object to process
165 $langObj = isset( self
::$mLangObjCache[$code] )
166 ? self
::$mLangObjCache[$code]
167 : self
::newFromCode( $code );
169 // merge the language object in to get it up front in the cache
170 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
171 // get rid of the oldest ones in case we have an overflow
172 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
178 * Create a language object for a given language code
179 * @param string $code
180 * @throws MWException
183 protected static function newFromCode( $code ) {
184 // Protect against path traversal below
185 if ( !Language
::isValidCode( $code )
186 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code )
188 throw new MWException( "Invalid language code \"$code\"" );
191 if ( !Language
::isValidBuiltInCode( $code ) ) {
192 // It's not possible to customise this code with class files, so
193 // just return a Language object. This is to support uselang= hacks.
194 $lang = new Language
;
195 $lang->setCode( $code );
199 // Check if there is a language class for the code
200 $class = self
::classFromCode( $code );
201 self
::preloadLanguageClass( $class );
202 if ( class_exists( $class ) ) {
207 // Keep trying the fallback list until we find an existing class
208 $fallbacks = Language
::getFallbacksFor( $code );
209 foreach ( $fallbacks as $fallbackCode ) {
210 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
211 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
214 $class = self
::classFromCode( $fallbackCode );
215 self
::preloadLanguageClass( $class );
216 if ( class_exists( $class ) ) {
217 $lang = Language
::newFromCode( $fallbackCode );
218 $lang->setCode( $code );
223 throw new MWException( "Invalid fallback sequence for language '$code'" );
227 * Checks whether any localisation is available for that language tag
228 * in MediaWiki (MessagesXx.php exists).
230 * @param string $code Language tag (in lower case)
231 * @return bool Whether language is supported
234 public static function isSupportedLanguage( $code ) {
235 return self
::isValidBuiltInCode( $code )
236 && ( is_readable( self
::getMessagesFileName( $code ) )
237 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
242 * Returns true if a language code string is a well-formed language tag
243 * according to RFC 5646.
244 * This function only checks well-formedness; it doesn't check that
245 * language, script or variant codes actually exist in the repositories.
247 * Based on regexes by Mark Davis of the Unicode Consortium:
248 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
250 * @param string $code
251 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
256 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
259 $alphanum = '[a-z0-9]';
260 $x = 'x'; # private use singleton
261 $singleton = '[a-wy-z]'; # other singleton
262 $s = $lenient ?
'[-_]' : '-';
264 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
265 $script = "$alpha{4}"; # ISO 15924
266 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
267 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
268 $extension = "$singleton(?:$s$alphanum{2,8})+";
269 $privateUse = "$x(?:$s$alphanum{1,8})+";
271 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
272 # Since these are limited, this is safe even later changes to the registry --
273 # the only oddity is that it might change the type of the tag, and thus
274 # the results from the capturing groups.
275 # http://www.iana.org/assignments/language-subtag-registry
277 $grandfathered = "en{$s}GB{$s}oed"
278 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
279 . "|no{$s}(?:bok|nyn)"
280 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
281 . "|zh{$s}min{$s}nan";
283 $variantList = "$variant(?:$s$variant)*";
284 $extensionList = "$extension(?:$s$extension)*";
286 $langtag = "(?:($language)"
289 . "(?:$s$variantList)?"
290 . "(?:$s$extensionList)?"
291 . "(?:$s$privateUse)?)";
293 # The final breakdown, with capturing groups for each of these components
294 # The variants, extensions, grandfathered, and private-use may have interior '-'
296 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
298 return (bool)preg_match( "/$root/", strtolower( $code ) );
302 * Returns true if a language code string is of a valid form, whether or
303 * not it exists. This includes codes which are used solely for
304 * customisation via the MediaWiki namespace.
306 * @param string $code
310 public static function isValidCode( $code ) {
311 static $cache = array();
312 if ( isset( $cache[$code] ) ) {
313 return $cache[$code];
315 // People think language codes are html safe, so enforce it.
316 // Ideally we should only allow a-zA-Z0-9-
317 // but, .+ and other chars are often used for {{int:}} hacks
318 // see bugs 37564, 37587, 36938
320 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
321 && !preg_match( MediaWikiTitleCodec
::getTitleInvalidRegex(), $code );
323 return $cache[$code];
327 * Returns true if a language code is of a valid form for the purposes of
328 * internal customisation of MediaWiki, via Messages*.php or *.json.
330 * @param string $code
332 * @throws MWException
336 public static function isValidBuiltInCode( $code ) {
338 if ( !is_string( $code ) ) {
339 if ( is_object( $code ) ) {
340 $addmsg = " of class " . get_class( $code );
344 $type = gettype( $code );
345 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
348 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
352 * Returns true if a language code is an IETF tag known to MediaWiki.
359 public static function isKnownLanguageTag( $tag ) {
360 static $coreLanguageNames;
362 // Quick escape for invalid input to avoid exceptions down the line
363 // when code tries to process tags which are not valid at all.
364 if ( !self
::isValidBuiltInCode( $tag ) ) {
368 if ( $coreLanguageNames === null ) {
370 include "$IP/languages/Names.php";
373 if ( isset( $coreLanguageNames[$tag] )
374 || self
::fetchLanguageName( $tag, $tag ) !== ''
383 * @param string $code
384 * @return string Name of the language class
386 public static function classFromCode( $code ) {
387 if ( $code == 'en' ) {
390 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
395 * Includes language class files
397 * @param string $class Name of the language class
399 public static function preloadLanguageClass( $class ) {
402 if ( $class === 'Language' ) {
406 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
407 include_once "$IP/languages/classes/$class.php";
412 * Get the LocalisationCache instance
414 * @return LocalisationCache
416 public static function getLocalisationCache() {
417 if ( is_null( self
::$dataCache ) ) {
418 global $wgLocalisationCacheConf;
419 $class = $wgLocalisationCacheConf['class'];
420 self
::$dataCache = new $class( $wgLocalisationCacheConf );
422 return self
::$dataCache;
425 function __construct() {
426 $this->mConverter
= new FakeConverter( $this );
427 // Set the code to the name of the descendant
428 if ( get_class( $this ) == 'Language' ) {
431 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
433 self
::getLocalisationCache();
437 * Reduce memory usage
439 function __destruct() {
440 foreach ( $this as $name => $value ) {
441 unset( $this->$name );
446 * Hook which will be called if this is the content language.
447 * Descendants can use this to register hook functions or modify globals
449 function initContLang() {
456 function getFallbackLanguages() {
457 return self
::getFallbacksFor( $this->mCode
);
461 * Exports $wgBookstoreListEn
464 function getBookstoreList() {
465 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
469 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
470 * available in localised form, it will be included in English.
474 public function getNamespaces() {
475 if ( is_null( $this->namespaceNames
) ) {
476 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
478 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
479 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
481 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
483 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
484 if ( $wgMetaNamespaceTalk ) {
485 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
487 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
488 $this->namespaceNames
[NS_PROJECT_TALK
] =
489 $this->fixVariableInNamespace( $talk );
492 # Sometimes a language will be localised but not actually exist on this wiki.
493 foreach ( $this->namespaceNames
as $key => $text ) {
494 if ( !isset( $validNamespaces[$key] ) ) {
495 unset( $this->namespaceNames
[$key] );
499 # The above mixing may leave namespaces out of canonical order.
500 # Re-order by namespace ID number...
501 ksort( $this->namespaceNames
);
503 Hooks
::run( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
506 return $this->namespaceNames
;
510 * Arbitrarily set all of the namespace names at once. Mainly used for testing
511 * @param array $namespaces Array of namespaces (id => name)
513 public function setNamespaces( array $namespaces ) {
514 $this->namespaceNames
= $namespaces;
515 $this->mNamespaceIds
= null;
519 * Resets all of the namespace caches. Mainly used for testing
521 public function resetNamespaces() {
522 $this->namespaceNames
= null;
523 $this->mNamespaceIds
= null;
524 $this->namespaceAliases
= null;
528 * A convenience function that returns getNamespaces() with spaces instead of underscores
529 * in values. Useful for producing output to be displayed e.g. in `<select>` forms.
533 function getFormattedNamespaces() {
534 $ns = $this->getNamespaces();
535 foreach ( $ns as $k => $v ) {
536 $ns[$k] = strtr( $v, '_', ' ' );
542 * Get a namespace value by key
545 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
546 * echo $mw_ns; // prints 'MediaWiki'
549 * @param int $index The array key of the namespace to return
550 * @return string|bool String if the namespace value exists, otherwise false
552 function getNsText( $index ) {
553 $ns = $this->getNamespaces();
554 return isset( $ns[$index] ) ?
$ns[$index] : false;
558 * A convenience function that returns the same thing as
559 * getNsText() except with '_' changed to ' ', useful for
563 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
564 * echo $mw_ns; // prints 'MediaWiki talk'
567 * @param int $index The array key of the namespace to return
568 * @return string Namespace name without underscores (empty string if namespace does not exist)
570 function getFormattedNsText( $index ) {
571 $ns = $this->getNsText( $index );
572 return strtr( $ns, '_', ' ' );
576 * Returns gender-dependent namespace alias if available.
577 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
578 * @param int $index Namespace index
579 * @param string $gender Gender key (male, female... )
583 function getGenderNsText( $index, $gender ) {
584 global $wgExtraGenderNamespaces;
586 $ns = $wgExtraGenderNamespaces +
587 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
589 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
593 * Whether this language uses gender-dependent namespace aliases.
594 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
598 function needsGenderDistinction() {
599 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
600 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
601 // $wgExtraGenderNamespaces overrides everything
603 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
604 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
605 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
608 // Check what is in i18n files
609 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
610 return count( $aliases ) > 0;
615 * Get a namespace key by value, case insensitive.
616 * Only matches namespace names for the current language, not the
617 * canonical ones defined in Namespace.php.
619 * @param string $text
620 * @return int|bool An integer if $text is a valid value otherwise false
622 function getLocalNsIndex( $text ) {
623 $lctext = $this->lc( $text );
624 $ids = $this->getNamespaceIds();
625 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
631 function getNamespaceAliases() {
632 if ( is_null( $this->namespaceAliases
) ) {
633 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
637 foreach ( $aliases as $name => $index ) {
638 if ( $index === NS_PROJECT_TALK
) {
639 unset( $aliases[$name] );
640 $name = $this->fixVariableInNamespace( $name );
641 $aliases[$name] = $index;
646 global $wgExtraGenderNamespaces;
647 $genders = $wgExtraGenderNamespaces +
648 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
649 foreach ( $genders as $index => $forms ) {
650 foreach ( $forms as $alias ) {
651 $aliases[$alias] = $index;
655 # Also add converted namespace names as aliases, to avoid confusion.
656 $convertedNames = array();
657 foreach ( $this->getVariants() as $variant ) {
658 if ( $variant === $this->mCode
) {
661 foreach ( $this->getNamespaces() as $ns => $_ ) {
662 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
666 $this->namespaceAliases
= $aliases +
$convertedNames;
669 return $this->namespaceAliases
;
675 function getNamespaceIds() {
676 if ( is_null( $this->mNamespaceIds
) ) {
677 global $wgNamespaceAliases;
678 # Put namespace names and aliases into a hashtable.
679 # If this is too slow, then we should arrange it so that it is done
680 # before caching. The catch is that at pre-cache time, the above
681 # class-specific fixup hasn't been done.
682 $this->mNamespaceIds
= array();
683 foreach ( $this->getNamespaces() as $index => $name ) {
684 $this->mNamespaceIds
[$this->lc( $name )] = $index;
686 foreach ( $this->getNamespaceAliases() as $name => $index ) {
687 $this->mNamespaceIds
[$this->lc( $name )] = $index;
689 if ( $wgNamespaceAliases ) {
690 foreach ( $wgNamespaceAliases as $name => $index ) {
691 $this->mNamespaceIds
[$this->lc( $name )] = $index;
695 return $this->mNamespaceIds
;
699 * Get a namespace key by value, case insensitive. Canonical namespace
700 * names override custom ones defined for the current language.
702 * @param string $text
703 * @return int|bool An integer if $text is a valid value otherwise false
705 function getNsIndex( $text ) {
706 $lctext = $this->lc( $text );
707 $ns = MWNamespace
::getCanonicalIndex( $lctext );
708 if ( $ns !== null ) {
711 $ids = $this->getNamespaceIds();
712 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
716 * short names for language variants used for language conversion links.
718 * @param string $code
719 * @param bool $usemsg Use the "variantname-xyz" message if it exists
722 function getVariantname( $code, $usemsg = true ) {
723 $msg = "variantname-$code";
724 if ( $usemsg && wfMessage( $msg )->exists() ) {
725 return $this->getMessageFromDB( $msg );
727 $name = self
::fetchLanguageName( $code );
729 return $name; # if it's defined as a language name, show that
731 # otherwise, output the language code
737 * @deprecated since 1.24, doesn't handle conflicting aliases. Use
738 * SpecialPageFactory::getLocalNameFor instead.
739 * @param string $name
742 function specialPage( $name ) {
743 $aliases = $this->getSpecialPageAliases();
744 if ( isset( $aliases[$name][0] ) ) {
745 $name = $aliases[$name][0];
747 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
753 function getDatePreferences() {
754 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
760 function getDateFormats() {
761 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
765 * @return array|string
767 function getDefaultDateFormat() {
768 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
769 if ( $df === 'dmy or mdy' ) {
770 global $wgAmericanDates;
771 return $wgAmericanDates ?
'mdy' : 'dmy';
780 function getDatePreferenceMigrationMap() {
781 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
785 * @param string $image
788 function getImageFile( $image ) {
789 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
796 function getImageFiles() {
797 return self
::$dataCache->getItem( $this->mCode
, 'imageFiles' );
803 function getExtraUserToggles() {
804 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
811 function getUserToggle( $tog ) {
812 return $this->getMessageFromDB( "tog-$tog" );
816 * Get native language names, indexed by code.
817 * Only those defined in MediaWiki, no other data like CLDR.
818 * If $customisedOnly is true, only returns codes with a messages file
820 * @param bool $customisedOnly
823 * @deprecated since 1.20, use fetchLanguageNames()
825 public static function getLanguageNames( $customisedOnly = false ) {
826 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
830 * Get translated language names. This is done on best effort and
831 * by default this is exactly the same as Language::getLanguageNames.
832 * The CLDR extension provides translated names.
833 * @param string $code Language code.
834 * @return array Language code => language name
836 * @deprecated since 1.20, use fetchLanguageNames()
838 public static function getTranslatedLanguageNames( $code ) {
839 return self
::fetchLanguageNames( $code, 'all' );
843 * Get an array of language names, indexed by code.
844 * @param null|string $inLanguage Code of language in which to return the names
845 * Use null for autonyms (native names)
846 * @param string $include One of:
847 * 'all' all available languages
848 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
849 * 'mwfile' only if the language is in 'mw' *and* has a message file
850 * @return array Language code => language name
853 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
854 $cacheKey = $inLanguage === null ?
'null' : $inLanguage;
855 $cacheKey .= ":$include";
856 if ( self
::$languageNameCache === null ) {
857 self
::$languageNameCache = new MapCacheLRU( 20 );
859 if ( self
::$languageNameCache->has( $cacheKey ) ) {
860 $ret = self
::$languageNameCache->get( $cacheKey );
862 $ret = self
::fetchLanguageNamesUncached( $inLanguage, $include );
863 self
::$languageNameCache->set( $cacheKey, $ret );
869 * Uncached helper for fetchLanguageNames
870 * @param null|string $inLanguage Code of language in which to return the names
871 * Use null for autonyms (native names)
872 * @param string $include One of:
873 * 'all' all available languages
874 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
875 * 'mwfile' only if the language is in 'mw' *and* has a message file
876 * @return array Language code => language name
878 private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
879 global $wgExtraLanguageNames;
880 static $coreLanguageNames;
882 if ( $coreLanguageNames === null ) {
884 include "$IP/languages/Names.php";
887 // If passed an invalid language code to use, fallback to en
888 if ( $inLanguage !== null && !Language
::isValidCode( $inLanguage ) ) {
895 # TODO: also include when $inLanguage is null, when this code is more efficient
896 Hooks
::run( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
899 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
900 foreach ( $mwNames as $mwCode => $mwName ) {
901 # - Prefer own MediaWiki native name when not using the hook
902 # - For other names just add if not added through the hook
903 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
904 $names[$mwCode] = $mwName;
908 if ( $include === 'all' ) {
914 $coreCodes = array_keys( $mwNames );
915 foreach ( $coreCodes as $coreCode ) {
916 $returnMw[$coreCode] = $names[$coreCode];
919 if ( $include === 'mwfile' ) {
920 $namesMwFile = array();
921 # We do this using a foreach over the codes instead of a directory
922 # loop so that messages files in extensions will work correctly.
923 foreach ( $returnMw as $code => $value ) {
924 if ( is_readable( self
::getMessagesFileName( $code ) )
925 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
927 $namesMwFile[$code] = $names[$code];
931 ksort( $namesMwFile );
936 # 'mw' option; default if it's not one of the other two options (all/mwfile)
941 * @param string $code The code of the language for which to get the name
942 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
943 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
944 * @return string Language name or empty
947 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
948 $code = strtolower( $code );
949 $array = self
::fetchLanguageNames( $inLanguage, $include );
950 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
954 * Get a message from the MediaWiki namespace.
956 * @param string $msg Message name
959 function getMessageFromDB( $msg ) {
960 return $this->msg( $msg )->text();
964 * Get message object in this language. Only for use inside this class.
966 * @param string $msg Message name
969 protected function msg( $msg ) {
970 return wfMessage( $msg )->inLanguage( $this );
974 * Get the native language name of $code.
975 * Only if defined in MediaWiki, no other data like CLDR.
976 * @param string $code
978 * @deprecated since 1.20, use fetchLanguageName()
980 function getLanguageName( $code ) {
981 return self
::fetchLanguageName( $code );
988 function getMonthName( $key ) {
989 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
995 function getMonthNamesArray() {
996 $monthNames = array( '' );
997 for ( $i = 1; $i < 13; $i++
) {
998 $monthNames[] = $this->getMonthName( $i );
1004 * @param string $key
1007 function getMonthNameGen( $key ) {
1008 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
1012 * @param string $key
1015 function getMonthAbbreviation( $key ) {
1016 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
1022 function getMonthAbbreviationsArray() {
1023 $monthNames = array( '' );
1024 for ( $i = 1; $i < 13; $i++
) {
1025 $monthNames[] = $this->getMonthAbbreviation( $i );
1031 * @param string $key
1034 function getWeekdayName( $key ) {
1035 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1039 * @param string $key
1042 function getWeekdayAbbreviation( $key ) {
1043 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1047 * @param string $key
1050 function getIranianCalendarMonthName( $key ) {
1051 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1055 * @param string $key
1058 function getHebrewCalendarMonthName( $key ) {
1059 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1063 * @param string $key
1066 function getHebrewCalendarMonthNameGen( $key ) {
1067 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1071 * @param string $key
1074 function getHijriCalendarMonthName( $key ) {
1075 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1079 * Pass through result from $dateTimeObj->format()
1080 * @param DateTime|bool|null &$dateTimeObj
1082 * @param DateTimeZone|bool|null $zone
1083 * @param string $code
1086 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1087 if ( !$dateTimeObj ) {
1088 $dateTimeObj = DateTime
::createFromFormat(
1089 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1092 return $dateTimeObj->format( $code );
1096 * This is a workalike of PHP's date() function, but with better
1097 * internationalisation, a reduced set of format characters, and a better
1100 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1101 * the PHP manual for definitions. There are a number of extensions, which
1104 * xn Do not translate digits of the next numeric format character
1105 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1106 * xr Use roman numerals for the next numeric format character
1107 * xh Use hebrew numerals for the next numeric format character
1109 * xg Genitive month name
1111 * xij j (day number) in Iranian calendar
1112 * xiF F (month name) in Iranian calendar
1113 * xin n (month number) in Iranian calendar
1114 * xiy y (two digit year) in Iranian calendar
1115 * xiY Y (full year) in Iranian calendar
1117 * xjj j (day number) in Hebrew calendar
1118 * xjF F (month name) in Hebrew calendar
1119 * xjt t (days in month) in Hebrew calendar
1120 * xjx xg (genitive month name) in Hebrew calendar
1121 * xjn n (month number) in Hebrew calendar
1122 * xjY Y (full year) in Hebrew calendar
1124 * xmj j (day number) in Hijri calendar
1125 * xmF F (month name) in Hijri calendar
1126 * xmn n (month number) in Hijri calendar
1127 * xmY Y (full year) in Hijri calendar
1129 * xkY Y (full year) in Thai solar calendar. Months and days are
1130 * identical to the Gregorian calendar
1131 * xoY Y (full year) in Minguo calendar or Juche year.
1132 * Months and days are identical to the
1133 * Gregorian calendar
1134 * xtY Y (full year) in Japanese nengo. Months and days are
1135 * identical to the Gregorian calendar
1137 * Characters enclosed in double quotes will be considered literal (with
1138 * the quotes themselves removed). Unmatched quotes will be considered
1139 * literal quotes. Example:
1141 * "The month is" F => The month is January
1144 * Backslash escaping is also supported.
1146 * Input timestamp is assumed to be pre-normalized to the desired local
1147 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1148 * $ts is UTC if $zone is not given.
1150 * @param string $format
1151 * @param string $ts 14-character timestamp
1154 * @param DateTimeZone $zone Timezone of $ts
1155 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1156 * Only makes sense if $ts is the current time.
1157 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1159 * @throws MWException
1162 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1167 $dateTimeObj = false;
1176 $usedSecond = false;
1177 $usedMinute = false;
1184 $usedISOYear = false;
1185 $usedIsLeapYear = false;
1187 $usedHebrewMonth = false;
1188 $usedIranianMonth = false;
1189 $usedHijriMonth = false;
1190 $usedHebrewYear = false;
1191 $usedIranianYear = false;
1192 $usedHijriYear = false;
1193 $usedTennoYear = false;
1195 if ( strlen( $ts ) !== 14 ) {
1196 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1199 if ( !ctype_digit( $ts ) ) {
1200 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1203 $formatLength = strlen( $format );
1204 for ( $p = 0; $p < $formatLength; $p++
) {
1206 $code = $format[$p];
1207 if ( $code == 'x' && $p < $formatLength - 1 ) {
1208 $code .= $format[++
$p];
1211 if ( ( $code === 'xi'
1217 && $p < $formatLength - 1 ) {
1218 $code .= $format[++
$p];
1229 $rawToggle = !$rawToggle;
1239 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1242 $usedHebrewMonth = true;
1244 $hebrew = self
::tsToHebrew( $ts );
1246 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1250 $num = substr( $ts, 6, 2 );
1254 $s .= $this->getWeekdayAbbreviation(
1255 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1
1260 $num = intval( substr( $ts, 6, 2 ) );
1265 $iranian = self
::tsToIranian( $ts );
1272 $hijri = self
::tsToHijri( $ts );
1279 $hebrew = self
::tsToHebrew( $ts );
1285 $s .= $this->getWeekdayName(
1286 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1
1291 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1294 $usedIranianMonth = true;
1296 $iranian = self
::tsToIranian( $ts );
1298 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1301 $usedHijriMonth = true;
1303 $hijri = self
::tsToHijri( $ts );
1305 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1308 $usedHebrewMonth = true;
1310 $hebrew = self
::tsToHebrew( $ts );
1312 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1316 $num = substr( $ts, 4, 2 );
1320 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1324 $num = intval( substr( $ts, 4, 2 ) );
1327 $usedIranianMonth = true;
1329 $iranian = self
::tsToIranian( $ts );
1334 $usedHijriMonth = true;
1336 $hijri = self
::tsToHijri( $ts );
1341 $usedHebrewMonth = true;
1343 $hebrew = self
::tsToHebrew( $ts );
1348 $usedHebrewMonth = true;
1350 $hebrew = self
::tsToHebrew( $ts );
1356 $num = substr( $ts, 0, 4 );
1359 $usedIranianYear = true;
1361 $iranian = self
::tsToIranian( $ts );
1366 $usedHijriYear = true;
1368 $hijri = self
::tsToHijri( $ts );
1373 $usedHebrewYear = true;
1375 $hebrew = self
::tsToHebrew( $ts );
1382 $thai = self
::tsToYear( $ts, 'thai' );
1389 $minguo = self
::tsToYear( $ts, 'minguo' );
1394 $usedTennoYear = true;
1396 $tenno = self
::tsToYear( $ts, 'tenno' );
1402 $num = substr( $ts, 2, 2 );
1405 $usedIranianYear = true;
1407 $iranian = self
::tsToIranian( $ts );
1409 $num = substr( $iranian[0], -2 );
1413 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1417 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1421 $h = substr( $ts, 8, 2 );
1422 $num = $h %
12 ?
$h %
12 : 12;
1426 $num = intval( substr( $ts, 8, 2 ) );
1430 $h = substr( $ts, 8, 2 );
1431 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1435 $num = substr( $ts, 8, 2 );
1439 $num = substr( $ts, 10, 2 );
1443 $num = substr( $ts, 12, 2 );
1453 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1459 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1463 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1467 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1470 $usedIsLeapYear = true;
1471 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1474 $usedISOYear = true;
1475 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1482 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1485 # Backslash escaping
1486 if ( $p < $formatLength - 1 ) {
1487 $s .= $format[++
$p];
1494 if ( $p < $formatLength - 1 ) {
1495 $endQuote = strpos( $format, '"', $p +
1 );
1496 if ( $endQuote === false ) {
1497 # No terminating quote, assume literal "
1500 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1504 # Quote at end of string, assume literal "
1511 if ( $num !== false ) {
1512 if ( $rawToggle ||
$raw ) {
1515 } elseif ( $roman ) {
1516 $s .= Language
::romanNumeral( $num );
1518 } elseif ( $hebrewNum ) {
1519 $s .= self
::hebrewNumeral( $num );
1522 $s .= $this->formatNum( $num, true );
1527 if ( $usedSecond ) {
1529 } elseif ( $usedMinute ) {
1530 $ttl = 60 - substr( $ts, 12, 2 );
1531 } elseif ( $usedHour ) {
1532 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1533 } elseif ( $usedAMPM ) {
1534 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 -
1535 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1539 $usedIranianMonth ||
1546 // @todo Someone who understands the non-Gregorian calendars
1547 // should write proper logic for them so that they don't need purged every day.
1548 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1549 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1551 $possibleTtls = array();
1552 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1553 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1556 ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1557 $timeRemainingInDay;
1558 } elseif ( $usedISOYear ) {
1559 // December 28th falls on the last ISO week of the year, every year.
1560 // The last ISO week of a year can be 52 or 53.
1561 $lastWeekOfISOYear = DateTime
::createFromFormat(
1563 substr( $ts, 0, 4 ) . '1228',
1564 $zone ?
: new DateTimeZone( 'UTC' )
1566 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1567 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1568 $timeRemainingInWeek =
1569 ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1570 +
$timeRemainingInDay;
1571 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1576 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1577 substr( $ts, 6, 2 ) ) * 86400
1578 +
$timeRemainingInDay;
1579 } elseif ( $usedYear ) {
1581 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 -
1582 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1583 +
$timeRemainingInDay;
1584 } elseif ( $usedIsLeapYear ) {
1585 $year = substr( $ts, 0, 4 );
1586 $timeRemainingInYear =
1587 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 -
1588 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1589 +
$timeRemainingInDay;
1591 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1592 // this isn't a leap year. see when the next one starts
1593 $nextCandidate = $year - $mod +
4;
1594 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1595 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1596 $timeRemainingInYear;
1598 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
1599 $timeRemainingInYear;
1602 // this is a leap year, so the next year isn't
1603 $possibleTtls[] = $timeRemainingInYear;
1607 if ( $possibleTtls ) {
1608 $ttl = min( $possibleTtls );
1615 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1616 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1619 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1620 * Gregorian dates to Iranian dates. Originally written in C, it
1621 * is released under the terms of GNU Lesser General Public
1622 * License. Conversion to PHP was performed by Niklas Laxström.
1624 * Link: http://www.farsiweb.info/jalali/jalali.c
1630 private static function tsToIranian( $ts ) {
1631 $gy = substr( $ts, 0, 4 ) -1600;
1632 $gm = substr( $ts, 4, 2 ) -1;
1633 $gd = substr( $ts, 6, 2 ) -1;
1635 # Days passed from the beginning (including leap years)
1637 +
floor( ( $gy +
3 ) / 4 )
1638 - floor( ( $gy +
99 ) / 100 )
1639 +
floor( ( $gy +
399 ) / 400 );
1641 // Add days of the past months of this year
1642 for ( $i = 0; $i < $gm; $i++
) {
1643 $gDayNo +
= self
::$GREG_DAYS[$i];
1647 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1651 // Days passed in current month
1652 $gDayNo +
= (int)$gd;
1654 $jDayNo = $gDayNo - 79;
1656 $jNp = floor( $jDayNo / 12053 );
1659 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1662 if ( $jDayNo >= 366 ) {
1663 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1664 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1667 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1668 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1674 return array( $jy, $jm, $jd );
1678 * Converting Gregorian dates to Hijri dates.
1680 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1682 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1688 private static function tsToHijri( $ts ) {
1689 $year = substr( $ts, 0, 4 );
1690 $month = substr( $ts, 4, 2 );
1691 $day = substr( $ts, 6, 2 );
1699 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1700 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1702 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1703 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1704 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1707 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1708 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1711 $zl = $zjd -1948440 +
10632;
1712 $zn = (int)( ( $zl - 1 ) / 10631 );
1713 $zl = $zl - 10631 * $zn +
354;
1714 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1715 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1716 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1717 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1718 $zm = (int)( ( 24 * $zl ) / 709 );
1719 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1720 $zy = 30 * $zn +
$zj - 30;
1722 return array( $zy, $zm, $zd );
1726 * Converting Gregorian dates to Hebrew dates.
1728 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1729 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1730 * to translate the relevant functions into PHP and release them under
1733 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1734 * and Adar II is 14. In a non-leap year, Adar is 6.
1740 private static function tsToHebrew( $ts ) {
1742 $year = substr( $ts, 0, 4 );
1743 $month = substr( $ts, 4, 2 );
1744 $day = substr( $ts, 6, 2 );
1746 # Calculate Hebrew year
1747 $hebrewYear = $year +
3760;
1749 # Month number when September = 1, August = 12
1751 if ( $month > 12 ) {
1758 # Calculate day of year from 1 September
1760 for ( $i = 1; $i < $month; $i++
) {
1764 # Check if the year is leap
1765 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1768 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1775 # Calculate the start of the Hebrew year
1776 $start = self
::hebrewYearStart( $hebrewYear );
1778 # Calculate next year's start
1779 if ( $dayOfYear <= $start ) {
1780 # Day is before the start of the year - it is the previous year
1782 $nextStart = $start;
1786 # Add days since previous year's 1 September
1788 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1792 # Start of the new (previous) year
1793 $start = self
::hebrewYearStart( $hebrewYear );
1796 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1799 # Calculate Hebrew day of year
1800 $hebrewDayOfYear = $dayOfYear - $start;
1802 # Difference between year's days
1803 $diff = $nextStart - $start;
1804 # Add 12 (or 13 for leap years) days to ignore the difference between
1805 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1806 # difference is only about the year type
1807 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1813 # Check the year pattern, and is leap year
1814 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1815 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1816 # and non-leap years
1817 $yearPattern = $diff %
30;
1818 # Check if leap year
1819 $isLeap = $diff >= 30;
1821 # Calculate day in the month from number of day in the Hebrew year
1822 # Don't check Adar - if the day is not in Adar, we will stop before;
1823 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1824 $hebrewDay = $hebrewDayOfYear;
1827 while ( $hebrewMonth <= 12 ) {
1828 # Calculate days in this month
1829 if ( $isLeap && $hebrewMonth == 6 ) {
1830 # Adar in a leap year
1832 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1834 if ( $hebrewDay <= $days ) {
1838 # Subtract the days of Adar I
1839 $hebrewDay -= $days;
1842 if ( $hebrewDay <= $days ) {
1848 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1849 # Cheshvan in a complete year (otherwise as the rule below)
1851 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1852 # Kislev in an incomplete year (otherwise as the rule below)
1855 # Odd months have 30 days, even have 29
1856 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1858 if ( $hebrewDay <= $days ) {
1859 # In the current month
1862 # Subtract the days of the current month
1863 $hebrewDay -= $days;
1864 # Try in the next month
1869 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1873 * This calculates the Hebrew year start, as days since 1 September.
1874 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1875 * Used for Hebrew date.
1881 private static function hebrewYearStart( $year ) {
1882 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1883 $b = intval( ( $year - 1 ) %
4 );
1884 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1888 $Mar = intval( $m );
1894 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1895 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1897 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1899 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1903 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1908 * Algorithm to convert Gregorian dates to Thai solar dates,
1909 * Minguo dates or Minguo dates.
1911 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1912 * http://en.wikipedia.org/wiki/Minguo_calendar
1913 * http://en.wikipedia.org/wiki/Japanese_era_name
1915 * @param string $ts 14-character timestamp
1916 * @param string $cName Calender name
1917 * @return array Converted year, month, day
1919 private static function tsToYear( $ts, $cName ) {
1920 $gy = substr( $ts, 0, 4 );
1921 $gm = substr( $ts, 4, 2 );
1922 $gd = substr( $ts, 6, 2 );
1924 if ( !strcmp( $cName, 'thai' ) ) {
1926 # Add 543 years to the Gregorian calendar
1927 # Months and days are identical
1928 $gy_offset = $gy +
543;
1929 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1931 # Deduct 1911 years from the Gregorian calendar
1932 # Months and days are identical
1933 $gy_offset = $gy - 1911;
1934 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1935 # Nengō dates up to Meiji period
1936 # Deduct years from the Gregorian calendar
1937 # depending on the nengo periods
1938 # Months and days are identical
1940 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1941 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1944 $gy_gannen = $gy - 1868 +
1;
1945 $gy_offset = $gy_gannen;
1946 if ( $gy_gannen == 1 ) {
1949 $gy_offset = '明治' . $gy_offset;
1951 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1952 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1953 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1954 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1955 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1958 $gy_gannen = $gy - 1912 +
1;
1959 $gy_offset = $gy_gannen;
1960 if ( $gy_gannen == 1 ) {
1963 $gy_offset = '大正' . $gy_offset;
1965 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1966 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1967 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1970 $gy_gannen = $gy - 1926 +
1;
1971 $gy_offset = $gy_gannen;
1972 if ( $gy_gannen == 1 ) {
1975 $gy_offset = '昭和' . $gy_offset;
1978 $gy_gannen = $gy - 1989 +
1;
1979 $gy_offset = $gy_gannen;
1980 if ( $gy_gannen == 1 ) {
1983 $gy_offset = '平成' . $gy_offset;
1989 return array( $gy_offset, $gm, $gd );
1993 * Roman number formatting up to 10000
1999 static function romanNumeral( $num ) {
2000 static $table = array(
2001 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
2002 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
2003 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
2004 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
2005 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
2008 $num = intval( $num );
2009 if ( $num > 10000 ||
$num <= 0 ) {
2014 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2015 if ( $num >= $pow10 ) {
2016 $s .= $table[$i][(int)floor( $num / $pow10 )];
2018 $num = $num %
$pow10;
2024 * Hebrew Gematria number formatting up to 9999
2030 static function hebrewNumeral( $num ) {
2031 static $table = array(
2032 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
2033 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
2043 array( 'ת', 'ת', 'ק' ),
2044 array( 'ת', 'ת', 'ר' ),
2046 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
2049 $num = intval( $num );
2050 if ( $num > 9999 ||
$num <= 0 ) {
2054 // Round thousands have special notations
2055 if ( $num === 1000 ) {
2057 } elseif ( $num %
1000 === 0 ) {
2058 return $table[0][$num / 1000] . "' אלפים";
2063 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2064 if ( $num >= $pow10 ) {
2065 if ( $num === 15 ||
$num === 16 ) {
2066 $letters[] = $table[0][9];
2067 $letters[] = $table[0][$num - 9];
2070 $letters = array_merge(
2072 (array)$table[$i][intval( $num / $pow10 )]
2075 if ( $pow10 === 1000 ) {
2081 $num = $num %
$pow10;
2084 $preTransformLength = count( $letters );
2085 if ( $preTransformLength === 1 ) {
2086 // Add geresh (single quote) to one-letter numbers
2089 $lastIndex = $preTransformLength - 1;
2090 $letters[$lastIndex] = str_replace(
2091 array( 'כ', 'מ', 'נ', 'פ', 'צ' ),
2092 array( 'ך', 'ם', 'ן', 'ף', 'ץ' ),
2093 $letters[$lastIndex]
2096 // Add gershayim (double quote) to multiple-letter numbers,
2097 // but exclude numbers with only one letter after the thousands
2098 // (1001-1009, 1020, 1030, 2001-2009, etc.)
2099 if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2102 array_splice( $letters, -1, 0, '"' );
2106 return implode( $letters );
2110 * Used by date() and time() to adjust the time output.
2112 * @param string $ts The time in date('YmdHis') format
2113 * @param mixed $tz Adjust the time by this amount (default false, mean we
2114 * get user timecorrection setting)
2117 function userAdjust( $ts, $tz = false ) {
2118 global $wgUser, $wgLocalTZoffset;
2120 if ( $tz === false ) {
2121 $tz = $wgUser->getOption( 'timecorrection' );
2124 $data = explode( '|', $tz, 3 );
2126 if ( $data[0] == 'ZoneInfo' ) {
2127 MediaWiki\
suppressWarnings();
2128 $userTZ = timezone_open( $data[2] );
2129 MediaWiki\restoreWarnings
();
2130 if ( $userTZ !== false ) {
2131 $date = date_create( $ts, timezone_open( 'UTC' ) );
2132 date_timezone_set( $date, $userTZ );
2133 $date = date_format( $date, 'YmdHis' );
2136 # Unrecognized timezone, default to 'Offset' with the stored offset.
2137 $data[0] = 'Offset';
2140 if ( $data[0] == 'System' ||
$tz == '' ) {
2141 # Global offset in minutes.
2142 $minDiff = $wgLocalTZoffset;
2143 } elseif ( $data[0] == 'Offset' ) {
2144 $minDiff = intval( $data[1] );
2146 $data = explode( ':', $tz );
2147 if ( count( $data ) == 2 ) {
2148 $data[0] = intval( $data[0] );
2149 $data[1] = intval( $data[1] );
2150 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2151 if ( $data[0] < 0 ) {
2152 $minDiff = -$minDiff;
2155 $minDiff = intval( $data[0] ) * 60;
2159 # No difference ? Return time unchanged
2160 if ( 0 == $minDiff ) {
2164 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
2165 # Generate an adjusted date; take advantage of the fact that mktime
2166 # will normalize out-of-range values so we don't have to split $minDiff
2167 # into hours and minutes.
2169 (int)substr( $ts, 8, 2 ) ), # Hours
2170 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2171 (int)substr( $ts, 12, 2 ), # Seconds
2172 (int)substr( $ts, 4, 2 ), # Month
2173 (int)substr( $ts, 6, 2 ), # Day
2174 (int)substr( $ts, 0, 4 ) ); # Year
2176 $date = date( 'YmdHis', $t );
2177 MediaWiki\restoreWarnings
();
2183 * This is meant to be used by time(), date(), and timeanddate() to get
2184 * the date preference they're supposed to use, it should be used in
2188 * function timeanddate([...], $format = true) {
2189 * $datePreference = $this->dateFormat($format);
2194 * @param int|string|bool $usePrefs If true, the user's preference is used
2195 * if false, the site/language default is used
2196 * if int/string, assumed to be a format.
2199 function dateFormat( $usePrefs = true ) {
2202 if ( is_bool( $usePrefs ) ) {
2204 $datePreference = $wgUser->getDatePreference();
2206 $datePreference = (string)User
::getDefaultOption( 'date' );
2209 $datePreference = (string)$usePrefs;
2213 if ( $datePreference == '' ) {
2217 return $datePreference;
2221 * Get a format string for a given type and preference
2222 * @param string $type May be date, time or both
2223 * @param string $pref The format name as it appears in Messages*.php
2225 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2229 function getDateFormatString( $type, $pref ) {
2230 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2231 if ( $pref == 'default' ) {
2232 $pref = $this->getDefaultDateFormat();
2233 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2235 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2237 if ( $type === 'pretty' && $df === null ) {
2238 $df = $this->getDateFormatString( 'date', $pref );
2241 if ( $df === null ) {
2242 $pref = $this->getDefaultDateFormat();
2243 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2246 $this->dateFormatStrings
[$type][$pref] = $df;
2248 return $this->dateFormatStrings
[$type][$pref];
2252 * @param string $ts The time format which needs to be turned into a
2253 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2254 * @param bool $adj Whether to adjust the time output according to the
2255 * user configured offset ($timecorrection)
2256 * @param mixed $format True to use user's date format preference
2257 * @param string|bool $timecorrection The time offset as returned by
2258 * validateTimeZone() in Special:Preferences
2261 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2262 $ts = wfTimestamp( TS_MW
, $ts );
2264 $ts = $this->userAdjust( $ts, $timecorrection );
2266 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2267 return $this->sprintfDate( $df, $ts );
2271 * @param string $ts The time format which needs to be turned into a
2272 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2273 * @param bool $adj Whether to adjust the time output according to the
2274 * user configured offset ($timecorrection)
2275 * @param mixed $format True to use user's date format preference
2276 * @param string|bool $timecorrection The time offset as returned by
2277 * validateTimeZone() in Special:Preferences
2280 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2281 $ts = wfTimestamp( TS_MW
, $ts );
2283 $ts = $this->userAdjust( $ts, $timecorrection );
2285 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2286 return $this->sprintfDate( $df, $ts );
2290 * @param string $ts The time format which needs to be turned into a
2291 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2292 * @param bool $adj Whether to adjust the time output according to the
2293 * user configured offset ($timecorrection)
2294 * @param mixed $format What format to return, if it's false output the
2295 * default one (default true)
2296 * @param string|bool $timecorrection The time offset as returned by
2297 * validateTimeZone() in Special:Preferences
2300 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2301 $ts = wfTimestamp( TS_MW
, $ts );
2303 $ts = $this->userAdjust( $ts, $timecorrection );
2305 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2306 return $this->sprintfDate( $df, $ts );
2310 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2314 * @param int $seconds The amount of seconds.
2315 * @param array $chosenIntervals The intervals to enable.
2319 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2320 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2322 $segments = array();
2324 foreach ( $intervals as $intervalName => $intervalValue ) {
2325 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2326 // duration-years, duration-decades, duration-centuries, duration-millennia
2327 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2328 $segments[] = $message->inLanguage( $this )->escaped();
2331 return $this->listToText( $segments );
2335 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2336 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2340 * @param int $seconds The amount of seconds.
2341 * @param array $chosenIntervals The intervals to enable.
2345 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2346 if ( empty( $chosenIntervals ) ) {
2347 $chosenIntervals = array(
2359 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2360 $sortedNames = array_keys( $intervals );
2361 $smallestInterval = array_pop( $sortedNames );
2363 $segments = array();
2365 foreach ( $intervals as $name => $length ) {
2366 $value = floor( $seconds / $length );
2368 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2369 $seconds -= $value * $length;
2370 $segments[$name] = $value;
2378 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2380 * @param string $type Can be 'date', 'time' or 'both'
2381 * @param string $ts The time format which needs to be turned into a
2382 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2383 * @param User $user User object used to get preferences for timezone and format
2384 * @param array $options Array, can contain the following keys:
2385 * - 'timecorrection': time correction, can have the following values:
2386 * - true: use user's preference
2387 * - false: don't use time correction
2388 * - int: value of time correction in minutes
2389 * - 'format': format to use, can have the following values:
2390 * - true: use user's preference
2391 * - false: use default preference
2392 * - string: format to use
2396 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2397 $ts = wfTimestamp( TS_MW
, $ts );
2398 $options +
= array( 'timecorrection' => true, 'format' => true );
2399 if ( $options['timecorrection'] !== false ) {
2400 if ( $options['timecorrection'] === true ) {
2401 $offset = $user->getOption( 'timecorrection' );
2403 $offset = $options['timecorrection'];
2405 $ts = $this->userAdjust( $ts, $offset );
2407 if ( $options['format'] === true ) {
2408 $format = $user->getDatePreference();
2410 $format = $options['format'];
2412 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2413 return $this->sprintfDate( $df, $ts );
2417 * Get the formatted date for the given timestamp and formatted for
2420 * @param mixed $ts Mixed: the time format which needs to be turned into a
2421 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2422 * @param User $user User object used to get preferences for timezone and format
2423 * @param array $options Array, can contain the following keys:
2424 * - 'timecorrection': time correction, can have the following values:
2425 * - true: use user's preference
2426 * - false: don't use time correction
2427 * - int: value of time correction in minutes
2428 * - 'format': format to use, can have the following values:
2429 * - true: use user's preference
2430 * - false: use default preference
2431 * - string: format to use
2435 public function userDate( $ts, User
$user, array $options = array() ) {
2436 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2440 * Get the formatted time for the given timestamp and formatted for
2443 * @param mixed $ts The time format which needs to be turned into a
2444 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2445 * @param User $user User object used to get preferences for timezone and format
2446 * @param array $options Array, can contain the following keys:
2447 * - 'timecorrection': time correction, can have the following values:
2448 * - true: use user's preference
2449 * - false: don't use time correction
2450 * - int: value of time correction in minutes
2451 * - 'format': format to use, can have the following values:
2452 * - true: use user's preference
2453 * - false: use default preference
2454 * - string: format to use
2458 public function userTime( $ts, User
$user, array $options = array() ) {
2459 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2463 * Get the formatted date and time for the given timestamp and formatted for
2466 * @param mixed $ts The time format which needs to be turned into a
2467 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2468 * @param User $user User object used to get preferences for timezone and format
2469 * @param array $options Array, can contain the following keys:
2470 * - 'timecorrection': time correction, can have the following values:
2471 * - true: use user's preference
2472 * - false: don't use time correction
2473 * - int: value of time correction in minutes
2474 * - 'format': format to use, can have the following values:
2475 * - true: use user's preference
2476 * - false: use default preference
2477 * - string: format to use
2481 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2482 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2486 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
2488 * Determine the difference between the timestamp and the current time, and
2489 * generate a readable timestamp by returning "<N> <units> ago", where the
2490 * largest possible unit is used.
2492 * @since 1.26 (Prior to 1.26 method existed but was not meant to be used directly)
2494 * @param MWTimestamp $time
2495 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
2496 * @param User|null $user User the timestamp is being generated for (or null to use main context's user)
2497 * @return string Formatted timestamp
2499 public function getHumanTimestamp( MWTimestamp
$time, MWTimestamp
$relativeTo = null, User
$user = null ) {
2500 if ( $relativeTo === null ) {
2501 $relativeTo = new MWTimestamp();
2503 if ( $user === null ) {
2504 $user = RequestContext
::getMain()->getUser();
2507 // Adjust for the user's timezone.
2508 $offsetThis = $time->offsetForUser( $user );
2509 $offsetRel = $relativeTo->offsetForUser( $user );
2512 if ( Hooks
::run( 'GetHumanTimestamp', array( &$ts, $time, $relativeTo, $user, $this ) ) ) {
2513 $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2516 // Reset the timezone on the objects.
2517 $time->timestamp
->sub( $offsetThis );
2518 $relativeTo->timestamp
->sub( $offsetRel );
2524 * Convert an MWTimestamp into a pretty human-readable timestamp using
2525 * the given user preferences and relative base time.
2527 * @see Language::getHumanTimestamp
2528 * @param MWTimestamp $ts Timestamp to prettify
2529 * @param MWTimestamp $relativeTo Base timestamp
2530 * @param User $user User preferences to use
2531 * @return string Human timestamp
2534 private function getHumanTimestampInternal( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2535 $diff = $ts->diff( $relativeTo );
2536 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2537 (int)$relativeTo->timestamp
->format( 'w' ) );
2538 $days = $diff->days ?
: (int)$diffDay;
2539 if ( $diff->invert ||
$days > 5
2540 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2542 // Timestamps are in different years: use full timestamp
2543 // Also do full timestamp for future dates
2545 * @todo FIXME: Add better handling of future timestamps.
2547 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2548 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2549 } elseif ( $days > 5 ) {
2550 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2551 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2552 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2553 } elseif ( $days > 1 ) {
2554 // Timestamp within the past week: show the day of the week and time
2555 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2556 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2558 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2559 $ts = wfMessage( "$weekday-at" )
2560 ->inLanguage( $this )
2561 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2563 } elseif ( $days == 1 ) {
2564 // Timestamp was yesterday: say 'yesterday' and the time.
2565 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2566 $ts = wfMessage( 'yesterday-at' )
2567 ->inLanguage( $this )
2568 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2570 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2571 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2572 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2573 $ts = wfMessage( 'today-at' )
2574 ->inLanguage( $this )
2575 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2578 // From here on in, the timestamp was soon enough ago so that we can simply say
2579 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2580 } elseif ( $diff->h
== 1 ) {
2581 // Less than 90 minutes, but more than an hour ago.
2582 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2583 } elseif ( $diff->i
>= 1 ) {
2584 // A few minutes ago.
2585 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2586 } elseif ( $diff->s
>= 30 ) {
2587 // Less than a minute, but more than 30 sec ago.
2588 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2590 // Less than 30 seconds ago.
2591 $ts = wfMessage( 'just-now' )->text();
2598 * @param string $key
2599 * @return array|null
2601 function getMessage( $key ) {
2602 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2608 function getAllMessages() {
2609 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2614 * @param string $out
2615 * @param string $string
2618 function iconv( $in, $out, $string ) {
2619 # This is a wrapper for iconv in all languages except esperanto,
2620 # which does some nasty x-conversions beforehand
2622 # Even with //IGNORE iconv can whine about illegal characters in
2623 # *input* string. We just ignore those too.
2624 # REF: http://bugs.php.net/bug.php?id=37166
2625 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2626 MediaWiki\
suppressWarnings();
2627 $text = iconv( $in, $out . '//IGNORE', $string );
2628 MediaWiki\restoreWarnings
();
2632 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2635 * @param array $matches
2636 * @return mixed|string
2638 function ucwordbreaksCallbackAscii( $matches ) {
2639 return $this->ucfirst( $matches[1] );
2643 * @param array $matches
2646 function ucwordbreaksCallbackMB( $matches ) {
2647 return mb_strtoupper( $matches[0] );
2651 * @param array $matches
2654 function ucCallback( $matches ) {
2655 list( $wikiUpperChars ) = self
::getCaseMaps();
2656 return strtr( $matches[1], $wikiUpperChars );
2660 * @param array $matches
2663 function lcCallback( $matches ) {
2664 list( , $wikiLowerChars ) = self
::getCaseMaps();
2665 return strtr( $matches[1], $wikiLowerChars );
2669 * @param array $matches
2672 function ucwordsCallbackMB( $matches ) {
2673 return mb_strtoupper( $matches[0] );
2677 * @param array $matches
2680 function ucwordsCallbackWiki( $matches ) {
2681 list( $wikiUpperChars ) = self
::getCaseMaps();
2682 return strtr( $matches[0], $wikiUpperChars );
2686 * Make a string's first character uppercase
2688 * @param string $str
2692 function ucfirst( $str ) {
2694 if ( $o < 96 ) { // if already uppercase...
2696 } elseif ( $o < 128 ) {
2697 return ucfirst( $str ); // use PHP's ucfirst()
2699 // fall back to more complex logic in case of multibyte strings
2700 return $this->uc( $str, true );
2705 * Convert a string to uppercase
2707 * @param string $str
2708 * @param bool $first
2712 function uc( $str, $first = false ) {
2713 if ( function_exists( 'mb_strtoupper' ) ) {
2715 if ( $this->isMultibyte( $str ) ) {
2716 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2718 return ucfirst( $str );
2721 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2724 if ( $this->isMultibyte( $str ) ) {
2725 $x = $first ?
'^' : '';
2726 return preg_replace_callback(
2727 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2728 array( $this, 'ucCallback' ),
2732 return $first ?
ucfirst( $str ) : strtoupper( $str );
2738 * @param string $str
2739 * @return mixed|string
2741 function lcfirst( $str ) {
2744 return strval( $str );
2745 } elseif ( $o >= 128 ) {
2746 return $this->lc( $str, true );
2747 } elseif ( $o > 96 ) {
2750 $str[0] = strtolower( $str[0] );
2756 * @param string $str
2757 * @param bool $first
2758 * @return mixed|string
2760 function lc( $str, $first = false ) {
2761 if ( function_exists( 'mb_strtolower' ) ) {
2763 if ( $this->isMultibyte( $str ) ) {
2764 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2766 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2769 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2772 if ( $this->isMultibyte( $str ) ) {
2773 $x = $first ?
'^' : '';
2774 return preg_replace_callback(
2775 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2776 array( $this, 'lcCallback' ),
2780 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2786 * @param string $str
2789 function isMultibyte( $str ) {
2790 return (bool)preg_match( '/[\x80-\xff]/', $str );
2794 * @param string $str
2795 * @return mixed|string
2797 function ucwords( $str ) {
2798 if ( $this->isMultibyte( $str ) ) {
2799 $str = $this->lc( $str );
2801 // regexp to find first letter in each word (i.e. after each space)
2802 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2804 // function to use to capitalize a single char
2805 if ( function_exists( 'mb_strtoupper' ) ) {
2806 return preg_replace_callback(
2808 array( $this, 'ucwordsCallbackMB' ),
2812 return preg_replace_callback(
2814 array( $this, 'ucwordsCallbackWiki' ),
2819 return ucwords( strtolower( $str ) );
2824 * capitalize words at word breaks
2826 * @param string $str
2829 function ucwordbreaks( $str ) {
2830 if ( $this->isMultibyte( $str ) ) {
2831 $str = $this->lc( $str );
2833 // since \b doesn't work for UTF-8, we explicitely define word break chars
2834 $breaks = "[ \-\(\)\}\{\.,\?!]";
2836 // find first letter after word break
2837 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2838 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2840 if ( function_exists( 'mb_strtoupper' ) ) {
2841 return preg_replace_callback(
2843 array( $this, 'ucwordbreaksCallbackMB' ),
2847 return preg_replace_callback(
2849 array( $this, 'ucwordsCallbackWiki' ),
2854 return preg_replace_callback(
2855 '/\b([\w\x80-\xff]+)\b/',
2856 array( $this, 'ucwordbreaksCallbackAscii' ),
2863 * Return a case-folded representation of $s
2865 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2866 * and $s2 are the same except for the case of their characters. It is not
2867 * necessary for the value returned to make sense when displayed.
2869 * Do *not* perform any other normalisation in this function. If a caller
2870 * uses this function when it should be using a more general normalisation
2871 * function, then fix the caller.
2877 function caseFold( $s ) {
2878 return $this->uc( $s );
2885 function checkTitleEncoding( $s ) {
2886 if ( is_array( $s ) ) {
2887 throw new MWException( 'Given array to checkTitleEncoding.' );
2889 if ( StringUtils
::isUtf8( $s ) ) {
2893 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2899 function fallback8bitEncoding() {
2900 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2904 * Most writing systems use whitespace to break up words.
2905 * Some languages such as Chinese don't conventionally do this,
2906 * which requires special handling when breaking up words for
2911 function hasWordBreaks() {
2916 * Some languages such as Chinese require word segmentation,
2917 * Specify such segmentation when overridden in derived class.
2919 * @param string $string
2922 function segmentByWord( $string ) {
2927 * Some languages have special punctuation need to be normalized.
2928 * Make such changes here.
2930 * @param string $string
2933 function normalizeForSearch( $string ) {
2934 return self
::convertDoubleWidth( $string );
2938 * convert double-width roman characters to single-width.
2939 * range: ff00-ff5f ~= 0020-007f
2941 * @param string $string
2945 protected static function convertDoubleWidth( $string ) {
2946 static $full = null;
2947 static $half = null;
2949 if ( $full === null ) {
2950 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2951 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2952 $full = str_split( $fullWidth, 3 );
2953 $half = str_split( $halfWidth );
2956 $string = str_replace( $full, $half, $string );
2961 * @param string $string
2962 * @param string $pattern
2965 protected static function insertSpace( $string, $pattern ) {
2966 $string = preg_replace( $pattern, " $1 ", $string );
2967 $string = preg_replace( '/ +/', ' ', $string );
2972 * @param array $termsArray
2975 function convertForSearchResult( $termsArray ) {
2976 # some languages, e.g. Chinese, need to do a conversion
2977 # in order for search results to be displayed correctly
2982 * Get the first character of a string.
2987 function firstChar( $s ) {
2990 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2991 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2996 if ( isset( $matches[1] ) ) {
2997 if ( strlen( $matches[1] ) != 3 ) {
3001 // Break down Hangul syllables to grab the first jamo
3002 $code = UtfNormal\Utils
::utf8ToCodepoint( $matches[1] );
3003 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
3005 } elseif ( $code < 0xb098 ) {
3006 return "\xe3\x84\xb1";
3007 } elseif ( $code < 0xb2e4 ) {
3008 return "\xe3\x84\xb4";
3009 } elseif ( $code < 0xb77c ) {
3010 return "\xe3\x84\xb7";
3011 } elseif ( $code < 0xb9c8 ) {
3012 return "\xe3\x84\xb9";
3013 } elseif ( $code < 0xbc14 ) {
3014 return "\xe3\x85\x81";
3015 } elseif ( $code < 0xc0ac ) {
3016 return "\xe3\x85\x82";
3017 } elseif ( $code < 0xc544 ) {
3018 return "\xe3\x85\x85";
3019 } elseif ( $code < 0xc790 ) {
3020 return "\xe3\x85\x87";
3021 } elseif ( $code < 0xcc28 ) {
3022 return "\xe3\x85\x88";
3023 } elseif ( $code < 0xce74 ) {
3024 return "\xe3\x85\x8a";
3025 } elseif ( $code < 0xd0c0 ) {
3026 return "\xe3\x85\x8b";
3027 } elseif ( $code < 0xd30c ) {
3028 return "\xe3\x85\x8c";
3029 } elseif ( $code < 0xd558 ) {
3030 return "\xe3\x85\x8d";
3032 return "\xe3\x85\x8e";
3039 function initEncoding() {
3040 # Some languages may have an alternate char encoding option
3041 # (Esperanto X-coding, Japanese furigana conversion, etc)
3042 # If this language is used as the primary content language,
3043 # an override to the defaults can be set here on startup.
3050 function recodeForEdit( $s ) {
3051 # For some languages we'll want to explicitly specify
3052 # which characters make it into the edit box raw
3053 # or are converted in some way or another.
3054 global $wgEditEncoding;
3055 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
3058 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
3066 function recodeInput( $s ) {
3067 # Take the previous into account.
3068 global $wgEditEncoding;
3069 if ( $wgEditEncoding != '' ) {
3070 $enc = $wgEditEncoding;
3074 if ( $enc == 'UTF-8' ) {
3077 return $this->iconv( $enc, 'UTF-8', $s );
3082 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
3083 * also cleans up certain backwards-compatible sequences, converting them
3084 * to the modern Unicode equivalent.
3086 * This is language-specific for performance reasons only.
3092 function normalize( $s ) {
3093 global $wgAllUnicodeFixes;
3094 $s = UtfNormal\Validator
::cleanUp( $s );
3095 if ( $wgAllUnicodeFixes ) {
3096 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
3097 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
3104 * Transform a string using serialized data stored in the given file (which
3105 * must be in the serialized subdirectory of $IP). The file contains pairs
3106 * mapping source characters to destination characters.
3108 * The data is cached in process memory. This will go faster if you have the
3109 * FastStringSearch extension.
3111 * @param string $file
3112 * @param string $string
3114 * @throws MWException
3117 function transformUsingPairFile( $file, $string ) {
3118 if ( !isset( $this->transformData
[$file] ) ) {
3119 $data = wfGetPrecompiledData( $file );
3120 if ( $data === false ) {
3121 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
3123 $this->transformData
[$file] = new ReplacementArray( $data );
3125 return $this->transformData
[$file]->replace( $string );
3129 * For right-to-left language support
3134 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
3138 * Return the correct HTML 'dir' attribute value for this language.
3142 return $this->isRTL() ?
'rtl' : 'ltr';
3146 * Return 'left' or 'right' as appropriate alignment for line-start
3147 * for this language's text direction.
3149 * Should be equivalent to CSS3 'start' text-align value....
3153 function alignStart() {
3154 return $this->isRTL() ?
'right' : 'left';
3158 * Return 'right' or 'left' as appropriate alignment for line-end
3159 * for this language's text direction.
3161 * Should be equivalent to CSS3 'end' text-align value....
3165 function alignEnd() {
3166 return $this->isRTL() ?
'left' : 'right';
3170 * A hidden direction mark (LRM or RLM), depending on the language direction.
3171 * Unlike getDirMark(), this function returns the character as an HTML entity.
3172 * This function should be used when the output is guaranteed to be HTML,
3173 * because it makes the output HTML source code more readable. When
3174 * the output is plain text or can be escaped, getDirMark() should be used.
3176 * @param bool $opposite Get the direction mark opposite to your language
3180 function getDirMarkEntity( $opposite = false ) {
3182 return $this->isRTL() ?
'‎' : '‏';
3184 return $this->isRTL() ?
'‏' : '‎';
3188 * A hidden direction mark (LRM or RLM), depending on the language direction.
3189 * This function produces them as invisible Unicode characters and
3190 * the output may be hard to read and debug, so it should only be used
3191 * when the output is plain text or can be escaped. When the output is
3192 * HTML, use getDirMarkEntity() instead.
3194 * @param bool $opposite Get the direction mark opposite to your language
3197 function getDirMark( $opposite = false ) {
3198 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3199 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3201 return $this->isRTL() ?
$lrm : $rlm;
3203 return $this->isRTL() ?
$rlm : $lrm;
3209 function capitalizeAllNouns() {
3210 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3214 * An arrow, depending on the language direction.
3216 * @param string $direction The direction of the arrow: forwards (default),
3217 * backwards, left, right, up, down.
3220 function getArrow( $direction = 'forwards' ) {
3221 switch ( $direction ) {
3223 return $this->isRTL() ?
'←' : '→';
3225 return $this->isRTL() ?
'→' : '←';
3238 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3242 function linkPrefixExtension() {
3243 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3247 * Get all magic words from cache.
3250 function getMagicWords() {
3251 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3255 * Run the LanguageGetMagic hook once.
3257 protected function doMagicHook() {
3258 if ( $this->mMagicHookDone
) {
3261 $this->mMagicHookDone
= true;
3262 Hooks
::run( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3266 * Fill a MagicWord object with data from here
3268 * @param MagicWord $mw
3270 function getMagic( $mw ) {
3271 // Saves a function call
3272 if ( !$this->mMagicHookDone
) {
3273 $this->doMagicHook();
3276 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3277 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3279 $rawEntry = self
::$dataCache->getSubitem(
3280 $this->mCode
, 'magicWords', $mw->mId
);
3283 if ( !is_array( $rawEntry ) ) {
3284 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3286 $mw->mCaseSensitive
= $rawEntry[0];
3287 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3292 * Add magic words to the extension array
3294 * @param array $newWords
3296 function addMagicWordsByLang( $newWords ) {
3297 $fallbackChain = $this->getFallbackLanguages();
3298 $fallbackChain = array_reverse( $fallbackChain );
3299 foreach ( $fallbackChain as $code ) {
3300 if ( isset( $newWords[$code] ) ) {
3301 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3307 * Get special page names, as an associative array
3308 * canonical name => array of valid names, including aliases
3311 function getSpecialPageAliases() {
3312 // Cache aliases because it may be slow to load them
3313 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3315 $this->mExtendedSpecialPageAliases
=
3316 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3317 Hooks
::run( 'LanguageGetSpecialPageAliases',
3318 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3321 return $this->mExtendedSpecialPageAliases
;
3325 * Italic is unsuitable for some languages
3327 * @param string $text The text to be emphasized.
3330 function emphasize( $text ) {
3331 return "<em>$text</em>";
3335 * Normally we output all numbers in plain en_US style, that is
3336 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3337 * point twohundredthirtyfive. However this is not suitable for all
3338 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3339 * Icelandic just want to use commas instead of dots, and dots instead
3340 * of commas like "293.291,235".
3342 * An example of this function being called:
3344 * wfMessage( 'message' )->numParams( $num )->text()
3347 * See $separatorTransformTable on MessageIs.php for
3348 * the , => . and . => , implementation.
3350 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3351 * @param int|float $number The string to be formatted, should be an integer
3352 * or a floating point number.
3353 * @param bool $nocommafy Set to true for special numbers like dates
3356 public function formatNum( $number, $nocommafy = false ) {
3357 global $wgTranslateNumerals;
3358 if ( !$nocommafy ) {
3359 $number = $this->commafy( $number );
3360 $s = $this->separatorTransformTable();
3362 $number = strtr( $number, $s );
3366 if ( $wgTranslateNumerals ) {
3367 $s = $this->digitTransformTable();
3369 $number = strtr( $number, $s );
3377 * Front-end for non-commafied formatNum
3379 * @param int|float $number The string to be formatted, should be an integer
3380 * or a floating point number.
3384 public function formatNumNoSeparators( $number ) {
3385 return $this->formatNum( $number, true );
3389 * @param string $number
3392 public function parseFormattedNumber( $number ) {
3393 $s = $this->digitTransformTable();
3395 // eliminate empty array values such as ''. (bug 64347)
3396 $s = array_filter( $s );
3397 $number = strtr( $number, array_flip( $s ) );
3400 $s = $this->separatorTransformTable();
3402 // eliminate empty array values such as ''. (bug 64347)
3403 $s = array_filter( $s );
3404 $number = strtr( $number, array_flip( $s ) );
3407 $number = strtr( $number, array( ',' => '' ) );
3412 * Adds commas to a given number
3414 * @param mixed $number
3417 function commafy( $number ) {
3418 $digitGroupingPattern = $this->digitGroupingPattern();
3419 if ( $number === null ) {
3423 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3424 // default grouping is at thousands, use the same for ###,###,### pattern too.
3425 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3427 // Ref: http://cldr.unicode.org/translation/number-patterns
3429 if ( intval( $number ) < 0 ) {
3430 // For negative numbers apply the algorithm like positive number and add sign.
3432 $number = substr( $number, 1 );
3434 $integerPart = array();
3435 $decimalPart = array();
3436 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3437 preg_match( "/\d+/", $number, $integerPart );
3438 preg_match( "/\.\d*/", $number, $decimalPart );
3439 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3440 if ( $groupedNumber === $number ) {
3441 // the string does not have any number part. Eg: .12345
3442 return $sign . $groupedNumber;
3444 $start = $end = ( $integerPart ) ?
strlen( $integerPart[0] ) : 0;
3445 while ( $start > 0 ) {
3446 $match = $matches[0][$numMatches - 1];
3447 $matchLen = strlen( $match );
3448 $start = $end - $matchLen;
3452 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3454 if ( $numMatches > 1 ) {
3455 // use the last pattern for the rest of the number
3459 $groupedNumber = "," . $groupedNumber;
3462 return $sign . $groupedNumber;
3469 function digitGroupingPattern() {
3470 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3476 function digitTransformTable() {
3477 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3483 function separatorTransformTable() {
3484 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3488 * Take a list of strings and build a locale-friendly comma-separated
3489 * list, using the local comma-separator message.
3490 * The last two strings are chained with an "and".
3491 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3493 * @param string[] $l
3496 function listToText( array $l ) {
3497 $m = count( $l ) - 1;
3502 $and = $this->msg( 'and' )->escaped();
3503 $space = $this->msg( 'word-separator' )->escaped();
3505 $comma = $this->msg( 'comma-separator' )->escaped();
3509 for ( $i = $m - 1; $i >= 0; $i-- ) {
3510 if ( $i == $m - 1 ) {
3511 $s = $l[$i] . $and . $space . $s;
3513 $s = $l[$i] . $comma . $s;
3520 * Take a list of strings and build a locale-friendly comma-separated
3521 * list, using the local comma-separator message.
3522 * @param string[] $list Array of strings to put in a comma list
3525 function commaList( array $list ) {
3527 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3533 * Take a list of strings and build a locale-friendly semicolon-separated
3534 * list, using the local semicolon-separator message.
3535 * @param string[] $list Array of strings to put in a semicolon list
3538 function semicolonList( array $list ) {
3540 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3546 * Same as commaList, but separate it with the pipe instead.
3547 * @param string[] $list Array of strings to put in a pipe list
3550 function pipeList( array $list ) {
3552 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3558 * Truncate a string to a specified length in bytes, appending an optional
3559 * string (e.g. for ellipses)
3561 * The database offers limited byte lengths for some columns in the database;
3562 * multi-byte character sets mean we need to ensure that only whole characters
3563 * are included, otherwise broken characters can be passed to the user
3565 * If $length is negative, the string will be truncated from the beginning
3567 * @param string $string String to truncate
3568 * @param int $length Maximum length (including ellipses)
3569 * @param string $ellipsis String to append to the truncated text
3570 * @param bool $adjustLength Subtract length of ellipsis from $length.
3571 * $adjustLength was introduced in 1.18, before that behaved as if false.
3574 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3575 # Use the localized ellipsis character
3576 if ( $ellipsis == '...' ) {
3577 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3579 # Check if there is no need to truncate
3580 if ( $length == 0 ) {
3581 return $ellipsis; // convention
3582 } elseif ( strlen( $string ) <= abs( $length ) ) {
3583 return $string; // no need to truncate
3585 $stringOriginal = $string;
3586 # If ellipsis length is >= $length then we can't apply $adjustLength
3587 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3588 $string = $ellipsis; // this can be slightly unexpected
3589 # Otherwise, truncate and add ellipsis...
3591 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3592 if ( $length > 0 ) {
3593 $length -= $eLength;
3594 $string = substr( $string, 0, $length ); // xyz...
3595 $string = $this->removeBadCharLast( $string );
3596 $string = rtrim( $string );
3597 $string = $string . $ellipsis;
3599 $length +
= $eLength;
3600 $string = substr( $string, $length ); // ...xyz
3601 $string = $this->removeBadCharFirst( $string );
3602 $string = ltrim( $string );
3603 $string = $ellipsis . $string;
3606 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3607 # This check is *not* redundant if $adjustLength, due to the single case where
3608 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3609 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3612 return $stringOriginal;
3617 * Remove bytes that represent an incomplete Unicode character
3618 * at the end of string (e.g. bytes of the char are missing)
3620 * @param string $string
3623 protected function removeBadCharLast( $string ) {
3624 if ( $string != '' ) {
3625 $char = ord( $string[strlen( $string ) - 1] );
3627 if ( $char >= 0xc0 ) {
3628 # We got the first byte only of a multibyte char; remove it.
3629 $string = substr( $string, 0, -1 );
3630 } elseif ( $char >= 0x80 &&
3631 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3632 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3634 # We chopped in the middle of a character; remove it
3642 * Remove bytes that represent an incomplete Unicode character
3643 * at the start of string (e.g. bytes of the char are missing)
3645 * @param string $string
3648 protected function removeBadCharFirst( $string ) {
3649 if ( $string != '' ) {
3650 $char = ord( $string[0] );
3651 if ( $char >= 0x80 && $char < 0xc0 ) {
3652 # We chopped in the middle of a character; remove the whole thing
3653 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3660 * Truncate a string of valid HTML to a specified length in bytes,
3661 * appending an optional string (e.g. for ellipses), and return valid HTML
3663 * This is only intended for styled/linked text, such as HTML with
3664 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3665 * Also, this will not detect things like "display:none" CSS.
3667 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3669 * @param string $text HTML string to truncate
3670 * @param int $length (zero/positive) Maximum length (including ellipses)
3671 * @param string $ellipsis String to append to the truncated text
3674 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3675 # Use the localized ellipsis character
3676 if ( $ellipsis == '...' ) {
3677 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3679 # Check if there is clearly no need to truncate
3680 if ( $length <= 0 ) {
3681 return $ellipsis; // no text shown, nothing to format (convention)
3682 } elseif ( strlen( $text ) <= $length ) {
3683 return $text; // string short enough even *with* HTML (short-circuit)
3686 $dispLen = 0; // innerHTML legth so far
3687 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3688 $tagType = 0; // 0-open, 1-close
3689 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3690 $entityState = 0; // 0-not entity, 1-entity
3691 $tag = $ret = ''; // accumulated tag name, accumulated result string
3692 $openTags = array(); // open tag stack
3693 $maybeState = null; // possible truncation state
3695 $textLen = strlen( $text );
3696 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3697 for ( $pos = 0; true; ++
$pos ) {
3698 # Consider truncation once the display length has reached the maximim.
3699 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3700 # Check that we're not in the middle of a bracket/entity...
3701 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3702 if ( !$testingEllipsis ) {
3703 $testingEllipsis = true;
3704 # Save where we are; we will truncate here unless there turn out to
3705 # be so few remaining characters that truncation is not necessary.
3706 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3707 $maybeState = array( $ret, $openTags ); // save state
3709 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3710 # String in fact does need truncation, the truncation point was OK.
3711 list( $ret, $openTags ) = $maybeState; // reload state
3712 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3713 $ret .= $ellipsis; // add ellipsis
3717 if ( $pos >= $textLen ) {
3718 break; // extra iteration just for above checks
3721 # Read the next char...
3723 $lastCh = $pos ?
$text[$pos - 1] : '';
3724 $ret .= $ch; // add to result string
3726 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3727 $entityState = 0; // for bad HTML
3728 $bracketState = 1; // tag started (checking for backslash)
3729 } elseif ( $ch == '>' ) {
3730 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3731 $entityState = 0; // for bad HTML
3732 $bracketState = 0; // out of brackets
3733 } elseif ( $bracketState == 1 ) {
3735 $tagType = 1; // close tag (e.g. "</span>")
3737 $tagType = 0; // open tag (e.g. "<span>")
3740 $bracketState = 2; // building tag name
3741 } elseif ( $bracketState == 2 ) {
3745 // Name found (e.g. "<a href=..."), add on tag attributes...
3746 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3748 } elseif ( $bracketState == 0 ) {
3749 if ( $entityState ) {
3752 $dispLen++
; // entity is one displayed char
3755 if ( $neLength == 0 && !$maybeState ) {
3756 // Save state without $ch. We want to *hit* the first
3757 // display char (to get tags) but not *use* it if truncating.
3758 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3761 $entityState = 1; // entity found, (e.g. " ")
3763 $dispLen++
; // this char is displayed
3764 // Add the next $max display text chars after this in one swoop...
3765 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3766 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3767 $dispLen +
= $skipped;
3773 // Close the last tag if left unclosed by bad HTML
3774 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3775 while ( count( $openTags ) > 0 ) {
3776 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3782 * truncateHtml() helper function
3783 * like strcspn() but adds the skipped chars to $ret
3785 * @param string $ret
3786 * @param string $text
3787 * @param string $search
3789 * @param null|int $len
3792 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3793 if ( $len === null ) {
3794 $len = -1; // -1 means "no limit" for strcspn
3795 } elseif ( $len < 0 ) {
3799 if ( $start < strlen( $text ) ) {
3800 $skipCount = strcspn( $text, $search, $start, $len );
3801 $ret .= substr( $text, $start, $skipCount );
3807 * truncateHtml() helper function
3808 * (a) push or pop $tag from $openTags as needed
3809 * (b) clear $tag value
3810 * @param string &$tag Current HTML tag name we are looking at
3811 * @param int $tagType (0-open tag, 1-close tag)
3812 * @param string $lastCh Character before the '>' that ended this tag
3813 * @param array &$openTags Open tag stack (not accounting for $tag)
3815 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3816 $tag = ltrim( $tag );
3818 if ( $tagType == 0 && $lastCh != '/' ) {
3819 $openTags[] = $tag; // tag opened (didn't close itself)
3820 } elseif ( $tagType == 1 ) {
3821 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3822 array_pop( $openTags ); // tag closed
3830 * Grammatical transformations, needed for inflected languages
3831 * Invoked by putting {{grammar:case|word}} in a message
3833 * @param string $word
3834 * @param string $case
3837 function convertGrammar( $word, $case ) {
3838 global $wgGrammarForms;
3839 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3840 return $wgGrammarForms[$this->getCode()][$case][$word];
3846 * Get the grammar forms for the content language
3847 * @return array Array of grammar forms
3850 function getGrammarForms() {
3851 global $wgGrammarForms;
3852 if ( isset( $wgGrammarForms[$this->getCode()] )
3853 && is_array( $wgGrammarForms[$this->getCode()] )
3855 return $wgGrammarForms[$this->getCode()];
3861 * Provides an alternative text depending on specified gender.
3862 * Usage {{gender:username|masculine|feminine|unknown}}.
3863 * username is optional, in which case the gender of current user is used,
3864 * but only in (some) interface messages; otherwise default gender is used.
3866 * If no forms are given, an empty string is returned. If only one form is
3867 * given, it will be returned unconditionally. These details are implied by
3868 * the caller and cannot be overridden in subclasses.
3870 * If three forms are given, the default is to use the third (unknown) form.
3871 * If fewer than three forms are given, the default is to use the first (masculine) form.
3872 * These details can be overridden in subclasses.
3874 * @param string $gender
3875 * @param array $forms
3879 function gender( $gender, $forms ) {
3880 if ( !count( $forms ) ) {
3883 $forms = $this->preConvertPlural( $forms, 2 );
3884 if ( $gender === 'male' ) {
3887 if ( $gender === 'female' ) {
3890 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3894 * Plural form transformations, needed for some languages.
3895 * For example, there are 3 form of plural in Russian and Polish,
3896 * depending on "count mod 10". See [[w:Plural]]
3897 * For English it is pretty simple.
3899 * Invoked by putting {{plural:count|wordform1|wordform2}}
3900 * or {{plural:count|wordform1|wordform2|wordform3}}
3902 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3904 * @param int $count Non-localized number
3905 * @param array $forms Different plural forms
3906 * @return string Correct form of plural for $count in this language
3908 function convertPlural( $count, $forms ) {
3909 // Handle explicit n=pluralform cases
3910 $forms = $this->handleExplicitPluralForms( $count, $forms );
3911 if ( is_string( $forms ) ) {
3914 if ( !count( $forms ) ) {
3918 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3919 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3920 return $forms[$pluralForm];
3924 * Handles explicit plural forms for Language::convertPlural()
3926 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3927 * If an explicitly defined plural form matches the $count, then
3928 * string value returned, otherwise array returned for further consideration
3929 * by CLDR rules or overridden convertPlural().
3933 * @param int $count Non-localized number
3934 * @param array $forms Different plural forms
3936 * @return array|string
3938 protected function handleExplicitPluralForms( $count, array $forms ) {
3939 foreach ( $forms as $index => $form ) {
3940 if ( preg_match( '/\d+=/i', $form ) ) {
3941 $pos = strpos( $form, '=' );
3942 if ( substr( $form, 0, $pos ) === (string)$count ) {
3943 return substr( $form, $pos +
1 );
3945 unset( $forms[$index] );
3948 return array_values( $forms );
3952 * Checks that convertPlural was given an array and pads it to requested
3953 * amount of forms by copying the last one.
3955 * @param array $forms Array of forms given to convertPlural
3956 * @param int $count How many forms should there be at least
3957 * @return array Padded array of forms or an exception if not an array
3959 protected function preConvertPlural( /* Array */ $forms, $count ) {
3960 while ( count( $forms ) < $count ) {
3961 $forms[] = $forms[count( $forms ) - 1];
3967 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3968 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3969 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3970 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3973 * @param string $str The validated block duration in English
3974 * @return string Somehow translated block duration
3975 * @see LanguageFi.php for example implementation
3977 function translateBlockExpiry( $str ) {
3978 $duration = SpecialBlock
::getSuggestedDurations( $this );
3979 foreach ( $duration as $show => $value ) {
3980 if ( strcmp( $str, $value ) == 0 ) {
3981 return htmlspecialchars( trim( $show ) );
3985 if ( wfIsInfinity( $str ) ) {
3986 foreach ( $duration as $show => $value ) {
3987 if ( wfIsInfinity( $value ) ) {
3988 return htmlspecialchars( trim( $show ) );
3993 // If all else fails, return a standard duration or timestamp description.
3994 $time = strtotime( $str, 0 );
3995 if ( $time === false ) { // Unknown format. Return it as-is in case.
3997 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3998 // $time is relative to 0 so it's a duration length.
3999 return $this->formatDuration( $time );
4000 } else { // It's an absolute timestamp.
4001 if ( $time === 0 ) {
4002 // wfTimestamp() handles 0 as current time instead of epoch.
4003 return $this->timeanddate( '19700101000000' );
4005 return $this->timeanddate( $time );
4011 * languages like Chinese need to be segmented in order for the diff
4014 * @param string $text
4017 public function segmentForDiff( $text ) {
4022 * and unsegment to show the result
4024 * @param string $text
4027 public function unsegmentForDiff( $text ) {
4032 * Return the LanguageConverter used in the Language
4035 * @return LanguageConverter
4037 public function getConverter() {
4038 return $this->mConverter
;
4042 * convert text to all supported variants
4044 * @param string $text
4047 public function autoConvertToAllVariants( $text ) {
4048 return $this->mConverter
->autoConvertToAllVariants( $text );
4052 * convert text to different variants of a language.
4054 * @param string $text
4057 public function convert( $text ) {
4058 return $this->mConverter
->convert( $text );
4062 * Convert a Title object to a string in the preferred variant
4064 * @param Title $title
4067 public function convertTitle( $title ) {
4068 return $this->mConverter
->convertTitle( $title );
4072 * Convert a namespace index to a string in the preferred variant
4077 public function convertNamespace( $ns ) {
4078 return $this->mConverter
->convertNamespace( $ns );
4082 * Check if this is a language with variants
4086 public function hasVariants() {
4087 return count( $this->getVariants() ) > 1;
4091 * Check if the language has the specific variant
4094 * @param string $variant
4097 public function hasVariant( $variant ) {
4098 return (bool)$this->mConverter
->validateVariant( $variant );
4102 * Put custom tags (e.g. -{ }-) around math to prevent conversion
4104 * @param string $text
4106 * @deprecated since 1.22 is no longer used
4108 public function armourMath( $text ) {
4109 return $this->mConverter
->armourMath( $text );
4113 * Perform output conversion on a string, and encode for safe HTML output.
4114 * @param string $text Text to be converted
4115 * @param bool $isTitle Whether this conversion is for the article title
4117 * @todo this should get integrated somewhere sane
4119 public function convertHtml( $text, $isTitle = false ) {
4120 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4124 * @param string $key
4127 public function convertCategoryKey( $key ) {
4128 return $this->mConverter
->convertCategoryKey( $key );
4132 * Get the list of variants supported by this language
4133 * see sample implementation in LanguageZh.php
4135 * @return array An array of language codes
4137 public function getVariants() {
4138 return $this->mConverter
->getVariants();
4144 public function getPreferredVariant() {
4145 return $this->mConverter
->getPreferredVariant();
4151 public function getDefaultVariant() {
4152 return $this->mConverter
->getDefaultVariant();
4158 public function getURLVariant() {
4159 return $this->mConverter
->getURLVariant();
4163 * If a language supports multiple variants, it is
4164 * possible that non-existing link in one variant
4165 * actually exists in another variant. this function
4166 * tries to find it. See e.g. LanguageZh.php
4167 * The input parameters may be modified upon return
4169 * @param string &$link The name of the link
4170 * @param Title &$nt The title object of the link
4171 * @param bool $ignoreOtherCond To disable other conditions when
4172 * we need to transclude a template or update a category's link
4174 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4175 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4179 * returns language specific options used by User::getPageRenderHash()
4180 * for example, the preferred language variant
4184 function getExtraHashOptions() {
4185 return $this->mConverter
->getExtraHashOptions();
4189 * For languages that support multiple variants, the title of an
4190 * article may be displayed differently in different variants. this
4191 * function returns the apporiate title defined in the body of the article.
4195 public function getParsedTitle() {
4196 return $this->mConverter
->getParsedTitle();
4200 * Prepare external link text for conversion. When the text is
4201 * a URL, it shouldn't be converted, and it'll be wrapped in
4202 * the "raw" tag (-{R| }-) to prevent conversion.
4204 * This function is called "markNoConversion" for historical
4207 * @param string $text Text to be used for external link
4208 * @param bool $noParse Wrap it without confirming it's a real URL first
4209 * @return string The tagged text
4211 public function markNoConversion( $text, $noParse = false ) {
4212 // Excluding protocal-relative URLs may avoid many false positives.
4213 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4214 return $this->mConverter
->markNoConversion( $text );
4221 * A regular expression to match legal word-trailing characters
4222 * which should be merged onto a link of the form [[foo]]bar.
4226 public function linkTrail() {
4227 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4231 * A regular expression character set to match legal word-prefixing
4232 * characters which should be merged onto a link of the form foo[[bar]].
4236 public function linkPrefixCharset() {
4237 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4241 * @deprecated since 1.24, will be removed in 1.25
4244 function getLangObj() {
4245 wfDeprecated( __METHOD__
, '1.24' );
4250 * Get the "parent" language which has a converter to convert a "compatible" language
4251 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4253 * @return Language|null
4256 public function getParentLanguage() {
4257 if ( $this->mParentLanguage
!== false ) {
4258 return $this->mParentLanguage
;
4261 $pieces = explode( '-', $this->getCode() );
4263 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4264 $this->mParentLanguage
= null;
4267 $lang = Language
::factory( $code );
4268 if ( !$lang->hasVariant( $this->getCode() ) ) {
4269 $this->mParentLanguage
= null;
4273 $this->mParentLanguage
= $lang;
4278 * Get the RFC 3066 code for this language object
4280 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4281 * htmlspecialchars() or similar
4285 public function getCode() {
4286 return $this->mCode
;
4290 * Get the code in Bcp47 format which we can use
4291 * inside of html lang="" tags.
4293 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4294 * htmlspecialchars() or similar.
4299 public function getHtmlCode() {
4300 if ( is_null( $this->mHtmlCode
) ) {
4301 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4303 return $this->mHtmlCode
;
4307 * @param string $code
4309 public function setCode( $code ) {
4310 $this->mCode
= $code;
4311 // Ensure we don't leave incorrect cached data lying around
4312 $this->mHtmlCode
= null;
4313 $this->mParentLanguage
= false;
4317 * Get the name of a file for a certain language code
4318 * @param string $prefix Prepend this to the filename
4319 * @param string $code Language code
4320 * @param string $suffix Append this to the filename
4321 * @throws MWException
4322 * @return string $prefix . $mangledCode . $suffix
4324 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4325 if ( !self
::isValidBuiltInCode( $code ) ) {
4326 throw new MWException( "Invalid language code \"$code\"" );
4329 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4333 * Get the language code from a file name. Inverse of getFileName()
4334 * @param string $filename $prefix . $languageCode . $suffix
4335 * @param string $prefix Prefix before the language code
4336 * @param string $suffix Suffix after the language code
4337 * @return string Language code, or false if $prefix or $suffix isn't found
4339 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4341 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4342 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4343 if ( !count( $m ) ) {
4346 return str_replace( '_', '-', strtolower( $m[1] ) );
4350 * @param string $code
4353 public static function getMessagesFileName( $code ) {
4355 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4356 Hooks
::run( 'Language::getMessagesFileName', array( $code, &$file ) );
4361 * @param string $code
4365 public static function getJsonMessagesFileName( $code ) {
4368 if ( !self
::isValidBuiltInCode( $code ) ) {
4369 throw new MWException( "Invalid language code \"$code\"" );
4372 return "$IP/languages/i18n/$code.json";
4376 * @param string $code
4379 public static function getClassFileName( $code ) {
4381 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4385 * Get the first fallback for a given language.
4387 * @param string $code
4389 * @return bool|string
4391 public static function getFallbackFor( $code ) {
4392 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4395 $fallbacks = self
::getFallbacksFor( $code );
4396 return $fallbacks[0];
4401 * Get the ordered list of fallback languages.
4404 * @param string $code Language code
4405 * @return array Non-empty array, ending in "en"
4407 public static function getFallbacksFor( $code ) {
4408 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4411 // For unknown languages, fallbackSequence returns an empty array,
4412 // hardcode fallback to 'en' in that case.
4413 return self
::getLocalisationCache()->getItem( $code, 'fallbackSequence' ) ?
: array( 'en' );
4417 * Get the ordered list of fallback languages, ending with the fallback
4418 * language chain for the site language.
4421 * @param string $code Language code
4422 * @return array Array( fallbacks, site fallbacks )
4424 public static function getFallbacksIncludingSiteLanguage( $code ) {
4425 global $wgLanguageCode;
4427 // Usually, we will only store a tiny number of fallback chains, so we
4428 // keep them in static memory.
4429 $cacheKey = "{$code}-{$wgLanguageCode}";
4431 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4432 $fallbacks = self
::getFallbacksFor( $code );
4434 // Append the site's fallback chain, including the site language itself
4435 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4436 array_unshift( $siteFallbacks, $wgLanguageCode );
4438 // Eliminate any languages already included in the chain
4439 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4441 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4443 return self
::$fallbackLanguageCache[$cacheKey];
4447 * Get all messages for a given language
4448 * WARNING: this may take a long time. If you just need all message *keys*
4449 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4451 * @param string $code
4455 public static function getMessagesFor( $code ) {
4456 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4460 * Get a message for a given language
4462 * @param string $key
4463 * @param string $code
4467 public static function getMessageFor( $key, $code ) {
4468 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4472 * Get all message keys for a given language. This is a faster alternative to
4473 * array_keys( Language::getMessagesFor( $code ) )
4476 * @param string $code Language code
4477 * @return array Array of message keys (strings)
4479 public static function getMessageKeysFor( $code ) {
4480 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4484 * @param string $talk
4487 function fixVariableInNamespace( $talk ) {
4488 if ( strpos( $talk, '$1' ) === false ) {
4492 global $wgMetaNamespace;
4493 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4495 # Allow grammar transformations
4496 # Allowing full message-style parsing would make simple requests
4497 # such as action=raw much more expensive than they need to be.
4498 # This will hopefully cover most cases.
4499 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4500 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4501 return str_replace( ' ', '_', $talk );
4508 function replaceGrammarInNamespace( $m ) {
4509 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4513 * @throws MWException
4516 static function getCaseMaps() {
4517 static $wikiUpperChars, $wikiLowerChars;
4518 if ( isset( $wikiUpperChars ) ) {
4519 return array( $wikiUpperChars, $wikiLowerChars );
4522 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4523 if ( $arr === false ) {
4524 throw new MWException(
4525 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4527 $wikiUpperChars = $arr['wikiUpperChars'];
4528 $wikiLowerChars = $arr['wikiLowerChars'];
4529 return array( $wikiUpperChars, $wikiLowerChars );
4533 * Decode an expiry (block, protection, etc) which has come from the DB
4535 * @param string $expiry Database expiry String
4536 * @param bool|int $format True to process using language functions, or TS_ constant
4537 * to return the expiry in a given timestamp
4538 * @param string $inifinity If $format is not true, use this string for infinite expiry
4542 public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4544 if ( $dbInfinity === null ) {
4545 $dbInfinity = wfGetDB( DB_SLAVE
)->getInfinity();
4548 if ( $expiry == '' ||
$expiry === 'infinity' ||
$expiry == $dbInfinity ) {
4549 return $format === true
4550 ?
$this->getMessageFromDB( 'infiniteblock' )
4553 return $format === true
4554 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4555 : wfTimestamp( $format, $expiry );
4561 * @param int|float $seconds
4562 * @param array $format Optional
4563 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4564 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4565 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4567 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4568 * or 'avoidminutes'.
4571 function formatTimePeriod( $seconds, $format = array() ) {
4572 if ( !is_array( $format ) ) {
4573 $format = array( 'avoid' => $format ); // For backwards compatibility
4575 if ( !isset( $format['avoid'] ) ) {
4576 $format['avoid'] = false;
4578 if ( !isset( $format['noabbrevs'] ) ) {
4579 $format['noabbrevs'] = false;
4581 $secondsMsg = wfMessage(
4582 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4583 $minutesMsg = wfMessage(
4584 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4585 $hoursMsg = wfMessage(
4586 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4587 $daysMsg = wfMessage(
4588 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4590 if ( round( $seconds * 10 ) < 100 ) {
4591 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4592 $s = $secondsMsg->params( $s )->text();
4593 } elseif ( round( $seconds ) < 60 ) {
4594 $s = $this->formatNum( round( $seconds ) );
4595 $s = $secondsMsg->params( $s )->text();
4596 } elseif ( round( $seconds ) < 3600 ) {
4597 $minutes = floor( $seconds / 60 );
4598 $secondsPart = round( fmod( $seconds, 60 ) );
4599 if ( $secondsPart == 60 ) {
4603 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4605 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4606 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4607 $hours = floor( $seconds / 3600 );
4608 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4609 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4610 if ( $secondsPart == 60 ) {
4614 if ( $minutes == 60 ) {
4618 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4620 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4621 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4622 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4625 $days = floor( $seconds / 86400 );
4626 if ( $format['avoid'] === 'avoidminutes' ) {
4627 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4628 if ( $hours == 24 ) {
4632 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4634 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4635 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4636 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4637 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4638 if ( $minutes == 60 ) {
4642 if ( $hours == 24 ) {
4646 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4648 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4650 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4652 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4654 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4661 * Format a bitrate for output, using an appropriate
4662 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4663 * the magnitude in question.
4665 * This use base 1000. For base 1024 use formatSize(), for another base
4666 * see formatComputingNumbers().
4671 function formatBitrate( $bps ) {
4672 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4676 * @param int $size Size of the unit
4677 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4678 * @param string $messageKey Message key to be uesd
4681 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4683 return str_replace( '$1', $this->formatNum( $size ),
4684 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4687 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4690 $maxIndex = count( $sizes ) - 1;
4691 while ( $size >= $boundary && $index < $maxIndex ) {
4696 // For small sizes no decimal places necessary
4699 // For MB and bigger two decimal places are smarter
4702 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4704 $size = round( $size, $round );
4705 $text = $this->getMessageFromDB( $msg );
4706 return str_replace( '$1', $this->formatNum( $size ), $text );
4710 * Format a size in bytes for output, using an appropriate
4711 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4713 * This method use base 1024. For base 1000 use formatBitrate(), for
4714 * another base see formatComputingNumbers()
4716 * @param int $size Size to format
4717 * @return string Plain text (not HTML)
4719 function formatSize( $size ) {
4720 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4724 * Make a list item, used by various special pages
4726 * @param string $page Page link
4727 * @param string $details HTML safe text between brackets
4728 * @param bool $oppositedm Add the direction mark opposite to your
4729 * language, to display text properly
4730 * @return HTML escaped string
4732 function specialList( $page, $details, $oppositedm = true ) {
4737 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) . $this->getDirMark();
4741 $this->msg( 'word-separator' )->escaped() .
4742 $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4746 * Generate (prev x| next x) (20|50|100...) type links for paging
4748 * @param Title $title Title object to link
4749 * @param int $offset
4751 * @param array $query Optional URL query parameter string
4752 * @param bool $atend Optional param for specified if this is the last page
4755 public function viewPrevNext( Title
$title, $offset, $limit,
4756 array $query = array(), $atend = false
4758 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4760 # Make 'previous' link
4761 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4762 if ( $offset > 0 ) {
4763 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4764 $query, $prev, 'prevn-title', 'mw-prevlink' );
4766 $plink = htmlspecialchars( $prev );
4770 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4772 $nlink = htmlspecialchars( $next );
4774 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4775 $query, $next, 'nextn-title', 'mw-nextlink' );
4778 # Make links to set number of items per page
4779 $numLinks = array();
4780 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4781 $numLinks[] = $this->numLink( $title, $offset, $num,
4782 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4785 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4786 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4790 * Helper function for viewPrevNext() that generates links
4792 * @param Title $title Title object to link
4793 * @param int $offset
4795 * @param array $query Extra query parameters
4796 * @param string $link Text to use for the link; will be escaped
4797 * @param string $tooltipMsg Name of the message to use as tooltip
4798 * @param string $class Value of the "class" attribute of the link
4799 * @return string HTML fragment
4801 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4804 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4805 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4806 ->numParams( $limit )->text();
4808 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4809 'title' => $tooltip, 'class' => $class ), $link );
4813 * Get the conversion rule title, if any.
4817 public function getConvRuleTitle() {
4818 return $this->mConverter
->getConvRuleTitle();
4822 * Get the compiled plural rules for the language
4824 * @return array Associative array with plural form, and plural rule as key-value pairs
4826 public function getCompiledPluralRules() {
4827 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4828 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4829 if ( !$pluralRules ) {
4830 foreach ( $fallbacks as $fallbackCode ) {
4831 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4832 if ( $pluralRules ) {
4837 return $pluralRules;
4841 * Get the plural rules for the language
4843 * @return array Associative array with plural form number and plural rule as key-value pairs
4845 public function getPluralRules() {
4846 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4847 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4848 if ( !$pluralRules ) {
4849 foreach ( $fallbacks as $fallbackCode ) {
4850 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4851 if ( $pluralRules ) {
4856 return $pluralRules;
4860 * Get the plural rule types for the language
4862 * @return array Associative array with plural form number and plural rule type as key-value pairs
4864 public function getPluralRuleTypes() {
4865 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4866 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4867 if ( !$pluralRuleTypes ) {
4868 foreach ( $fallbacks as $fallbackCode ) {
4869 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4870 if ( $pluralRuleTypes ) {
4875 return $pluralRuleTypes;
4879 * Find the index number of the plural rule appropriate for the given number
4880 * @param int $number
4881 * @return int The index number of the plural rule
4883 public function getPluralRuleIndexNumber( $number ) {
4884 $pluralRules = $this->getCompiledPluralRules();
4885 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4890 * Find the plural rule type appropriate for the given number
4891 * For example, if the language is set to Arabic, getPluralType(5) should
4894 * @param int $number
4895 * @return string The name of the plural rule type, e.g. one, two, few, many
4897 public function getPluralRuleType( $number ) {
4898 $index = $this->getPluralRuleIndexNumber( $number );
4899 $pluralRuleTypes = $this->getPluralRuleTypes();
4900 if ( isset( $pluralRuleTypes[$index] ) ) {
4901 return $pluralRuleTypes[$index];