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 the same thing as
529 * getNamespaces() except with the array values changed to ' '
530 * where it found '_', useful for producing output to be displayed
531 * e.g. in <select> forms.
535 function getFormattedNamespaces() {
536 $ns = $this->getNamespaces();
537 foreach ( $ns as $k => $v ) {
538 $ns[$k] = strtr( $v, '_', ' ' );
544 * Get a namespace value by key
546 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
547 * echo $mw_ns; // prints 'MediaWiki'
550 * @param int $index The array key of the namespace to return
551 * @return string|bool String if the namespace value exists, otherwise false
553 function getNsText( $index ) {
554 $ns = $this->getNamespaces();
556 return isset( $ns[$index] ) ?
$ns[$index] : false;
560 * A convenience function that returns the same thing as
561 * getNsText() except with '_' changed to ' ', useful for
565 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
566 * echo $mw_ns; // prints 'MediaWiki talk'
569 * @param int $index The array key of the namespace to return
570 * @return string Namespace name without underscores (empty string if namespace does not exist)
572 function getFormattedNsText( $index ) {
573 $ns = $this->getNsText( $index );
575 return strtr( $ns, '_', ' ' );
579 * Returns gender-dependent namespace alias if available.
580 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
581 * @param int $index Namespace index
582 * @param string $gender Gender key (male, female... )
586 function getGenderNsText( $index, $gender ) {
587 global $wgExtraGenderNamespaces;
589 $ns = $wgExtraGenderNamespaces +
590 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
592 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
596 * Whether this language uses gender-dependent namespace aliases.
597 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
601 function needsGenderDistinction() {
602 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
603 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
604 // $wgExtraGenderNamespaces overrides everything
606 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
607 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
608 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
611 // Check what is in i18n files
612 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
613 return count( $aliases ) > 0;
618 * Get a namespace key by value, case insensitive.
619 * Only matches namespace names for the current language, not the
620 * canonical ones defined in Namespace.php.
622 * @param string $text
623 * @return int|bool An integer if $text is a valid value otherwise false
625 function getLocalNsIndex( $text ) {
626 $lctext = $this->lc( $text );
627 $ids = $this->getNamespaceIds();
628 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
634 function getNamespaceAliases() {
635 if ( is_null( $this->namespaceAliases
) ) {
636 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
640 foreach ( $aliases as $name => $index ) {
641 if ( $index === NS_PROJECT_TALK
) {
642 unset( $aliases[$name] );
643 $name = $this->fixVariableInNamespace( $name );
644 $aliases[$name] = $index;
649 global $wgExtraGenderNamespaces;
650 $genders = $wgExtraGenderNamespaces +
651 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
652 foreach ( $genders as $index => $forms ) {
653 foreach ( $forms as $alias ) {
654 $aliases[$alias] = $index;
658 # Also add converted namespace names as aliases, to avoid confusion.
659 $convertedNames = array();
660 foreach ( $this->getVariants() as $variant ) {
661 if ( $variant === $this->mCode
) {
664 foreach ( $this->getNamespaces() as $ns => $_ ) {
665 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
669 $this->namespaceAliases
= $aliases +
$convertedNames;
672 return $this->namespaceAliases
;
678 function getNamespaceIds() {
679 if ( is_null( $this->mNamespaceIds
) ) {
680 global $wgNamespaceAliases;
681 # Put namespace names and aliases into a hashtable.
682 # If this is too slow, then we should arrange it so that it is done
683 # before caching. The catch is that at pre-cache time, the above
684 # class-specific fixup hasn't been done.
685 $this->mNamespaceIds
= array();
686 foreach ( $this->getNamespaces() as $index => $name ) {
687 $this->mNamespaceIds
[$this->lc( $name )] = $index;
689 foreach ( $this->getNamespaceAliases() as $name => $index ) {
690 $this->mNamespaceIds
[$this->lc( $name )] = $index;
692 if ( $wgNamespaceAliases ) {
693 foreach ( $wgNamespaceAliases as $name => $index ) {
694 $this->mNamespaceIds
[$this->lc( $name )] = $index;
698 return $this->mNamespaceIds
;
702 * Get a namespace key by value, case insensitive. Canonical namespace
703 * names override custom ones defined for the current language.
705 * @param string $text
706 * @return int|bool An integer if $text is a valid value otherwise false
708 function getNsIndex( $text ) {
709 $lctext = $this->lc( $text );
710 $ns = MWNamespace
::getCanonicalIndex( $lctext );
711 if ( $ns !== null ) {
714 $ids = $this->getNamespaceIds();
715 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
719 * short names for language variants used for language conversion links.
721 * @param string $code
722 * @param bool $usemsg Use the "variantname-xyz" message if it exists
725 function getVariantname( $code, $usemsg = true ) {
726 $msg = "variantname-$code";
727 if ( $usemsg && wfMessage( $msg )->exists() ) {
728 return $this->getMessageFromDB( $msg );
730 $name = self
::fetchLanguageName( $code );
732 return $name; # if it's defined as a language name, show that
734 # otherwise, output the language code
740 * @deprecated since 1.24, doesn't handle conflicting aliases. Use
741 * SpecialPageFactory::getLocalNameFor instead.
742 * @param string $name
745 function specialPage( $name ) {
746 $aliases = $this->getSpecialPageAliases();
747 if ( isset( $aliases[$name][0] ) ) {
748 $name = $aliases[$name][0];
750 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
756 function getDatePreferences() {
757 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
763 function getDateFormats() {
764 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
768 * @return array|string
770 function getDefaultDateFormat() {
771 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
772 if ( $df === 'dmy or mdy' ) {
773 global $wgAmericanDates;
774 return $wgAmericanDates ?
'mdy' : 'dmy';
783 function getDatePreferenceMigrationMap() {
784 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
788 * @param string $image
791 function getImageFile( $image ) {
792 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
799 function getImageFiles() {
800 return self
::$dataCache->getItem( $this->mCode
, 'imageFiles' );
806 function getExtraUserToggles() {
807 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
814 function getUserToggle( $tog ) {
815 return $this->getMessageFromDB( "tog-$tog" );
819 * Get native language names, indexed by code.
820 * Only those defined in MediaWiki, no other data like CLDR.
821 * If $customisedOnly is true, only returns codes with a messages file
823 * @param bool $customisedOnly
826 * @deprecated since 1.20, use fetchLanguageNames()
828 public static function getLanguageNames( $customisedOnly = false ) {
829 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
833 * Get translated language names. This is done on best effort and
834 * by default this is exactly the same as Language::getLanguageNames.
835 * The CLDR extension provides translated names.
836 * @param string $code Language code.
837 * @return array Language code => language name
839 * @deprecated since 1.20, use fetchLanguageNames()
841 public static function getTranslatedLanguageNames( $code ) {
842 return self
::fetchLanguageNames( $code, 'all' );
846 * Get an array of language names, indexed by code.
847 * @param null|string $inLanguage Code of language in which to return the names
848 * Use null for autonyms (native names)
849 * @param string $include One of:
850 * 'all' all available languages
851 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
852 * 'mwfile' only if the language is in 'mw' *and* has a message file
853 * @return array Language code => language name
856 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
857 $cacheKey = $inLanguage === null ?
'null' : $inLanguage;
858 $cacheKey .= ":$include";
859 if ( self
::$languageNameCache === null ) {
860 self
::$languageNameCache = new MapCacheLRU( 20 );
862 if ( self
::$languageNameCache->has( $cacheKey ) ) {
863 $ret = self
::$languageNameCache->get( $cacheKey );
865 $ret = self
::fetchLanguageNamesUncached( $inLanguage, $include );
866 self
::$languageNameCache->set( $cacheKey, $ret );
872 * Uncached helper for fetchLanguageNames
873 * @param null|string $inLanguage Code of language in which to return the names
874 * Use null for autonyms (native names)
875 * @param string $include One of:
876 * 'all' all available languages
877 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
878 * 'mwfile' only if the language is in 'mw' *and* has a message file
879 * @return array Language code => language name
881 private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
882 global $wgExtraLanguageNames;
883 static $coreLanguageNames;
885 if ( $coreLanguageNames === null ) {
887 include "$IP/languages/Names.php";
890 // If passed an invalid language code to use, fallback to en
891 if ( $inLanguage !== null && !Language
::isValidCode( $inLanguage ) ) {
898 # TODO: also include when $inLanguage is null, when this code is more efficient
899 Hooks
::run( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
902 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
903 foreach ( $mwNames as $mwCode => $mwName ) {
904 # - Prefer own MediaWiki native name when not using the hook
905 # - For other names just add if not added through the hook
906 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
907 $names[$mwCode] = $mwName;
911 if ( $include === 'all' ) {
917 $coreCodes = array_keys( $mwNames );
918 foreach ( $coreCodes as $coreCode ) {
919 $returnMw[$coreCode] = $names[$coreCode];
922 if ( $include === 'mwfile' ) {
923 $namesMwFile = array();
924 # We do this using a foreach over the codes instead of a directory
925 # loop so that messages files in extensions will work correctly.
926 foreach ( $returnMw as $code => $value ) {
927 if ( is_readable( self
::getMessagesFileName( $code ) )
928 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
930 $namesMwFile[$code] = $names[$code];
934 ksort( $namesMwFile );
939 # 'mw' option; default if it's not one of the other two options (all/mwfile)
944 * @param string $code The code of the language for which to get the name
945 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
946 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
947 * @return string Language name or empty
950 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
951 $code = strtolower( $code );
952 $array = self
::fetchLanguageNames( $inLanguage, $include );
953 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
957 * Get a message from the MediaWiki namespace.
959 * @param string $msg Message name
962 function getMessageFromDB( $msg ) {
963 return $this->msg( $msg )->text();
967 * Get message object in this language. Only for use inside this class.
969 * @param string $msg Message name
972 protected function msg( $msg ) {
973 return wfMessage( $msg )->inLanguage( $this );
977 * Get the native language name of $code.
978 * Only if defined in MediaWiki, no other data like CLDR.
979 * @param string $code
981 * @deprecated since 1.20, use fetchLanguageName()
983 function getLanguageName( $code ) {
984 return self
::fetchLanguageName( $code );
991 function getMonthName( $key ) {
992 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
998 function getMonthNamesArray() {
999 $monthNames = array( '' );
1000 for ( $i = 1; $i < 13; $i++
) {
1001 $monthNames[] = $this->getMonthName( $i );
1007 * @param string $key
1010 function getMonthNameGen( $key ) {
1011 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
1015 * @param string $key
1018 function getMonthAbbreviation( $key ) {
1019 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
1025 function getMonthAbbreviationsArray() {
1026 $monthNames = array( '' );
1027 for ( $i = 1; $i < 13; $i++
) {
1028 $monthNames[] = $this->getMonthAbbreviation( $i );
1034 * @param string $key
1037 function getWeekdayName( $key ) {
1038 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1042 * @param string $key
1045 function getWeekdayAbbreviation( $key ) {
1046 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1050 * @param string $key
1053 function getIranianCalendarMonthName( $key ) {
1054 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1058 * @param string $key
1061 function getHebrewCalendarMonthName( $key ) {
1062 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1066 * @param string $key
1069 function getHebrewCalendarMonthNameGen( $key ) {
1070 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1074 * @param string $key
1077 function getHijriCalendarMonthName( $key ) {
1078 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1082 * Pass through result from $dateTimeObj->format()
1083 * @param DateTime|bool|null &$dateTimeObj
1085 * @param DateTimeZone|bool|null $zone
1086 * @param string $code
1089 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1090 if ( !$dateTimeObj ) {
1091 $dateTimeObj = DateTime
::createFromFormat(
1092 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1095 return $dateTimeObj->format( $code );
1099 * This is a workalike of PHP's date() function, but with better
1100 * internationalisation, a reduced set of format characters, and a better
1103 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1104 * the PHP manual for definitions. There are a number of extensions, which
1107 * xn Do not translate digits of the next numeric format character
1108 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1109 * xr Use roman numerals for the next numeric format character
1110 * xh Use hebrew numerals for the next numeric format character
1112 * xg Genitive month name
1114 * xij j (day number) in Iranian calendar
1115 * xiF F (month name) in Iranian calendar
1116 * xin n (month number) in Iranian calendar
1117 * xiy y (two digit year) in Iranian calendar
1118 * xiY Y (full year) in Iranian calendar
1120 * xjj j (day number) in Hebrew calendar
1121 * xjF F (month name) in Hebrew calendar
1122 * xjt t (days in month) in Hebrew calendar
1123 * xjx xg (genitive month name) in Hebrew calendar
1124 * xjn n (month number) in Hebrew calendar
1125 * xjY Y (full year) in Hebrew calendar
1127 * xmj j (day number) in Hijri calendar
1128 * xmF F (month name) in Hijri calendar
1129 * xmn n (month number) in Hijri calendar
1130 * xmY Y (full year) in Hijri calendar
1132 * xkY Y (full year) in Thai solar calendar. Months and days are
1133 * identical to the Gregorian calendar
1134 * xoY Y (full year) in Minguo calendar or Juche year.
1135 * Months and days are identical to the
1136 * Gregorian calendar
1137 * xtY Y (full year) in Japanese nengo. Months and days are
1138 * identical to the Gregorian calendar
1140 * Characters enclosed in double quotes will be considered literal (with
1141 * the quotes themselves removed). Unmatched quotes will be considered
1142 * literal quotes. Example:
1144 * "The month is" F => The month is January
1147 * Backslash escaping is also supported.
1149 * Input timestamp is assumed to be pre-normalized to the desired local
1150 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1151 * $ts is UTC if $zone is not given.
1153 * @param string $format
1154 * @param string $ts 14-character timestamp
1157 * @param DateTimeZone $zone Timezone of $ts
1158 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1159 * Only makes sense if $ts is the current time.
1160 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1162 * @throws MWException
1165 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1170 $dateTimeObj = false;
1179 $usedSecond = false;
1180 $usedMinute = false;
1187 $usedISOYear = false;
1188 $usedIsLeapYear = false;
1190 $usedHebrewMonth = false;
1191 $usedIranianMonth = false;
1192 $usedHijriMonth = false;
1193 $usedHebrewYear = false;
1194 $usedIranianYear = false;
1195 $usedHijriYear = false;
1196 $usedTennoYear = false;
1198 if ( strlen( $ts ) !== 14 ) {
1199 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1202 if ( !ctype_digit( $ts ) ) {
1203 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1206 $formatLength = strlen( $format );
1207 for ( $p = 0; $p < $formatLength; $p++
) {
1209 $code = $format[$p];
1210 if ( $code == 'x' && $p < $formatLength - 1 ) {
1211 $code .= $format[++
$p];
1214 if ( ( $code === 'xi'
1220 && $p < $formatLength - 1 ) {
1221 $code .= $format[++
$p];
1232 $rawToggle = !$rawToggle;
1242 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1245 $usedHebrewMonth = true;
1247 $hebrew = self
::tsToHebrew( $ts );
1249 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1253 $num = substr( $ts, 6, 2 );
1257 $s .= $this->getWeekdayAbbreviation(
1258 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1
1263 $num = intval( substr( $ts, 6, 2 ) );
1268 $iranian = self
::tsToIranian( $ts );
1275 $hijri = self
::tsToHijri( $ts );
1282 $hebrew = self
::tsToHebrew( $ts );
1288 $s .= $this->getWeekdayName(
1289 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1
1294 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1297 $usedIranianMonth = true;
1299 $iranian = self
::tsToIranian( $ts );
1301 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1304 $usedHijriMonth = true;
1306 $hijri = self
::tsToHijri( $ts );
1308 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1311 $usedHebrewMonth = true;
1313 $hebrew = self
::tsToHebrew( $ts );
1315 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1319 $num = substr( $ts, 4, 2 );
1323 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1327 $num = intval( substr( $ts, 4, 2 ) );
1330 $usedIranianMonth = true;
1332 $iranian = self
::tsToIranian( $ts );
1337 $usedHijriMonth = true;
1339 $hijri = self
::tsToHijri ( $ts );
1344 $usedHebrewMonth = true;
1346 $hebrew = self
::tsToHebrew( $ts );
1351 $usedHebrewMonth = true;
1353 $hebrew = self
::tsToHebrew( $ts );
1359 $num = substr( $ts, 0, 4 );
1362 $usedIranianYear = true;
1364 $iranian = self
::tsToIranian( $ts );
1369 $usedHijriYear = true;
1371 $hijri = self
::tsToHijri( $ts );
1376 $usedHebrewYear = true;
1378 $hebrew = self
::tsToHebrew( $ts );
1385 $thai = self
::tsToYear( $ts, 'thai' );
1392 $minguo = self
::tsToYear( $ts, 'minguo' );
1397 $usedTennoYear = true;
1399 $tenno = self
::tsToYear( $ts, 'tenno' );
1405 $num = substr( $ts, 2, 2 );
1408 $usedIranianYear = true;
1410 $iranian = self
::tsToIranian( $ts );
1412 $num = substr( $iranian[0], -2 );
1416 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1420 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1424 $h = substr( $ts, 8, 2 );
1425 $num = $h %
12 ?
$h %
12 : 12;
1429 $num = intval( substr( $ts, 8, 2 ) );
1433 $h = substr( $ts, 8, 2 );
1434 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1438 $num = substr( $ts, 8, 2 );
1442 $num = substr( $ts, 10, 2 );
1446 $num = substr( $ts, 12, 2 );
1456 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1462 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1466 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1470 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1473 $usedIsLeapYear = true;
1474 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1477 $usedISOYear = true;
1478 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1485 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1488 # Backslash escaping
1489 if ( $p < $formatLength - 1 ) {
1490 $s .= $format[++
$p];
1497 if ( $p < $formatLength - 1 ) {
1498 $endQuote = strpos( $format, '"', $p +
1 );
1499 if ( $endQuote === false ) {
1500 # No terminating quote, assume literal "
1503 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1507 # Quote at end of string, assume literal "
1514 if ( $num !== false ) {
1515 if ( $rawToggle ||
$raw ) {
1518 } elseif ( $roman ) {
1519 $s .= Language
::romanNumeral( $num );
1521 } elseif ( $hebrewNum ) {
1522 $s .= self
::hebrewNumeral( $num );
1525 $s .= $this->formatNum( $num, true );
1530 if ( $usedSecond ) {
1532 } elseif ( $usedMinute ) {
1533 $ttl = 60 - substr( $ts, 12, 2 );
1534 } elseif ( $usedHour ) {
1535 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1536 } elseif ( $usedAMPM ) {
1537 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 -
1538 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1542 $usedIranianMonth ||
1549 // @todo Someone who understands the non-Gregorian calendars
1550 // should write proper logic for them so that they don't need purged every day.
1551 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1552 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1554 $possibleTtls = array();
1555 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1556 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1559 ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1560 $timeRemainingInDay;
1561 } elseif ( $usedISOYear ) {
1562 // December 28th falls on the last ISO week of the year, every year.
1563 // The last ISO week of a year can be 52 or 53.
1564 $lastWeekOfISOYear = DateTime
::createFromFormat(
1566 substr( $ts, 0, 4 ) . '1228',
1567 $zone ?
: new DateTimeZone( 'UTC' )
1569 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1570 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1571 $timeRemainingInWeek =
1572 ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1573 +
$timeRemainingInDay;
1574 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1579 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1580 substr( $ts, 6, 2 ) ) * 86400
1581 +
$timeRemainingInDay;
1582 } elseif ( $usedYear ) {
1584 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 -
1585 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1586 +
$timeRemainingInDay;
1587 } elseif ( $usedIsLeapYear ) {
1588 $year = substr( $ts, 0, 4 );
1589 $timeRemainingInYear =
1590 ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 -
1591 Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1592 +
$timeRemainingInDay;
1594 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1595 // this isn't a leap year. see when the next one starts
1596 $nextCandidate = $year - $mod +
4;
1597 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1598 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1599 $timeRemainingInYear;
1601 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
1602 $timeRemainingInYear;
1605 // this is a leap year, so the next year isn't
1606 $possibleTtls[] = $timeRemainingInYear;
1610 if ( $possibleTtls ) {
1611 $ttl = min( $possibleTtls );
1618 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1619 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1622 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1623 * Gregorian dates to Iranian dates. Originally written in C, it
1624 * is released under the terms of GNU Lesser General Public
1625 * License. Conversion to PHP was performed by Niklas Laxström.
1627 * Link: http://www.farsiweb.info/jalali/jalali.c
1633 private static function tsToIranian( $ts ) {
1634 $gy = substr( $ts, 0, 4 ) -1600;
1635 $gm = substr( $ts, 4, 2 ) -1;
1636 $gd = substr( $ts, 6, 2 ) -1;
1638 # Days passed from the beginning (including leap years)
1640 +
floor( ( $gy +
3 ) / 4 )
1641 - floor( ( $gy +
99 ) / 100 )
1642 +
floor( ( $gy +
399 ) / 400 );
1644 // Add days of the past months of this year
1645 for ( $i = 0; $i < $gm; $i++
) {
1646 $gDayNo +
= self
::$GREG_DAYS[$i];
1650 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1654 // Days passed in current month
1655 $gDayNo +
= (int)$gd;
1657 $jDayNo = $gDayNo - 79;
1659 $jNp = floor( $jDayNo / 12053 );
1662 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1665 if ( $jDayNo >= 366 ) {
1666 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1667 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1670 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1671 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1677 return array( $jy, $jm, $jd );
1681 * Converting Gregorian dates to Hijri dates.
1683 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1685 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1691 private static function tsToHijri( $ts ) {
1692 $year = substr( $ts, 0, 4 );
1693 $month = substr( $ts, 4, 2 );
1694 $day = substr( $ts, 6, 2 );
1702 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1703 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1705 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1706 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1707 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1710 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1711 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1714 $zl = $zjd -1948440 +
10632;
1715 $zn = (int)( ( $zl - 1 ) / 10631 );
1716 $zl = $zl - 10631 * $zn +
354;
1717 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1718 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1719 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1720 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1721 $zm = (int)( ( 24 * $zl ) / 709 );
1722 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1723 $zy = 30 * $zn +
$zj - 30;
1725 return array( $zy, $zm, $zd );
1729 * Converting Gregorian dates to Hebrew dates.
1731 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1732 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1733 * to translate the relevant functions into PHP and release them under
1736 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1737 * and Adar II is 14. In a non-leap year, Adar is 6.
1743 private static function tsToHebrew( $ts ) {
1745 $year = substr( $ts, 0, 4 );
1746 $month = substr( $ts, 4, 2 );
1747 $day = substr( $ts, 6, 2 );
1749 # Calculate Hebrew year
1750 $hebrewYear = $year +
3760;
1752 # Month number when September = 1, August = 12
1754 if ( $month > 12 ) {
1761 # Calculate day of year from 1 September
1763 for ( $i = 1; $i < $month; $i++
) {
1767 # Check if the year is leap
1768 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1771 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1778 # Calculate the start of the Hebrew year
1779 $start = self
::hebrewYearStart( $hebrewYear );
1781 # Calculate next year's start
1782 if ( $dayOfYear <= $start ) {
1783 # Day is before the start of the year - it is the previous year
1785 $nextStart = $start;
1789 # Add days since previous year's 1 September
1791 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1795 # Start of the new (previous) year
1796 $start = self
::hebrewYearStart( $hebrewYear );
1799 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1802 # Calculate Hebrew day of year
1803 $hebrewDayOfYear = $dayOfYear - $start;
1805 # Difference between year's days
1806 $diff = $nextStart - $start;
1807 # Add 12 (or 13 for leap years) days to ignore the difference between
1808 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1809 # difference is only about the year type
1810 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1816 # Check the year pattern, and is leap year
1817 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1818 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1819 # and non-leap years
1820 $yearPattern = $diff %
30;
1821 # Check if leap year
1822 $isLeap = $diff >= 30;
1824 # Calculate day in the month from number of day in the Hebrew year
1825 # Don't check Adar - if the day is not in Adar, we will stop before;
1826 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1827 $hebrewDay = $hebrewDayOfYear;
1830 while ( $hebrewMonth <= 12 ) {
1831 # Calculate days in this month
1832 if ( $isLeap && $hebrewMonth == 6 ) {
1833 # Adar in a leap year
1835 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1837 if ( $hebrewDay <= $days ) {
1841 # Subtract the days of Adar I
1842 $hebrewDay -= $days;
1845 if ( $hebrewDay <= $days ) {
1851 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1852 # Cheshvan in a complete year (otherwise as the rule below)
1854 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1855 # Kislev in an incomplete year (otherwise as the rule below)
1858 # Odd months have 30 days, even have 29
1859 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1861 if ( $hebrewDay <= $days ) {
1862 # In the current month
1865 # Subtract the days of the current month
1866 $hebrewDay -= $days;
1867 # Try in the next month
1872 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1876 * This calculates the Hebrew year start, as days since 1 September.
1877 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1878 * Used for Hebrew date.
1884 private static function hebrewYearStart( $year ) {
1885 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1886 $b = intval( ( $year - 1 ) %
4 );
1887 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1891 $Mar = intval( $m );
1897 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1898 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1900 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1902 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1906 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1911 * Algorithm to convert Gregorian dates to Thai solar dates,
1912 * Minguo dates or Minguo dates.
1914 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1915 * http://en.wikipedia.org/wiki/Minguo_calendar
1916 * http://en.wikipedia.org/wiki/Japanese_era_name
1918 * @param string $ts 14-character timestamp
1919 * @param string $cName Calender name
1920 * @return array Converted year, month, day
1922 private static function tsToYear( $ts, $cName ) {
1923 $gy = substr( $ts, 0, 4 );
1924 $gm = substr( $ts, 4, 2 );
1925 $gd = substr( $ts, 6, 2 );
1927 if ( !strcmp( $cName, 'thai' ) ) {
1929 # Add 543 years to the Gregorian calendar
1930 # Months and days are identical
1931 $gy_offset = $gy +
543;
1932 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1934 # Deduct 1911 years from the Gregorian calendar
1935 # Months and days are identical
1936 $gy_offset = $gy - 1911;
1937 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1938 # Nengō dates up to Meiji period
1939 # Deduct years from the Gregorian calendar
1940 # depending on the nengo periods
1941 # Months and days are identical
1943 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1944 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1947 $gy_gannen = $gy - 1868 +
1;
1948 $gy_offset = $gy_gannen;
1949 if ( $gy_gannen == 1 ) {
1952 $gy_offset = '明治' . $gy_offset;
1954 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1955 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1956 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1957 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1958 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1961 $gy_gannen = $gy - 1912 +
1;
1962 $gy_offset = $gy_gannen;
1963 if ( $gy_gannen == 1 ) {
1966 $gy_offset = '大正' . $gy_offset;
1968 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1969 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1970 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1973 $gy_gannen = $gy - 1926 +
1;
1974 $gy_offset = $gy_gannen;
1975 if ( $gy_gannen == 1 ) {
1978 $gy_offset = '昭和' . $gy_offset;
1981 $gy_gannen = $gy - 1989 +
1;
1982 $gy_offset = $gy_gannen;
1983 if ( $gy_gannen == 1 ) {
1986 $gy_offset = '平成' . $gy_offset;
1992 return array( $gy_offset, $gm, $gd );
1996 * Roman number formatting up to 10000
2002 static function romanNumeral( $num ) {
2003 static $table = array(
2004 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
2005 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
2006 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
2007 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
2008 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
2011 $num = intval( $num );
2012 if ( $num > 10000 ||
$num <= 0 ) {
2017 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2018 if ( $num >= $pow10 ) {
2019 $s .= $table[$i][(int)floor( $num / $pow10 )];
2021 $num = $num %
$pow10;
2027 * Hebrew Gematria number formatting up to 9999
2033 static function hebrewNumeral( $num ) {
2034 static $table = array(
2035 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
2036 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
2037 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
2038 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
2041 $num = intval( $num );
2042 if ( $num > 9999 ||
$num <= 0 ) {
2047 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2048 if ( $num >= $pow10 ) {
2049 if ( $num === 15 ||
$num === 16 ) {
2050 $s .= $table[0][9] . $table[0][$num - 9];
2053 $s .= $table[$i][intval( ( $num / $pow10 ) )];
2054 if ( $pow10 === 1000 ) {
2060 $num = $num %
$pow10;
2063 if ( strlen( $s ) === 2 ) {
2066 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
2067 $str .= substr( $s, strlen( $s ) - 2, 2 );
2070 $start = substr( $str, 0, strlen( $str ) - 2 );
2071 $end = substr( $str, strlen( $str ) - 2 );
2075 $str = $start . 'ך';
2078 $str = $start . 'ם';
2081 $str = $start . 'ן';
2084 $str = $start . 'ף';
2087 $str = $start . 'ץ';
2095 * Used by date() and time() to adjust the time output.
2097 * @param string $ts The time in date('YmdHis') format
2098 * @param mixed $tz Adjust the time by this amount (default false, mean we
2099 * get user timecorrection setting)
2102 function userAdjust( $ts, $tz = false ) {
2103 global $wgUser, $wgLocalTZoffset;
2105 if ( $tz === false ) {
2106 $tz = $wgUser->getOption( 'timecorrection' );
2109 $data = explode( '|', $tz, 3 );
2111 if ( $data[0] == 'ZoneInfo' ) {
2112 wfSuppressWarnings();
2113 $userTZ = timezone_open( $data[2] );
2114 wfRestoreWarnings();
2115 if ( $userTZ !== false ) {
2116 $date = date_create( $ts, timezone_open( 'UTC' ) );
2117 date_timezone_set( $date, $userTZ );
2118 $date = date_format( $date, 'YmdHis' );
2121 # Unrecognized timezone, default to 'Offset' with the stored offset.
2122 $data[0] = 'Offset';
2125 if ( $data[0] == 'System' ||
$tz == '' ) {
2126 # Global offset in minutes.
2127 $minDiff = $wgLocalTZoffset;
2128 } elseif ( $data[0] == 'Offset' ) {
2129 $minDiff = intval( $data[1] );
2131 $data = explode( ':', $tz );
2132 if ( count( $data ) == 2 ) {
2133 $data[0] = intval( $data[0] );
2134 $data[1] = intval( $data[1] );
2135 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2136 if ( $data[0] < 0 ) {
2137 $minDiff = -$minDiff;
2140 $minDiff = intval( $data[0] ) * 60;
2144 # No difference ? Return time unchanged
2145 if ( 0 == $minDiff ) {
2149 wfSuppressWarnings(); // E_STRICT system time bitching
2150 # Generate an adjusted date; take advantage of the fact that mktime
2151 # will normalize out-of-range values so we don't have to split $minDiff
2152 # into hours and minutes.
2154 (int)substr( $ts, 8, 2 ) ), # Hours
2155 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2156 (int)substr( $ts, 12, 2 ), # Seconds
2157 (int)substr( $ts, 4, 2 ), # Month
2158 (int)substr( $ts, 6, 2 ), # Day
2159 (int)substr( $ts, 0, 4 ) ); # Year
2161 $date = date( 'YmdHis', $t );
2162 wfRestoreWarnings();
2168 * This is meant to be used by time(), date(), and timeanddate() to get
2169 * the date preference they're supposed to use, it should be used in
2173 * function timeanddate([...], $format = true) {
2174 * $datePreference = $this->dateFormat($format);
2179 * @param int|string|bool $usePrefs If true, the user's preference is used
2180 * if false, the site/language default is used
2181 * if int/string, assumed to be a format.
2184 function dateFormat( $usePrefs = true ) {
2187 if ( is_bool( $usePrefs ) ) {
2189 $datePreference = $wgUser->getDatePreference();
2191 $datePreference = (string)User
::getDefaultOption( 'date' );
2194 $datePreference = (string)$usePrefs;
2198 if ( $datePreference == '' ) {
2202 return $datePreference;
2206 * Get a format string for a given type and preference
2207 * @param string $type May be date, time or both
2208 * @param string $pref The format name as it appears in Messages*.php
2210 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2214 function getDateFormatString( $type, $pref ) {
2215 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2216 if ( $pref == 'default' ) {
2217 $pref = $this->getDefaultDateFormat();
2218 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2220 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2222 if ( $type === 'pretty' && $df === null ) {
2223 $df = $this->getDateFormatString( 'date', $pref );
2226 if ( $df === null ) {
2227 $pref = $this->getDefaultDateFormat();
2228 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2231 $this->dateFormatStrings
[$type][$pref] = $df;
2233 return $this->dateFormatStrings
[$type][$pref];
2237 * @param string $ts The time format which needs to be turned into a
2238 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2239 * @param bool $adj Whether to adjust the time output according to the
2240 * user configured offset ($timecorrection)
2241 * @param mixed $format True to use user's date format preference
2242 * @param string|bool $timecorrection The time offset as returned by
2243 * validateTimeZone() in Special:Preferences
2246 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2247 $ts = wfTimestamp( TS_MW
, $ts );
2249 $ts = $this->userAdjust( $ts, $timecorrection );
2251 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2252 return $this->sprintfDate( $df, $ts );
2256 * @param string $ts The time format which needs to be turned into a
2257 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2258 * @param bool $adj Whether to adjust the time output according to the
2259 * user configured offset ($timecorrection)
2260 * @param mixed $format True to use user's date format preference
2261 * @param string|bool $timecorrection The time offset as returned by
2262 * validateTimeZone() in Special:Preferences
2265 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2266 $ts = wfTimestamp( TS_MW
, $ts );
2268 $ts = $this->userAdjust( $ts, $timecorrection );
2270 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2271 return $this->sprintfDate( $df, $ts );
2275 * @param string $ts The time format which needs to be turned into a
2276 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2277 * @param bool $adj Whether to adjust the time output according to the
2278 * user configured offset ($timecorrection)
2279 * @param mixed $format What format to return, if it's false output the
2280 * default one (default true)
2281 * @param string|bool $timecorrection The time offset as returned by
2282 * validateTimeZone() in Special:Preferences
2285 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2286 $ts = wfTimestamp( TS_MW
, $ts );
2288 $ts = $this->userAdjust( $ts, $timecorrection );
2290 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2291 return $this->sprintfDate( $df, $ts );
2295 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2299 * @param int $seconds The amount of seconds.
2300 * @param array $chosenIntervals The intervals to enable.
2304 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2305 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2307 $segments = array();
2309 foreach ( $intervals as $intervalName => $intervalValue ) {
2310 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2311 // duration-years, duration-decades, duration-centuries, duration-millennia
2312 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2313 $segments[] = $message->inLanguage( $this )->escaped();
2316 return $this->listToText( $segments );
2320 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2321 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2325 * @param int $seconds The amount of seconds.
2326 * @param array $chosenIntervals The intervals to enable.
2330 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2331 if ( empty( $chosenIntervals ) ) {
2332 $chosenIntervals = array(
2344 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2345 $sortedNames = array_keys( $intervals );
2346 $smallestInterval = array_pop( $sortedNames );
2348 $segments = array();
2350 foreach ( $intervals as $name => $length ) {
2351 $value = floor( $seconds / $length );
2353 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2354 $seconds -= $value * $length;
2355 $segments[$name] = $value;
2363 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2365 * @param string $type Can be 'date', 'time' or 'both'
2366 * @param string $ts The time format which needs to be turned into a
2367 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2368 * @param User $user User object used to get preferences for timezone and format
2369 * @param array $options Array, can contain the following keys:
2370 * - 'timecorrection': time correction, can have the following values:
2371 * - true: use user's preference
2372 * - false: don't use time correction
2373 * - int: value of time correction in minutes
2374 * - 'format': format to use, can have the following values:
2375 * - true: use user's preference
2376 * - false: use default preference
2377 * - string: format to use
2381 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2382 $ts = wfTimestamp( TS_MW
, $ts );
2383 $options +
= array( 'timecorrection' => true, 'format' => true );
2384 if ( $options['timecorrection'] !== false ) {
2385 if ( $options['timecorrection'] === true ) {
2386 $offset = $user->getOption( 'timecorrection' );
2388 $offset = $options['timecorrection'];
2390 $ts = $this->userAdjust( $ts, $offset );
2392 if ( $options['format'] === true ) {
2393 $format = $user->getDatePreference();
2395 $format = $options['format'];
2397 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2398 return $this->sprintfDate( $df, $ts );
2402 * Get the formatted date for the given timestamp and formatted for
2405 * @param mixed $ts Mixed: the time format which needs to be turned into a
2406 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2407 * @param User $user User object used to get preferences for timezone and format
2408 * @param array $options Array, can contain the following keys:
2409 * - 'timecorrection': time correction, can have the following values:
2410 * - true: use user's preference
2411 * - false: don't use time correction
2412 * - int: value of time correction in minutes
2413 * - 'format': format to use, can have the following values:
2414 * - true: use user's preference
2415 * - false: use default preference
2416 * - string: format to use
2420 public function userDate( $ts, User
$user, array $options = array() ) {
2421 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2425 * Get the formatted time for the given timestamp and formatted for
2428 * @param mixed $ts The time format which needs to be turned into a
2429 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2430 * @param User $user User object used to get preferences for timezone and format
2431 * @param array $options Array, can contain the following keys:
2432 * - 'timecorrection': time correction, can have the following values:
2433 * - true: use user's preference
2434 * - false: don't use time correction
2435 * - int: value of time correction in minutes
2436 * - 'format': format to use, can have the following values:
2437 * - true: use user's preference
2438 * - false: use default preference
2439 * - string: format to use
2443 public function userTime( $ts, User
$user, array $options = array() ) {
2444 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2448 * Get the formatted date and time for the given timestamp and formatted for
2451 * @param mixed $ts The time format which needs to be turned into a
2452 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2453 * @param User $user User object used to get preferences for timezone and format
2454 * @param array $options Array, can contain the following keys:
2455 * - 'timecorrection': time correction, can have the following values:
2456 * - true: use user's preference
2457 * - false: don't use time correction
2458 * - int: value of time correction in minutes
2459 * - 'format': format to use, can have the following values:
2460 * - true: use user's preference
2461 * - false: use default preference
2462 * - string: format to use
2466 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2467 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2471 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
2473 * Determine the difference between the timestamp and the current time, and
2474 * generate a readable timestamp by returning "<N> <units> ago", where the
2475 * largest possible unit is used.
2477 * @since 1.26 (Prior to 1.26 method existed but was not meant to be used directly)
2479 * @param MWTimestamp $time
2480 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
2481 * @param User|null $user User the timestamp is being generated for (or null to use main context's user)
2482 * @return string Formatted timestamp
2484 public function getHumanTimestamp( MWTimestamp
$time, MWTimestamp
$relativeTo = null, User
$user = null ) {
2485 if ( $relativeTo === null ) {
2486 $relativeTo = new MWTimestamp();
2488 if ( $user === null ) {
2489 $user = RequestContext
::getMain()->getUser();
2492 // Adjust for the user's timezone.
2493 $offsetThis = $time->offsetForUser( $user );
2494 $offsetRel = $relativeTo->offsetForUser( $user );
2497 if ( Hooks
::run( 'GetHumanTimestamp', array( &$ts, $time, $relativeTo, $user, $this ) ) ) {
2498 $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2501 // Reset the timezone on the objects.
2502 $time->timestamp
->sub( $offsetThis );
2503 $relativeTo->timestamp
->sub( $offsetRel );
2509 * Convert an MWTimestamp into a pretty human-readable timestamp using
2510 * the given user preferences and relative base time.
2512 * @see Language::getHumanTimestamp
2513 * @param MWTimestamp $ts Timestamp to prettify
2514 * @param MWTimestamp $relativeTo Base timestamp
2515 * @param User $user User preferences to use
2516 * @return string Human timestamp
2519 private function getHumanTimestampInternal( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2520 $diff = $ts->diff( $relativeTo );
2521 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2522 (int)$relativeTo->timestamp
->format( 'w' ) );
2523 $days = $diff->days ?
: (int)$diffDay;
2524 if ( $diff->invert ||
$days > 5
2525 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2527 // Timestamps are in different years: use full timestamp
2528 // Also do full timestamp for future dates
2530 * @todo FIXME: Add better handling of future timestamps.
2532 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2533 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2534 } elseif ( $days > 5 ) {
2535 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2536 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2537 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2538 } elseif ( $days > 1 ) {
2539 // Timestamp within the past week: show the day of the week and time
2540 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2541 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2543 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2544 $ts = wfMessage( "$weekday-at" )
2545 ->inLanguage( $this )
2546 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2548 } elseif ( $days == 1 ) {
2549 // Timestamp was yesterday: say 'yesterday' and the time.
2550 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2551 $ts = wfMessage( 'yesterday-at' )
2552 ->inLanguage( $this )
2553 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2555 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2556 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2557 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2558 $ts = wfMessage( 'today-at' )
2559 ->inLanguage( $this )
2560 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2563 // From here on in, the timestamp was soon enough ago so that we can simply say
2564 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2565 } elseif ( $diff->h
== 1 ) {
2566 // Less than 90 minutes, but more than an hour ago.
2567 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2568 } elseif ( $diff->i
>= 1 ) {
2569 // A few minutes ago.
2570 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2571 } elseif ( $diff->s
>= 30 ) {
2572 // Less than a minute, but more than 30 sec ago.
2573 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2575 // Less than 30 seconds ago.
2576 $ts = wfMessage( 'just-now' )->text();
2583 * @param string $key
2584 * @return array|null
2586 function getMessage( $key ) {
2587 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2593 function getAllMessages() {
2594 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2599 * @param string $out
2600 * @param string $string
2603 function iconv( $in, $out, $string ) {
2604 # This is a wrapper for iconv in all languages except esperanto,
2605 # which does some nasty x-conversions beforehand
2607 # Even with //IGNORE iconv can whine about illegal characters in
2608 # *input* string. We just ignore those too.
2609 # REF: http://bugs.php.net/bug.php?id=37166
2610 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2611 wfSuppressWarnings();
2612 $text = iconv( $in, $out . '//IGNORE', $string );
2613 wfRestoreWarnings();
2617 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2620 * @param array $matches
2621 * @return mixed|string
2623 function ucwordbreaksCallbackAscii( $matches ) {
2624 return $this->ucfirst( $matches[1] );
2628 * @param array $matches
2631 function ucwordbreaksCallbackMB( $matches ) {
2632 return mb_strtoupper( $matches[0] );
2636 * @param array $matches
2639 function ucCallback( $matches ) {
2640 list( $wikiUpperChars ) = self
::getCaseMaps();
2641 return strtr( $matches[1], $wikiUpperChars );
2645 * @param array $matches
2648 function lcCallback( $matches ) {
2649 list( , $wikiLowerChars ) = self
::getCaseMaps();
2650 return strtr( $matches[1], $wikiLowerChars );
2654 * @param array $matches
2657 function ucwordsCallbackMB( $matches ) {
2658 return mb_strtoupper( $matches[0] );
2662 * @param array $matches
2665 function ucwordsCallbackWiki( $matches ) {
2666 list( $wikiUpperChars ) = self
::getCaseMaps();
2667 return strtr( $matches[0], $wikiUpperChars );
2671 * Make a string's first character uppercase
2673 * @param string $str
2677 function ucfirst( $str ) {
2679 if ( $o < 96 ) { // if already uppercase...
2681 } elseif ( $o < 128 ) {
2682 return ucfirst( $str ); // use PHP's ucfirst()
2684 // fall back to more complex logic in case of multibyte strings
2685 return $this->uc( $str, true );
2690 * Convert a string to uppercase
2692 * @param string $str
2693 * @param bool $first
2697 function uc( $str, $first = false ) {
2698 if ( function_exists( 'mb_strtoupper' ) ) {
2700 if ( $this->isMultibyte( $str ) ) {
2701 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2703 return ucfirst( $str );
2706 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2709 if ( $this->isMultibyte( $str ) ) {
2710 $x = $first ?
'^' : '';
2711 return preg_replace_callback(
2712 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2713 array( $this, 'ucCallback' ),
2717 return $first ?
ucfirst( $str ) : strtoupper( $str );
2723 * @param string $str
2724 * @return mixed|string
2726 function lcfirst( $str ) {
2729 return strval( $str );
2730 } elseif ( $o >= 128 ) {
2731 return $this->lc( $str, true );
2732 } elseif ( $o > 96 ) {
2735 $str[0] = strtolower( $str[0] );
2741 * @param string $str
2742 * @param bool $first
2743 * @return mixed|string
2745 function lc( $str, $first = false ) {
2746 if ( function_exists( 'mb_strtolower' ) ) {
2748 if ( $this->isMultibyte( $str ) ) {
2749 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2751 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2754 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2757 if ( $this->isMultibyte( $str ) ) {
2758 $x = $first ?
'^' : '';
2759 return preg_replace_callback(
2760 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2761 array( $this, 'lcCallback' ),
2765 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2771 * @param string $str
2774 function isMultibyte( $str ) {
2775 return (bool)preg_match( '/[\x80-\xff]/', $str );
2779 * @param string $str
2780 * @return mixed|string
2782 function ucwords( $str ) {
2783 if ( $this->isMultibyte( $str ) ) {
2784 $str = $this->lc( $str );
2786 // regexp to find first letter in each word (i.e. after each space)
2787 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2789 // function to use to capitalize a single char
2790 if ( function_exists( 'mb_strtoupper' ) ) {
2791 return preg_replace_callback(
2793 array( $this, 'ucwordsCallbackMB' ),
2797 return preg_replace_callback(
2799 array( $this, 'ucwordsCallbackWiki' ),
2804 return ucwords( strtolower( $str ) );
2809 * capitalize words at word breaks
2811 * @param string $str
2814 function ucwordbreaks( $str ) {
2815 if ( $this->isMultibyte( $str ) ) {
2816 $str = $this->lc( $str );
2818 // since \b doesn't work for UTF-8, we explicitely define word break chars
2819 $breaks = "[ \-\(\)\}\{\.,\?!]";
2821 // find first letter after word break
2822 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2823 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2825 if ( function_exists( 'mb_strtoupper' ) ) {
2826 return preg_replace_callback(
2828 array( $this, 'ucwordbreaksCallbackMB' ),
2832 return preg_replace_callback(
2834 array( $this, 'ucwordsCallbackWiki' ),
2839 return preg_replace_callback(
2840 '/\b([\w\x80-\xff]+)\b/',
2841 array( $this, 'ucwordbreaksCallbackAscii' ),
2848 * Return a case-folded representation of $s
2850 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2851 * and $s2 are the same except for the case of their characters. It is not
2852 * necessary for the value returned to make sense when displayed.
2854 * Do *not* perform any other normalisation in this function. If a caller
2855 * uses this function when it should be using a more general normalisation
2856 * function, then fix the caller.
2862 function caseFold( $s ) {
2863 return $this->uc( $s );
2870 function checkTitleEncoding( $s ) {
2871 if ( is_array( $s ) ) {
2872 throw new MWException( 'Given array to checkTitleEncoding.' );
2874 if ( StringUtils
::isUtf8( $s ) ) {
2878 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2884 function fallback8bitEncoding() {
2885 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2889 * Most writing systems use whitespace to break up words.
2890 * Some languages such as Chinese don't conventionally do this,
2891 * which requires special handling when breaking up words for
2896 function hasWordBreaks() {
2901 * Some languages such as Chinese require word segmentation,
2902 * Specify such segmentation when overridden in derived class.
2904 * @param string $string
2907 function segmentByWord( $string ) {
2912 * Some languages have special punctuation need to be normalized.
2913 * Make such changes here.
2915 * @param string $string
2918 function normalizeForSearch( $string ) {
2919 return self
::convertDoubleWidth( $string );
2923 * convert double-width roman characters to single-width.
2924 * range: ff00-ff5f ~= 0020-007f
2926 * @param string $string
2930 protected static function convertDoubleWidth( $string ) {
2931 static $full = null;
2932 static $half = null;
2934 if ( $full === null ) {
2935 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2936 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2937 $full = str_split( $fullWidth, 3 );
2938 $half = str_split( $halfWidth );
2941 $string = str_replace( $full, $half, $string );
2946 * @param string $string
2947 * @param string $pattern
2950 protected static function insertSpace( $string, $pattern ) {
2951 $string = preg_replace( $pattern, " $1 ", $string );
2952 $string = preg_replace( '/ +/', ' ', $string );
2957 * @param array $termsArray
2960 function convertForSearchResult( $termsArray ) {
2961 # some languages, e.g. Chinese, need to do a conversion
2962 # in order for search results to be displayed correctly
2967 * Get the first character of a string.
2972 function firstChar( $s ) {
2975 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2976 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2981 if ( isset( $matches[1] ) ) {
2982 if ( strlen( $matches[1] ) != 3 ) {
2986 // Break down Hangul syllables to grab the first jamo
2987 $code = UtfNormal\Utils
::utf8ToCodepoint( $matches[1] );
2988 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2990 } elseif ( $code < 0xb098 ) {
2991 return "\xe3\x84\xb1";
2992 } elseif ( $code < 0xb2e4 ) {
2993 return "\xe3\x84\xb4";
2994 } elseif ( $code < 0xb77c ) {
2995 return "\xe3\x84\xb7";
2996 } elseif ( $code < 0xb9c8 ) {
2997 return "\xe3\x84\xb9";
2998 } elseif ( $code < 0xbc14 ) {
2999 return "\xe3\x85\x81";
3000 } elseif ( $code < 0xc0ac ) {
3001 return "\xe3\x85\x82";
3002 } elseif ( $code < 0xc544 ) {
3003 return "\xe3\x85\x85";
3004 } elseif ( $code < 0xc790 ) {
3005 return "\xe3\x85\x87";
3006 } elseif ( $code < 0xcc28 ) {
3007 return "\xe3\x85\x88";
3008 } elseif ( $code < 0xce74 ) {
3009 return "\xe3\x85\x8a";
3010 } elseif ( $code < 0xd0c0 ) {
3011 return "\xe3\x85\x8b";
3012 } elseif ( $code < 0xd30c ) {
3013 return "\xe3\x85\x8c";
3014 } elseif ( $code < 0xd558 ) {
3015 return "\xe3\x85\x8d";
3017 return "\xe3\x85\x8e";
3024 function initEncoding() {
3025 # Some languages may have an alternate char encoding option
3026 # (Esperanto X-coding, Japanese furigana conversion, etc)
3027 # If this language is used as the primary content language,
3028 # an override to the defaults can be set here on startup.
3035 function recodeForEdit( $s ) {
3036 # For some languages we'll want to explicitly specify
3037 # which characters make it into the edit box raw
3038 # or are converted in some way or another.
3039 global $wgEditEncoding;
3040 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
3043 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
3051 function recodeInput( $s ) {
3052 # Take the previous into account.
3053 global $wgEditEncoding;
3054 if ( $wgEditEncoding != '' ) {
3055 $enc = $wgEditEncoding;
3059 if ( $enc == 'UTF-8' ) {
3062 return $this->iconv( $enc, 'UTF-8', $s );
3067 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
3068 * also cleans up certain backwards-compatible sequences, converting them
3069 * to the modern Unicode equivalent.
3071 * This is language-specific for performance reasons only.
3077 function normalize( $s ) {
3078 global $wgAllUnicodeFixes;
3079 $s = UtfNormal\Validator
::cleanUp( $s );
3080 if ( $wgAllUnicodeFixes ) {
3081 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
3082 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
3089 * Transform a string using serialized data stored in the given file (which
3090 * must be in the serialized subdirectory of $IP). The file contains pairs
3091 * mapping source characters to destination characters.
3093 * The data is cached in process memory. This will go faster if you have the
3094 * FastStringSearch extension.
3096 * @param string $file
3097 * @param string $string
3099 * @throws MWException
3102 function transformUsingPairFile( $file, $string ) {
3103 if ( !isset( $this->transformData
[$file] ) ) {
3104 $data = wfGetPrecompiledData( $file );
3105 if ( $data === false ) {
3106 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
3108 $this->transformData
[$file] = new ReplacementArray( $data );
3110 return $this->transformData
[$file]->replace( $string );
3114 * For right-to-left language support
3119 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
3123 * Return the correct HTML 'dir' attribute value for this language.
3127 return $this->isRTL() ?
'rtl' : 'ltr';
3131 * Return 'left' or 'right' as appropriate alignment for line-start
3132 * for this language's text direction.
3134 * Should be equivalent to CSS3 'start' text-align value....
3138 function alignStart() {
3139 return $this->isRTL() ?
'right' : 'left';
3143 * Return 'right' or 'left' as appropriate alignment for line-end
3144 * for this language's text direction.
3146 * Should be equivalent to CSS3 'end' text-align value....
3150 function alignEnd() {
3151 return $this->isRTL() ?
'left' : 'right';
3155 * A hidden direction mark (LRM or RLM), depending on the language direction.
3156 * Unlike getDirMark(), this function returns the character as an HTML entity.
3157 * This function should be used when the output is guaranteed to be HTML,
3158 * because it makes the output HTML source code more readable. When
3159 * the output is plain text or can be escaped, getDirMark() should be used.
3161 * @param bool $opposite Get the direction mark opposite to your language
3165 function getDirMarkEntity( $opposite = false ) {
3167 return $this->isRTL() ?
'‎' : '‏';
3169 return $this->isRTL() ?
'‏' : '‎';
3173 * A hidden direction mark (LRM or RLM), depending on the language direction.
3174 * This function produces them as invisible Unicode characters and
3175 * the output may be hard to read and debug, so it should only be used
3176 * when the output is plain text or can be escaped. When the output is
3177 * HTML, use getDirMarkEntity() instead.
3179 * @param bool $opposite Get the direction mark opposite to your language
3182 function getDirMark( $opposite = false ) {
3183 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3184 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3186 return $this->isRTL() ?
$lrm : $rlm;
3188 return $this->isRTL() ?
$rlm : $lrm;
3194 function capitalizeAllNouns() {
3195 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3199 * An arrow, depending on the language direction.
3201 * @param string $direction The direction of the arrow: forwards (default),
3202 * backwards, left, right, up, down.
3205 function getArrow( $direction = 'forwards' ) {
3206 switch ( $direction ) {
3208 return $this->isRTL() ?
'←' : '→';
3210 return $this->isRTL() ?
'→' : '←';
3223 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3227 function linkPrefixExtension() {
3228 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3232 * Get all magic words from cache.
3235 function getMagicWords() {
3236 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3240 * Run the LanguageGetMagic hook once.
3242 protected function doMagicHook() {
3243 if ( $this->mMagicHookDone
) {
3246 $this->mMagicHookDone
= true;
3247 Hooks
::run( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3251 * Fill a MagicWord object with data from here
3253 * @param MagicWord $mw
3255 function getMagic( $mw ) {
3256 // Saves a function call
3257 if ( !$this->mMagicHookDone
) {
3258 $this->doMagicHook();
3261 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3262 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3264 $rawEntry = self
::$dataCache->getSubitem(
3265 $this->mCode
, 'magicWords', $mw->mId
);
3268 if ( !is_array( $rawEntry ) ) {
3269 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3271 $mw->mCaseSensitive
= $rawEntry[0];
3272 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3277 * Add magic words to the extension array
3279 * @param array $newWords
3281 function addMagicWordsByLang( $newWords ) {
3282 $fallbackChain = $this->getFallbackLanguages();
3283 $fallbackChain = array_reverse( $fallbackChain );
3284 foreach ( $fallbackChain as $code ) {
3285 if ( isset( $newWords[$code] ) ) {
3286 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3292 * Get special page names, as an associative array
3293 * canonical name => array of valid names, including aliases
3296 function getSpecialPageAliases() {
3297 // Cache aliases because it may be slow to load them
3298 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3300 $this->mExtendedSpecialPageAliases
=
3301 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3302 Hooks
::run( 'LanguageGetSpecialPageAliases',
3303 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3306 return $this->mExtendedSpecialPageAliases
;
3310 * Italic is unsuitable for some languages
3312 * @param string $text The text to be emphasized.
3315 function emphasize( $text ) {
3316 return "<em>$text</em>";
3320 * Normally we output all numbers in plain en_US style, that is
3321 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3322 * point twohundredthirtyfive. However this is not suitable for all
3323 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3324 * Icelandic just want to use commas instead of dots, and dots instead
3325 * of commas like "293.291,235".
3327 * An example of this function being called:
3329 * wfMessage( 'message' )->numParams( $num )->text()
3332 * See $separatorTransformTable on MessageIs.php for
3333 * the , => . and . => , implementation.
3335 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3336 * @param int|float $number The string to be formatted, should be an integer
3337 * or a floating point number.
3338 * @param bool $nocommafy Set to true for special numbers like dates
3341 public function formatNum( $number, $nocommafy = false ) {
3342 global $wgTranslateNumerals;
3343 if ( !$nocommafy ) {
3344 $number = $this->commafy( $number );
3345 $s = $this->separatorTransformTable();
3347 $number = strtr( $number, $s );
3351 if ( $wgTranslateNumerals ) {
3352 $s = $this->digitTransformTable();
3354 $number = strtr( $number, $s );
3362 * Front-end for non-commafied formatNum
3364 * @param int|float $number The string to be formatted, should be an integer
3365 * or a floating point number.
3369 public function formatNumNoSeparators( $number ) {
3370 return $this->formatNum( $number, true );
3374 * @param string $number
3377 public function parseFormattedNumber( $number ) {
3378 $s = $this->digitTransformTable();
3380 // eliminate empty array values such as ''. (bug 64347)
3381 $s = array_filter( $s );
3382 $number = strtr( $number, array_flip( $s ) );
3385 $s = $this->separatorTransformTable();
3387 // eliminate empty array values such as ''. (bug 64347)
3388 $s = array_filter( $s );
3389 $number = strtr( $number, array_flip( $s ) );
3392 $number = strtr( $number, array( ',' => '' ) );
3397 * Adds commas to a given number
3399 * @param mixed $number
3402 function commafy( $number ) {
3403 $digitGroupingPattern = $this->digitGroupingPattern();
3404 if ( $number === null ) {
3408 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3409 // default grouping is at thousands, use the same for ###,###,### pattern too.
3410 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3412 // Ref: http://cldr.unicode.org/translation/number-patterns
3414 if ( intval( $number ) < 0 ) {
3415 // For negative numbers apply the algorithm like positive number and add sign.
3417 $number = substr( $number, 1 );
3419 $integerPart = array();
3420 $decimalPart = array();
3421 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3422 preg_match( "/\d+/", $number, $integerPart );
3423 preg_match( "/\.\d*/", $number, $decimalPart );
3424 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3425 if ( $groupedNumber === $number ) {
3426 // the string does not have any number part. Eg: .12345
3427 return $sign . $groupedNumber;
3429 $start = $end = ($integerPart) ?
strlen( $integerPart[0] ) : 0;
3430 while ( $start > 0 ) {
3431 $match = $matches[0][$numMatches - 1];
3432 $matchLen = strlen( $match );
3433 $start = $end - $matchLen;
3437 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3439 if ( $numMatches > 1 ) {
3440 // use the last pattern for the rest of the number
3444 $groupedNumber = "," . $groupedNumber;
3447 return $sign . $groupedNumber;
3454 function digitGroupingPattern() {
3455 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3461 function digitTransformTable() {
3462 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3468 function separatorTransformTable() {
3469 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3473 * Take a list of strings and build a locale-friendly comma-separated
3474 * list, using the local comma-separator message.
3475 * The last two strings are chained with an "and".
3476 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3478 * @param string[] $l
3481 function listToText( array $l ) {
3482 $m = count( $l ) - 1;
3487 $and = $this->msg( 'and' )->escaped();
3488 $space = $this->msg( 'word-separator' )->escaped();
3490 $comma = $this->msg( 'comma-separator' )->escaped();
3494 for ( $i = $m - 1; $i >= 0; $i-- ) {
3495 if ( $i == $m - 1 ) {
3496 $s = $l[$i] . $and . $space . $s;
3498 $s = $l[$i] . $comma . $s;
3505 * Take a list of strings and build a locale-friendly comma-separated
3506 * list, using the local comma-separator message.
3507 * @param string[] $list Array of strings to put in a comma list
3510 function commaList( array $list ) {
3512 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3518 * Take a list of strings and build a locale-friendly semicolon-separated
3519 * list, using the local semicolon-separator message.
3520 * @param string[] $list Array of strings to put in a semicolon list
3523 function semicolonList( array $list ) {
3525 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3531 * Same as commaList, but separate it with the pipe instead.
3532 * @param string[] $list Array of strings to put in a pipe list
3535 function pipeList( array $list ) {
3537 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3543 * Truncate a string to a specified length in bytes, appending an optional
3544 * string (e.g. for ellipses)
3546 * The database offers limited byte lengths for some columns in the database;
3547 * multi-byte character sets mean we need to ensure that only whole characters
3548 * are included, otherwise broken characters can be passed to the user
3550 * If $length is negative, the string will be truncated from the beginning
3552 * @param string $string String to truncate
3553 * @param int $length Maximum length (including ellipses)
3554 * @param string $ellipsis String to append to the truncated text
3555 * @param bool $adjustLength Subtract length of ellipsis from $length.
3556 * $adjustLength was introduced in 1.18, before that behaved as if false.
3559 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3560 # Use the localized ellipsis character
3561 if ( $ellipsis == '...' ) {
3562 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3564 # Check if there is no need to truncate
3565 if ( $length == 0 ) {
3566 return $ellipsis; // convention
3567 } elseif ( strlen( $string ) <= abs( $length ) ) {
3568 return $string; // no need to truncate
3570 $stringOriginal = $string;
3571 # If ellipsis length is >= $length then we can't apply $adjustLength
3572 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3573 $string = $ellipsis; // this can be slightly unexpected
3574 # Otherwise, truncate and add ellipsis...
3576 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3577 if ( $length > 0 ) {
3578 $length -= $eLength;
3579 $string = substr( $string, 0, $length ); // xyz...
3580 $string = $this->removeBadCharLast( $string );
3581 $string = rtrim( $string );
3582 $string = $string . $ellipsis;
3584 $length +
= $eLength;
3585 $string = substr( $string, $length ); // ...xyz
3586 $string = $this->removeBadCharFirst( $string );
3587 $string = ltrim( $string );
3588 $string = $ellipsis . $string;
3591 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3592 # This check is *not* redundant if $adjustLength, due to the single case where
3593 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3594 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3597 return $stringOriginal;
3602 * Remove bytes that represent an incomplete Unicode character
3603 * at the end of string (e.g. bytes of the char are missing)
3605 * @param string $string
3608 protected function removeBadCharLast( $string ) {
3609 if ( $string != '' ) {
3610 $char = ord( $string[strlen( $string ) - 1] );
3612 if ( $char >= 0xc0 ) {
3613 # We got the first byte only of a multibyte char; remove it.
3614 $string = substr( $string, 0, -1 );
3615 } elseif ( $char >= 0x80 &&
3616 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3617 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3619 # We chopped in the middle of a character; remove it
3627 * Remove bytes that represent an incomplete Unicode character
3628 * at the start of string (e.g. bytes of the char are missing)
3630 * @param string $string
3633 protected function removeBadCharFirst( $string ) {
3634 if ( $string != '' ) {
3635 $char = ord( $string[0] );
3636 if ( $char >= 0x80 && $char < 0xc0 ) {
3637 # We chopped in the middle of a character; remove the whole thing
3638 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3645 * Truncate a string of valid HTML to a specified length in bytes,
3646 * appending an optional string (e.g. for ellipses), and return valid HTML
3648 * This is only intended for styled/linked text, such as HTML with
3649 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3650 * Also, this will not detect things like "display:none" CSS.
3652 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3654 * @param string $text HTML string to truncate
3655 * @param int $length (zero/positive) Maximum length (including ellipses)
3656 * @param string $ellipsis String to append to the truncated text
3659 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3660 # Use the localized ellipsis character
3661 if ( $ellipsis == '...' ) {
3662 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3664 # Check if there is clearly no need to truncate
3665 if ( $length <= 0 ) {
3666 return $ellipsis; // no text shown, nothing to format (convention)
3667 } elseif ( strlen( $text ) <= $length ) {
3668 return $text; // string short enough even *with* HTML (short-circuit)
3671 $dispLen = 0; // innerHTML legth so far
3672 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3673 $tagType = 0; // 0-open, 1-close
3674 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3675 $entityState = 0; // 0-not entity, 1-entity
3676 $tag = $ret = ''; // accumulated tag name, accumulated result string
3677 $openTags = array(); // open tag stack
3678 $maybeState = null; // possible truncation state
3680 $textLen = strlen( $text );
3681 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3682 for ( $pos = 0; true; ++
$pos ) {
3683 # Consider truncation once the display length has reached the maximim.
3684 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3685 # Check that we're not in the middle of a bracket/entity...
3686 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3687 if ( !$testingEllipsis ) {
3688 $testingEllipsis = true;
3689 # Save where we are; we will truncate here unless there turn out to
3690 # be so few remaining characters that truncation is not necessary.
3691 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3692 $maybeState = array( $ret, $openTags ); // save state
3694 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3695 # String in fact does need truncation, the truncation point was OK.
3696 list( $ret, $openTags ) = $maybeState; // reload state
3697 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3698 $ret .= $ellipsis; // add ellipsis
3702 if ( $pos >= $textLen ) {
3703 break; // extra iteration just for above checks
3706 # Read the next char...
3708 $lastCh = $pos ?
$text[$pos - 1] : '';
3709 $ret .= $ch; // add to result string
3711 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3712 $entityState = 0; // for bad HTML
3713 $bracketState = 1; // tag started (checking for backslash)
3714 } elseif ( $ch == '>' ) {
3715 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3716 $entityState = 0; // for bad HTML
3717 $bracketState = 0; // out of brackets
3718 } elseif ( $bracketState == 1 ) {
3720 $tagType = 1; // close tag (e.g. "</span>")
3722 $tagType = 0; // open tag (e.g. "<span>")
3725 $bracketState = 2; // building tag name
3726 } elseif ( $bracketState == 2 ) {
3730 // Name found (e.g. "<a href=..."), add on tag attributes...
3731 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3733 } elseif ( $bracketState == 0 ) {
3734 if ( $entityState ) {
3737 $dispLen++
; // entity is one displayed char
3740 if ( $neLength == 0 && !$maybeState ) {
3741 // Save state without $ch. We want to *hit* the first
3742 // display char (to get tags) but not *use* it if truncating.
3743 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3746 $entityState = 1; // entity found, (e.g. " ")
3748 $dispLen++
; // this char is displayed
3749 // Add the next $max display text chars after this in one swoop...
3750 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3751 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3752 $dispLen +
= $skipped;
3758 // Close the last tag if left unclosed by bad HTML
3759 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3760 while ( count( $openTags ) > 0 ) {
3761 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3767 * truncateHtml() helper function
3768 * like strcspn() but adds the skipped chars to $ret
3770 * @param string $ret
3771 * @param string $text
3772 * @param string $search
3774 * @param null|int $len
3777 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3778 if ( $len === null ) {
3779 $len = -1; // -1 means "no limit" for strcspn
3780 } elseif ( $len < 0 ) {
3784 if ( $start < strlen( $text ) ) {
3785 $skipCount = strcspn( $text, $search, $start, $len );
3786 $ret .= substr( $text, $start, $skipCount );
3792 * truncateHtml() helper function
3793 * (a) push or pop $tag from $openTags as needed
3794 * (b) clear $tag value
3795 * @param string &$tag Current HTML tag name we are looking at
3796 * @param int $tagType (0-open tag, 1-close tag)
3797 * @param string $lastCh Character before the '>' that ended this tag
3798 * @param array &$openTags Open tag stack (not accounting for $tag)
3800 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3801 $tag = ltrim( $tag );
3803 if ( $tagType == 0 && $lastCh != '/' ) {
3804 $openTags[] = $tag; // tag opened (didn't close itself)
3805 } elseif ( $tagType == 1 ) {
3806 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3807 array_pop( $openTags ); // tag closed
3815 * Grammatical transformations, needed for inflected languages
3816 * Invoked by putting {{grammar:case|word}} in a message
3818 * @param string $word
3819 * @param string $case
3822 function convertGrammar( $word, $case ) {
3823 global $wgGrammarForms;
3824 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3825 return $wgGrammarForms[$this->getCode()][$case][$word];
3831 * Get the grammar forms for the content language
3832 * @return array Array of grammar forms
3835 function getGrammarForms() {
3836 global $wgGrammarForms;
3837 if ( isset( $wgGrammarForms[$this->getCode()] )
3838 && is_array( $wgGrammarForms[$this->getCode()] )
3840 return $wgGrammarForms[$this->getCode()];
3846 * Provides an alternative text depending on specified gender.
3847 * Usage {{gender:username|masculine|feminine|unknown}}.
3848 * username is optional, in which case the gender of current user is used,
3849 * but only in (some) interface messages; otherwise default gender is used.
3851 * If no forms are given, an empty string is returned. If only one form is
3852 * given, it will be returned unconditionally. These details are implied by
3853 * the caller and cannot be overridden in subclasses.
3855 * If three forms are given, the default is to use the third (unknown) form.
3856 * If fewer than three forms are given, the default is to use the first (masculine) form.
3857 * These details can be overridden in subclasses.
3859 * @param string $gender
3860 * @param array $forms
3864 function gender( $gender, $forms ) {
3865 if ( !count( $forms ) ) {
3868 $forms = $this->preConvertPlural( $forms, 2 );
3869 if ( $gender === 'male' ) {
3872 if ( $gender === 'female' ) {
3875 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3879 * Plural form transformations, needed for some languages.
3880 * For example, there are 3 form of plural in Russian and Polish,
3881 * depending on "count mod 10". See [[w:Plural]]
3882 * For English it is pretty simple.
3884 * Invoked by putting {{plural:count|wordform1|wordform2}}
3885 * or {{plural:count|wordform1|wordform2|wordform3}}
3887 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3889 * @param int $count Non-localized number
3890 * @param array $forms Different plural forms
3891 * @return string Correct form of plural for $count in this language
3893 function convertPlural( $count, $forms ) {
3894 // Handle explicit n=pluralform cases
3895 $forms = $this->handleExplicitPluralForms( $count, $forms );
3896 if ( is_string( $forms ) ) {
3899 if ( !count( $forms ) ) {
3903 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3904 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3905 return $forms[$pluralForm];
3909 * Handles explicit plural forms for Language::convertPlural()
3911 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3912 * If an explicitly defined plural form matches the $count, then
3913 * string value returned, otherwise array returned for further consideration
3914 * by CLDR rules or overridden convertPlural().
3918 * @param int $count Non-localized number
3919 * @param array $forms Different plural forms
3921 * @return array|string
3923 protected function handleExplicitPluralForms( $count, array $forms ) {
3924 foreach ( $forms as $index => $form ) {
3925 if ( preg_match( '/\d+=/i', $form ) ) {
3926 $pos = strpos( $form, '=' );
3927 if ( substr( $form, 0, $pos ) === (string)$count ) {
3928 return substr( $form, $pos +
1 );
3930 unset( $forms[$index] );
3933 return array_values( $forms );
3937 * Checks that convertPlural was given an array and pads it to requested
3938 * amount of forms by copying the last one.
3940 * @param array $forms Array of forms given to convertPlural
3941 * @param int $count How many forms should there be at least
3942 * @return array Padded array of forms or an exception if not an array
3944 protected function preConvertPlural( /* Array */ $forms, $count ) {
3945 while ( count( $forms ) < $count ) {
3946 $forms[] = $forms[count( $forms ) - 1];
3952 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3953 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3954 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3955 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3958 * @param string $str The validated block duration in English
3959 * @return string Somehow translated block duration
3960 * @see LanguageFi.php for example implementation
3962 function translateBlockExpiry( $str ) {
3963 $duration = SpecialBlock
::getSuggestedDurations( $this );
3964 foreach ( $duration as $show => $value ) {
3965 if ( strcmp( $str, $value ) == 0 ) {
3966 return htmlspecialchars( trim( $show ) );
3970 if ( wfIsInfinity( $str ) ) {
3971 foreach ( $duration as $show => $value ) {
3972 if ( wfIsInfinity( $value ) ) {
3973 return htmlspecialchars( trim( $show ) );
3978 // If all else fails, return a standard duration or timestamp description.
3979 $time = strtotime( $str, 0 );
3980 if ( $time === false ) { // Unknown format. Return it as-is in case.
3982 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3983 // $time is relative to 0 so it's a duration length.
3984 return $this->formatDuration( $time );
3985 } else { // It's an absolute timestamp.
3986 if ( $time === 0 ) {
3987 // wfTimestamp() handles 0 as current time instead of epoch.
3988 return $this->timeanddate( '19700101000000' );
3990 return $this->timeanddate( $time );
3996 * languages like Chinese need to be segmented in order for the diff
3999 * @param string $text
4002 public function segmentForDiff( $text ) {
4007 * and unsegment to show the result
4009 * @param string $text
4012 public function unsegmentForDiff( $text ) {
4017 * Return the LanguageConverter used in the Language
4020 * @return LanguageConverter
4022 public function getConverter() {
4023 return $this->mConverter
;
4027 * convert text to all supported variants
4029 * @param string $text
4032 public function autoConvertToAllVariants( $text ) {
4033 return $this->mConverter
->autoConvertToAllVariants( $text );
4037 * convert text to different variants of a language.
4039 * @param string $text
4042 public function convert( $text ) {
4043 return $this->mConverter
->convert( $text );
4047 * Convert a Title object to a string in the preferred variant
4049 * @param Title $title
4052 public function convertTitle( $title ) {
4053 return $this->mConverter
->convertTitle( $title );
4057 * Convert a namespace index to a string in the preferred variant
4062 public function convertNamespace( $ns ) {
4063 return $this->mConverter
->convertNamespace( $ns );
4067 * Check if this is a language with variants
4071 public function hasVariants() {
4072 return count( $this->getVariants() ) > 1;
4076 * Check if the language has the specific variant
4079 * @param string $variant
4082 public function hasVariant( $variant ) {
4083 return (bool)$this->mConverter
->validateVariant( $variant );
4087 * Put custom tags (e.g. -{ }-) around math to prevent conversion
4089 * @param string $text
4091 * @deprecated since 1.22 is no longer used
4093 public function armourMath( $text ) {
4094 return $this->mConverter
->armourMath( $text );
4098 * Perform output conversion on a string, and encode for safe HTML output.
4099 * @param string $text Text to be converted
4100 * @param bool $isTitle Whether this conversion is for the article title
4102 * @todo this should get integrated somewhere sane
4104 public function convertHtml( $text, $isTitle = false ) {
4105 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4109 * @param string $key
4112 public function convertCategoryKey( $key ) {
4113 return $this->mConverter
->convertCategoryKey( $key );
4117 * Get the list of variants supported by this language
4118 * see sample implementation in LanguageZh.php
4120 * @return array An array of language codes
4122 public function getVariants() {
4123 return $this->mConverter
->getVariants();
4129 public function getPreferredVariant() {
4130 return $this->mConverter
->getPreferredVariant();
4136 public function getDefaultVariant() {
4137 return $this->mConverter
->getDefaultVariant();
4143 public function getURLVariant() {
4144 return $this->mConverter
->getURLVariant();
4148 * If a language supports multiple variants, it is
4149 * possible that non-existing link in one variant
4150 * actually exists in another variant. this function
4151 * tries to find it. See e.g. LanguageZh.php
4152 * The input parameters may be modified upon return
4154 * @param string &$link The name of the link
4155 * @param Title &$nt The title object of the link
4156 * @param bool $ignoreOtherCond To disable other conditions when
4157 * we need to transclude a template or update a category's link
4159 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4160 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4164 * returns language specific options used by User::getPageRenderHash()
4165 * for example, the preferred language variant
4169 function getExtraHashOptions() {
4170 return $this->mConverter
->getExtraHashOptions();
4174 * For languages that support multiple variants, the title of an
4175 * article may be displayed differently in different variants. this
4176 * function returns the apporiate title defined in the body of the article.
4180 public function getParsedTitle() {
4181 return $this->mConverter
->getParsedTitle();
4185 * Prepare external link text for conversion. When the text is
4186 * a URL, it shouldn't be converted, and it'll be wrapped in
4187 * the "raw" tag (-{R| }-) to prevent conversion.
4189 * This function is called "markNoConversion" for historical
4192 * @param string $text Text to be used for external link
4193 * @param bool $noParse Wrap it without confirming it's a real URL first
4194 * @return string The tagged text
4196 public function markNoConversion( $text, $noParse = false ) {
4197 // Excluding protocal-relative URLs may avoid many false positives.
4198 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4199 return $this->mConverter
->markNoConversion( $text );
4206 * A regular expression to match legal word-trailing characters
4207 * which should be merged onto a link of the form [[foo]]bar.
4211 public function linkTrail() {
4212 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4216 * A regular expression character set to match legal word-prefixing
4217 * characters which should be merged onto a link of the form foo[[bar]].
4221 public function linkPrefixCharset() {
4222 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4226 * @deprecated since 1.24, will be removed in 1.25
4229 function getLangObj() {
4230 wfDeprecated( __METHOD__
, '1.24' );
4235 * Get the "parent" language which has a converter to convert a "compatible" language
4236 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4238 * @return Language|null
4241 public function getParentLanguage() {
4242 if ( $this->mParentLanguage
!== false ) {
4243 return $this->mParentLanguage
;
4246 $pieces = explode( '-', $this->getCode() );
4248 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4249 $this->mParentLanguage
= null;
4252 $lang = Language
::factory( $code );
4253 if ( !$lang->hasVariant( $this->getCode() ) ) {
4254 $this->mParentLanguage
= null;
4258 $this->mParentLanguage
= $lang;
4263 * Get the RFC 3066 code for this language object
4265 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4266 * htmlspecialchars() or similar
4270 public function getCode() {
4271 return $this->mCode
;
4275 * Get the code in Bcp47 format which we can use
4276 * inside of html lang="" tags.
4278 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4279 * htmlspecialchars() or similar.
4284 public function getHtmlCode() {
4285 if ( is_null( $this->mHtmlCode
) ) {
4286 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4288 return $this->mHtmlCode
;
4292 * @param string $code
4294 public function setCode( $code ) {
4295 $this->mCode
= $code;
4296 // Ensure we don't leave incorrect cached data lying around
4297 $this->mHtmlCode
= null;
4298 $this->mParentLanguage
= false;
4302 * Get the name of a file for a certain language code
4303 * @param string $prefix Prepend this to the filename
4304 * @param string $code Language code
4305 * @param string $suffix Append this to the filename
4306 * @throws MWException
4307 * @return string $prefix . $mangledCode . $suffix
4309 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4310 if ( !self
::isValidBuiltInCode( $code ) ) {
4311 throw new MWException( "Invalid language code \"$code\"" );
4314 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4318 * Get the language code from a file name. Inverse of getFileName()
4319 * @param string $filename $prefix . $languageCode . $suffix
4320 * @param string $prefix Prefix before the language code
4321 * @param string $suffix Suffix after the language code
4322 * @return string Language code, or false if $prefix or $suffix isn't found
4324 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4326 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4327 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4328 if ( !count( $m ) ) {
4331 return str_replace( '_', '-', strtolower( $m[1] ) );
4335 * @param string $code
4338 public static function getMessagesFileName( $code ) {
4340 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4341 Hooks
::run( 'Language::getMessagesFileName', array( $code, &$file ) );
4346 * @param string $code
4350 public static function getJsonMessagesFileName( $code ) {
4353 if ( !self
::isValidBuiltInCode( $code ) ) {
4354 throw new MWException( "Invalid language code \"$code\"" );
4357 return "$IP/languages/i18n/$code.json";
4361 * @param string $code
4364 public static function getClassFileName( $code ) {
4366 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4370 * Get the first fallback for a given language.
4372 * @param string $code
4374 * @return bool|string
4376 public static function getFallbackFor( $code ) {
4377 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4380 $fallbacks = self
::getFallbacksFor( $code );
4381 $first = array_shift( $fallbacks );
4387 * Get the ordered list of fallback languages.
4390 * @param string $code Language code
4393 public static function getFallbacksFor( $code ) {
4394 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4397 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4398 $v = array_map( 'trim', explode( ',', $v ) );
4399 if ( $v[count( $v ) - 1] !== 'en' ) {
4407 * Get the ordered list of fallback languages, ending with the fallback
4408 * language chain for the site language.
4411 * @param string $code Language code
4412 * @return array Array( fallbacks, site fallbacks )
4414 public static function getFallbacksIncludingSiteLanguage( $code ) {
4415 global $wgLanguageCode;
4417 // Usually, we will only store a tiny number of fallback chains, so we
4418 // keep them in static memory.
4419 $cacheKey = "{$code}-{$wgLanguageCode}";
4421 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4422 $fallbacks = self
::getFallbacksFor( $code );
4424 // Append the site's fallback chain, including the site language itself
4425 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4426 array_unshift( $siteFallbacks, $wgLanguageCode );
4428 // Eliminate any languages already included in the chain
4429 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4431 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4433 return self
::$fallbackLanguageCache[$cacheKey];
4437 * Get all messages for a given language
4438 * WARNING: this may take a long time. If you just need all message *keys*
4439 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4441 * @param string $code
4445 public static function getMessagesFor( $code ) {
4446 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4450 * Get a message for a given language
4452 * @param string $key
4453 * @param string $code
4457 public static function getMessageFor( $key, $code ) {
4458 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4462 * Get all message keys for a given language. This is a faster alternative to
4463 * array_keys( Language::getMessagesFor( $code ) )
4466 * @param string $code Language code
4467 * @return array Array of message keys (strings)
4469 public static function getMessageKeysFor( $code ) {
4470 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4474 * @param string $talk
4477 function fixVariableInNamespace( $talk ) {
4478 if ( strpos( $talk, '$1' ) === false ) {
4482 global $wgMetaNamespace;
4483 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4485 # Allow grammar transformations
4486 # Allowing full message-style parsing would make simple requests
4487 # such as action=raw much more expensive than they need to be.
4488 # This will hopefully cover most cases.
4489 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4490 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4491 return str_replace( ' ', '_', $talk );
4498 function replaceGrammarInNamespace( $m ) {
4499 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4503 * @throws MWException
4506 static function getCaseMaps() {
4507 static $wikiUpperChars, $wikiLowerChars;
4508 if ( isset( $wikiUpperChars ) ) {
4509 return array( $wikiUpperChars, $wikiLowerChars );
4512 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4513 if ( $arr === false ) {
4514 throw new MWException(
4515 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4517 $wikiUpperChars = $arr['wikiUpperChars'];
4518 $wikiLowerChars = $arr['wikiLowerChars'];
4519 return array( $wikiUpperChars, $wikiLowerChars );
4523 * Decode an expiry (block, protection, etc) which has come from the DB
4525 * @param string $expiry Database expiry String
4526 * @param bool|int $format True to process using language functions, or TS_ constant
4527 * to return the expiry in a given timestamp
4528 * @param string $inifinity If $format is not true, use this string for infinite expiry
4532 public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4534 if ( $dbInfinity === null ) {
4535 $dbInfinity = wfGetDB( DB_SLAVE
)->getInfinity();
4538 if ( $expiry == '' ||
$expiry === 'infinity' ||
$expiry == $dbInfinity ) {
4539 return $format === true
4540 ?
$this->getMessageFromDB( 'infiniteblock' )
4543 return $format === true
4544 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4545 : wfTimestamp( $format, $expiry );
4551 * @param int|float $seconds
4552 * @param array $format Optional
4553 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4554 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4555 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4557 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4558 * or 'avoidminutes'.
4561 function formatTimePeriod( $seconds, $format = array() ) {
4562 if ( !is_array( $format ) ) {
4563 $format = array( 'avoid' => $format ); // For backwards compatibility
4565 if ( !isset( $format['avoid'] ) ) {
4566 $format['avoid'] = false;
4568 if ( !isset( $format['noabbrevs'] ) ) {
4569 $format['noabbrevs'] = false;
4571 $secondsMsg = wfMessage(
4572 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4573 $minutesMsg = wfMessage(
4574 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4575 $hoursMsg = wfMessage(
4576 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4577 $daysMsg = wfMessage(
4578 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4580 if ( round( $seconds * 10 ) < 100 ) {
4581 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4582 $s = $secondsMsg->params( $s )->text();
4583 } elseif ( round( $seconds ) < 60 ) {
4584 $s = $this->formatNum( round( $seconds ) );
4585 $s = $secondsMsg->params( $s )->text();
4586 } elseif ( round( $seconds ) < 3600 ) {
4587 $minutes = floor( $seconds / 60 );
4588 $secondsPart = round( fmod( $seconds, 60 ) );
4589 if ( $secondsPart == 60 ) {
4593 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4595 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4596 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4597 $hours = floor( $seconds / 3600 );
4598 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4599 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4600 if ( $secondsPart == 60 ) {
4604 if ( $minutes == 60 ) {
4608 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4610 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4611 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4612 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4615 $days = floor( $seconds / 86400 );
4616 if ( $format['avoid'] === 'avoidminutes' ) {
4617 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4618 if ( $hours == 24 ) {
4622 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4624 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4625 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4626 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4627 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4628 if ( $minutes == 60 ) {
4632 if ( $hours == 24 ) {
4636 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4638 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4640 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4642 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4644 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4651 * Format a bitrate for output, using an appropriate
4652 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4653 * the magnitude in question.
4655 * This use base 1000. For base 1024 use formatSize(), for another base
4656 * see formatComputingNumbers().
4661 function formatBitrate( $bps ) {
4662 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4666 * @param int $size Size of the unit
4667 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4668 * @param string $messageKey Message key to be uesd
4671 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4673 return str_replace( '$1', $this->formatNum( $size ),
4674 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4677 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4680 $maxIndex = count( $sizes ) - 1;
4681 while ( $size >= $boundary && $index < $maxIndex ) {
4686 // For small sizes no decimal places necessary
4689 // For MB and bigger two decimal places are smarter
4692 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4694 $size = round( $size, $round );
4695 $text = $this->getMessageFromDB( $msg );
4696 return str_replace( '$1', $this->formatNum( $size ), $text );
4700 * Format a size in bytes for output, using an appropriate
4701 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4703 * This method use base 1024. For base 1000 use formatBitrate(), for
4704 * another base see formatComputingNumbers()
4706 * @param int $size Size to format
4707 * @return string Plain text (not HTML)
4709 function formatSize( $size ) {
4710 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4714 * Make a list item, used by various special pages
4716 * @param string $page Page link
4717 * @param string $details HTML safe text between brackets
4718 * @param bool $oppositedm Add the direction mark opposite to your
4719 * language, to display text properly
4720 * @return HTML escaped string
4722 function specialList( $page, $details, $oppositedm = true ) {
4727 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) . $this->getDirMark();
4731 $this->msg( 'word-separator' )->escaped() .
4732 $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4736 * Generate (prev x| next x) (20|50|100...) type links for paging
4738 * @param Title $title Title object to link
4739 * @param int $offset
4741 * @param array $query Optional URL query parameter string
4742 * @param bool $atend Optional param for specified if this is the last page
4745 public function viewPrevNext( Title
$title, $offset, $limit,
4746 array $query = array(), $atend = false
4748 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4750 # Make 'previous' link
4751 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4752 if ( $offset > 0 ) {
4753 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4754 $query, $prev, 'prevn-title', 'mw-prevlink' );
4756 $plink = htmlspecialchars( $prev );
4760 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4762 $nlink = htmlspecialchars( $next );
4764 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4765 $query, $next, 'nextn-title', 'mw-nextlink' );
4768 # Make links to set number of items per page
4769 $numLinks = array();
4770 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4771 $numLinks[] = $this->numLink( $title, $offset, $num,
4772 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4775 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4776 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4780 * Helper function for viewPrevNext() that generates links
4782 * @param Title $title Title object to link
4783 * @param int $offset
4785 * @param array $query Extra query parameters
4786 * @param string $link Text to use for the link; will be escaped
4787 * @param string $tooltipMsg Name of the message to use as tooltip
4788 * @param string $class Value of the "class" attribute of the link
4789 * @return string HTML fragment
4791 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4794 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4795 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4796 ->numParams( $limit )->text();
4798 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4799 'title' => $tooltip, 'class' => $class ), $link );
4803 * Get the conversion rule title, if any.
4807 public function getConvRuleTitle() {
4808 return $this->mConverter
->getConvRuleTitle();
4812 * Get the compiled plural rules for the language
4814 * @return array Associative array with plural form, and plural rule as key-value pairs
4816 public function getCompiledPluralRules() {
4817 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4818 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4819 if ( !$pluralRules ) {
4820 foreach ( $fallbacks as $fallbackCode ) {
4821 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4822 if ( $pluralRules ) {
4827 return $pluralRules;
4831 * Get the plural rules for the language
4833 * @return array Associative array with plural form number and plural rule as key-value pairs
4835 public function getPluralRules() {
4836 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4837 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4838 if ( !$pluralRules ) {
4839 foreach ( $fallbacks as $fallbackCode ) {
4840 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4841 if ( $pluralRules ) {
4846 return $pluralRules;
4850 * Get the plural rule types for the language
4852 * @return array Associative array with plural form number and plural rule type as key-value pairs
4854 public function getPluralRuleTypes() {
4855 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4856 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4857 if ( !$pluralRuleTypes ) {
4858 foreach ( $fallbacks as $fallbackCode ) {
4859 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4860 if ( $pluralRuleTypes ) {
4865 return $pluralRuleTypes;
4869 * Find the index number of the plural rule appropriate for the given number
4870 * @param int $number
4871 * @return int The index number of the plural rule
4873 public function getPluralRuleIndexNumber( $number ) {
4874 $pluralRules = $this->getCompiledPluralRules();
4875 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4880 * Find the plural rule type appropriate for the given number
4881 * For example, if the language is set to Arabic, getPluralType(5) should
4884 * @param int $number
4885 * @return string The name of the plural rule type, e.g. one, two, few, many
4887 public function getPluralRuleType( $number ) {
4888 $index = $this->getPluralRuleIndexNumber( $number );
4889 $pluralRuleTypes = $this->getPluralRuleTypes();
4890 if ( isset( $pluralRuleTypes[$index] ) ) {
4891 return $pluralRuleTypes[$index];