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 * Get a cached or new language object for a given language code
148 * @param string $code
151 static function factory( $code ) {
152 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
154 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
155 $code = $wgDummyLanguageCodes[$code];
158 // get the language object to process
159 $langObj = isset( self
::$mLangObjCache[$code] )
160 ? self
::$mLangObjCache[$code]
161 : self
::newFromCode( $code );
163 // merge the language object in to get it up front in the cache
164 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
165 // get rid of the oldest ones in case we have an overflow
166 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
172 * Create a language object for a given language code
173 * @param string $code
174 * @throws MWException
177 protected static function newFromCode( $code ) {
178 // Protect against path traversal below
179 if ( !Language
::isValidCode( $code )
180 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code )
182 throw new MWException( "Invalid language code \"$code\"" );
185 if ( !Language
::isValidBuiltInCode( $code ) ) {
186 // It's not possible to customise this code with class files, so
187 // just return a Language object. This is to support uselang= hacks.
188 $lang = new Language
;
189 $lang->setCode( $code );
193 // Check if there is a language class for the code
194 $class = self
::classFromCode( $code );
195 self
::preloadLanguageClass( $class );
196 if ( class_exists( $class ) ) {
201 // Keep trying the fallback list until we find an existing class
202 $fallbacks = Language
::getFallbacksFor( $code );
203 foreach ( $fallbacks as $fallbackCode ) {
204 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
205 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
208 $class = self
::classFromCode( $fallbackCode );
209 self
::preloadLanguageClass( $class );
210 if ( class_exists( $class ) ) {
211 $lang = Language
::newFromCode( $fallbackCode );
212 $lang->setCode( $code );
217 throw new MWException( "Invalid fallback sequence for language '$code'" );
221 * Checks whether any localisation is available for that language tag
222 * in MediaWiki (MessagesXx.php exists).
224 * @param string $code Language tag (in lower case)
225 * @return bool Whether language is supported
228 public static function isSupportedLanguage( $code ) {
229 return self
::isValidBuiltInCode( $code )
230 && ( is_readable( self
::getMessagesFileName( $code ) )
231 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
236 * Returns true if a language code string is a well-formed language tag
237 * according to RFC 5646.
238 * This function only checks well-formedness; it doesn't check that
239 * language, script or variant codes actually exist in the repositories.
241 * Based on regexes by Mark Davis of the Unicode Consortium:
242 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
244 * @param string $code
245 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
250 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
253 $alphanum = '[a-z0-9]';
254 $x = 'x'; # private use singleton
255 $singleton = '[a-wy-z]'; # other singleton
256 $s = $lenient ?
'[-_]' : '-';
258 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
259 $script = "$alpha{4}"; # ISO 15924
260 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
261 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
262 $extension = "$singleton(?:$s$alphanum{2,8})+";
263 $privateUse = "$x(?:$s$alphanum{1,8})+";
265 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
266 # Since these are limited, this is safe even later changes to the registry --
267 # the only oddity is that it might change the type of the tag, and thus
268 # the results from the capturing groups.
269 # http://www.iana.org/assignments/language-subtag-registry
271 $grandfathered = "en{$s}GB{$s}oed"
272 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
273 . "|no{$s}(?:bok|nyn)"
274 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
275 . "|zh{$s}min{$s}nan";
277 $variantList = "$variant(?:$s$variant)*";
278 $extensionList = "$extension(?:$s$extension)*";
280 $langtag = "(?:($language)"
283 . "(?:$s$variantList)?"
284 . "(?:$s$extensionList)?"
285 . "(?:$s$privateUse)?)";
287 # The final breakdown, with capturing groups for each of these components
288 # The variants, extensions, grandfathered, and private-use may have interior '-'
290 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
292 return (bool)preg_match( "/$root/", strtolower( $code ) );
296 * Returns true if a language code string is of a valid form, whether or
297 * not it exists. This includes codes which are used solely for
298 * customisation via the MediaWiki namespace.
300 * @param string $code
304 public static function isValidCode( $code ) {
305 static $cache = array();
306 if ( isset( $cache[$code] ) ) {
307 return $cache[$code];
309 // People think language codes are html safe, so enforce it.
310 // Ideally we should only allow a-zA-Z0-9-
311 // but, .+ and other chars are often used for {{int:}} hacks
312 // see bugs 37564, 37587, 36938
314 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
315 && !preg_match( Title
::getTitleInvalidRegex(), $code );
317 return $cache[$code];
321 * Returns true if a language code is of a valid form for the purposes of
322 * internal customisation of MediaWiki, via Messages*.php or *.json.
324 * @param string $code
326 * @throws MWException
330 public static function isValidBuiltInCode( $code ) {
332 if ( !is_string( $code ) ) {
333 if ( is_object( $code ) ) {
334 $addmsg = " of class " . get_class( $code );
338 $type = gettype( $code );
339 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
342 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
346 * Returns true if a language code is an IETF tag known to MediaWiki.
353 public static function isKnownLanguageTag( $tag ) {
354 static $coreLanguageNames;
356 // Quick escape for invalid input to avoid exceptions down the line
357 // when code tries to process tags which are not valid at all.
358 if ( !self
::isValidBuiltInCode( $tag ) ) {
362 if ( $coreLanguageNames === null ) {
364 include "$IP/languages/Names.php";
367 if ( isset( $coreLanguageNames[$tag] )
368 || self
::fetchLanguageName( $tag, $tag ) !== ''
377 * @param string $code
378 * @return string Name of the language class
380 public static function classFromCode( $code ) {
381 if ( $code == 'en' ) {
384 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
389 * Includes language class files
391 * @param string $class Name of the language class
393 public static function preloadLanguageClass( $class ) {
396 if ( $class === 'Language' ) {
400 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
401 include_once "$IP/languages/classes/$class.php";
406 * Get the LocalisationCache instance
408 * @return LocalisationCache
410 public static function getLocalisationCache() {
411 if ( is_null( self
::$dataCache ) ) {
412 global $wgLocalisationCacheConf;
413 $class = $wgLocalisationCacheConf['class'];
414 self
::$dataCache = new $class( $wgLocalisationCacheConf );
416 return self
::$dataCache;
419 function __construct() {
420 $this->mConverter
= new FakeConverter( $this );
421 // Set the code to the name of the descendant
422 if ( get_class( $this ) == 'Language' ) {
425 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
427 self
::getLocalisationCache();
431 * Reduce memory usage
433 function __destruct() {
434 foreach ( $this as $name => $value ) {
435 unset( $this->$name );
440 * Hook which will be called if this is the content language.
441 * Descendants can use this to register hook functions or modify globals
443 function initContLang() {
450 function getFallbackLanguages() {
451 return self
::getFallbacksFor( $this->mCode
);
455 * Exports $wgBookstoreListEn
458 function getBookstoreList() {
459 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
463 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
464 * available in localised form, it will be included in English.
468 public function getNamespaces() {
469 if ( is_null( $this->namespaceNames
) ) {
470 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
472 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
473 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
475 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
477 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
478 if ( $wgMetaNamespaceTalk ) {
479 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
481 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
482 $this->namespaceNames
[NS_PROJECT_TALK
] =
483 $this->fixVariableInNamespace( $talk );
486 # Sometimes a language will be localised but not actually exist on this wiki.
487 foreach ( $this->namespaceNames
as $key => $text ) {
488 if ( !isset( $validNamespaces[$key] ) ) {
489 unset( $this->namespaceNames
[$key] );
493 # The above mixing may leave namespaces out of canonical order.
494 # Re-order by namespace ID number...
495 ksort( $this->namespaceNames
);
497 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
500 return $this->namespaceNames
;
504 * Arbitrarily set all of the namespace names at once. Mainly used for testing
505 * @param array $namespaces Array of namespaces (id => name)
507 public function setNamespaces( array $namespaces ) {
508 $this->namespaceNames
= $namespaces;
509 $this->mNamespaceIds
= null;
513 * Resets all of the namespace caches. Mainly used for testing
515 public function resetNamespaces() {
516 $this->namespaceNames
= null;
517 $this->mNamespaceIds
= null;
518 $this->namespaceAliases
= null;
522 * A convenience function that returns the same thing as
523 * getNamespaces() except with the array values changed to ' '
524 * where it found '_', useful for producing output to be displayed
525 * e.g. in <select> forms.
529 function getFormattedNamespaces() {
530 $ns = $this->getNamespaces();
531 foreach ( $ns as $k => $v ) {
532 $ns[$k] = strtr( $v, '_', ' ' );
538 * Get a namespace value by key
540 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
541 * echo $mw_ns; // prints 'MediaWiki'
544 * @param int $index The array key of the namespace to return
545 * @return string|bool String if the namespace value exists, otherwise false
547 function getNsText( $index ) {
548 $ns = $this->getNamespaces();
550 return isset( $ns[$index] ) ?
$ns[$index] : false;
554 * A convenience function that returns the same thing as
555 * getNsText() except with '_' changed to ' ', useful for
559 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
560 * echo $mw_ns; // prints 'MediaWiki talk'
563 * @param int $index The array key of the namespace to return
564 * @return string Namespace name without underscores (empty string if namespace does not exist)
566 function getFormattedNsText( $index ) {
567 $ns = $this->getNsText( $index );
569 return strtr( $ns, '_', ' ' );
573 * Returns gender-dependent namespace alias if available.
574 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
575 * @param int $index Namespace index
576 * @param string $gender Gender key (male, female... )
580 function getGenderNsText( $index, $gender ) {
581 global $wgExtraGenderNamespaces;
583 $ns = $wgExtraGenderNamespaces +
584 self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
586 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
590 * Whether this language uses gender-dependent namespace aliases.
591 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
595 function needsGenderDistinction() {
596 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
597 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
598 // $wgExtraGenderNamespaces overrides everything
600 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
601 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
602 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
605 // Check what is in i18n files
606 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
607 return count( $aliases ) > 0;
612 * Get a namespace key by value, case insensitive.
613 * Only matches namespace names for the current language, not the
614 * canonical ones defined in Namespace.php.
616 * @param string $text
617 * @return int|bool An integer if $text is a valid value otherwise false
619 function getLocalNsIndex( $text ) {
620 $lctext = $this->lc( $text );
621 $ids = $this->getNamespaceIds();
622 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
628 function getNamespaceAliases() {
629 if ( is_null( $this->namespaceAliases
) ) {
630 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
634 foreach ( $aliases as $name => $index ) {
635 if ( $index === NS_PROJECT_TALK
) {
636 unset( $aliases[$name] );
637 $name = $this->fixVariableInNamespace( $name );
638 $aliases[$name] = $index;
643 global $wgExtraGenderNamespaces;
644 $genders = $wgExtraGenderNamespaces +
645 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
646 foreach ( $genders as $index => $forms ) {
647 foreach ( $forms as $alias ) {
648 $aliases[$alias] = $index;
652 # Also add converted namespace names as aliases, to avoid confusion.
653 $convertedNames = array();
654 foreach ( $this->getVariants() as $variant ) {
655 if ( $variant === $this->mCode
) {
658 foreach ( $this->getNamespaces() as $ns => $_ ) {
659 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
663 $this->namespaceAliases
= $aliases +
$convertedNames;
666 return $this->namespaceAliases
;
672 function getNamespaceIds() {
673 if ( is_null( $this->mNamespaceIds
) ) {
674 global $wgNamespaceAliases;
675 # Put namespace names and aliases into a hashtable.
676 # If this is too slow, then we should arrange it so that it is done
677 # before caching. The catch is that at pre-cache time, the above
678 # class-specific fixup hasn't been done.
679 $this->mNamespaceIds
= array();
680 foreach ( $this->getNamespaces() as $index => $name ) {
681 $this->mNamespaceIds
[$this->lc( $name )] = $index;
683 foreach ( $this->getNamespaceAliases() as $name => $index ) {
684 $this->mNamespaceIds
[$this->lc( $name )] = $index;
686 if ( $wgNamespaceAliases ) {
687 foreach ( $wgNamespaceAliases as $name => $index ) {
688 $this->mNamespaceIds
[$this->lc( $name )] = $index;
692 return $this->mNamespaceIds
;
696 * Get a namespace key by value, case insensitive. Canonical namespace
697 * names override custom ones defined for the current language.
699 * @param string $text
700 * @return int|bool An integer if $text is a valid value otherwise false
702 function getNsIndex( $text ) {
703 $lctext = $this->lc( $text );
704 $ns = MWNamespace
::getCanonicalIndex( $lctext );
705 if ( $ns !== null ) {
708 $ids = $this->getNamespaceIds();
709 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
713 * short names for language variants used for language conversion links.
715 * @param string $code
716 * @param bool $usemsg Use the "variantname-xyz" message if it exists
719 function getVariantname( $code, $usemsg = true ) {
720 $msg = "variantname-$code";
721 if ( $usemsg && wfMessage( $msg )->exists() ) {
722 return $this->getMessageFromDB( $msg );
724 $name = self
::fetchLanguageName( $code );
726 return $name; # if it's defined as a language name, show that
728 # otherwise, output the language code
734 * @param string $name
737 function specialPage( $name ) {
738 $aliases = $this->getSpecialPageAliases();
739 if ( isset( $aliases[$name][0] ) ) {
740 $name = $aliases[$name][0];
742 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
748 function getDatePreferences() {
749 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
755 function getDateFormats() {
756 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
760 * @return array|string
762 function getDefaultDateFormat() {
763 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
764 if ( $df === 'dmy or mdy' ) {
765 global $wgAmericanDates;
766 return $wgAmericanDates ?
'mdy' : 'dmy';
775 function getDatePreferenceMigrationMap() {
776 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
780 * @param string $image
783 function getImageFile( $image ) {
784 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
791 function getImageFiles() {
792 return self
::$dataCache->getItem( $this->mCode
, 'imageFiles' );
798 function getExtraUserToggles() {
799 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
806 function getUserToggle( $tog ) {
807 return $this->getMessageFromDB( "tog-$tog" );
811 * Get native language names, indexed by code.
812 * Only those defined in MediaWiki, no other data like CLDR.
813 * If $customisedOnly is true, only returns codes with a messages file
815 * @param bool $customisedOnly
818 * @deprecated since 1.20, use fetchLanguageNames()
820 public static function getLanguageNames( $customisedOnly = false ) {
821 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
825 * Get translated language names. This is done on best effort and
826 * by default this is exactly the same as Language::getLanguageNames.
827 * The CLDR extension provides translated names.
828 * @param string $code Language code.
829 * @return array Language code => language name
831 * @deprecated since 1.20, use fetchLanguageNames()
833 public static function getTranslatedLanguageNames( $code ) {
834 return self
::fetchLanguageNames( $code, 'all' );
838 * Get an array of language names, indexed by code.
839 * @param null|string $inLanguage Code of language in which to return the names
840 * Use null for autonyms (native names)
841 * @param string $include One of:
842 * 'all' all available languages
843 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
844 * 'mwfile' only if the language is in 'mw' *and* has a message file
845 * @return array Language code => language name
848 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
849 global $wgExtraLanguageNames;
850 static $coreLanguageNames;
852 wfProfileIn( __METHOD__
);
854 if ( $coreLanguageNames === null ) {
856 include "$IP/languages/Names.php";
859 // If passed an invalid language code to use, fallback to en
860 if ( $inLanguage !== null && !Language
::isValidCode( $inLanguage ) ) {
867 # TODO: also include when $inLanguage is null, when this code is more efficient
868 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
871 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
872 foreach ( $mwNames as $mwCode => $mwName ) {
873 # - Prefer own MediaWiki native name when not using the hook
874 # - For other names just add if not added through the hook
875 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
876 $names[$mwCode] = $mwName;
880 if ( $include === 'all' ) {
881 wfProfileOut( __METHOD__
);
886 $coreCodes = array_keys( $mwNames );
887 foreach ( $coreCodes as $coreCode ) {
888 $returnMw[$coreCode] = $names[$coreCode];
891 if ( $include === 'mwfile' ) {
892 $namesMwFile = array();
893 # We do this using a foreach over the codes instead of a directory
894 # loop so that messages files in extensions will work correctly.
895 foreach ( $returnMw as $code => $value ) {
896 if ( is_readable( self
::getMessagesFileName( $code ) )
897 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
899 $namesMwFile[$code] = $names[$code];
903 wfProfileOut( __METHOD__
);
907 # 'mw' option; default if it's not one of the other two options (all/mwfile)
908 wfProfileOut( __METHOD__
);
913 * @param string $code The code of the language for which to get the name
914 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
915 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
916 * @return string Language name or empty
919 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
920 $code = strtolower( $code );
921 $array = self
::fetchLanguageNames( $inLanguage, $include );
922 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
926 * Get a message from the MediaWiki namespace.
928 * @param string $msg Message name
931 function getMessageFromDB( $msg ) {
932 return wfMessage( $msg )->inLanguage( $this )->text();
936 * Get the native language name of $code.
937 * Only if defined in MediaWiki, no other data like CLDR.
938 * @param string $code
940 * @deprecated since 1.20, use fetchLanguageName()
942 function getLanguageName( $code ) {
943 return self
::fetchLanguageName( $code );
950 function getMonthName( $key ) {
951 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
957 function getMonthNamesArray() {
958 $monthNames = array( '' );
959 for ( $i = 1; $i < 13; $i++
) {
960 $monthNames[] = $this->getMonthName( $i );
969 function getMonthNameGen( $key ) {
970 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
977 function getMonthAbbreviation( $key ) {
978 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
984 function getMonthAbbreviationsArray() {
985 $monthNames = array( '' );
986 for ( $i = 1; $i < 13; $i++
) {
987 $monthNames[] = $this->getMonthAbbreviation( $i );
996 function getWeekdayName( $key ) {
997 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1001 * @param string $key
1004 function getWeekdayAbbreviation( $key ) {
1005 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1009 * @param string $key
1012 function getIranianCalendarMonthName( $key ) {
1013 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1017 * @param string $key
1020 function getHebrewCalendarMonthName( $key ) {
1021 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1025 * @param string $key
1028 function getHebrewCalendarMonthNameGen( $key ) {
1029 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1033 * @param string $key
1036 function getHijriCalendarMonthName( $key ) {
1037 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1041 * Pass through result from $dateTimeObj->format()
1042 * @param DateTime|bool|null &$dateTimeObj
1044 * @param DateTimeZone|bool|null $zone
1045 * @param string $code
1048 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1049 if ( !$dateTimeObj ) {
1050 $dateTimeObj = DateTime
::createFromFormat(
1051 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1054 return $dateTimeObj->format( $code );
1058 * This is a workalike of PHP's date() function, but with better
1059 * internationalisation, a reduced set of format characters, and a better
1062 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1063 * the PHP manual for definitions. There are a number of extensions, which
1066 * xn Do not translate digits of the next numeric format character
1067 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1068 * xr Use roman numerals for the next numeric format character
1069 * xh Use hebrew numerals for the next numeric format character
1071 * xg Genitive month name
1073 * xij j (day number) in Iranian calendar
1074 * xiF F (month name) in Iranian calendar
1075 * xin n (month number) in Iranian calendar
1076 * xiy y (two digit year) in Iranian calendar
1077 * xiY Y (full year) in Iranian calendar
1079 * xjj j (day number) in Hebrew calendar
1080 * xjF F (month name) in Hebrew calendar
1081 * xjt t (days in month) in Hebrew calendar
1082 * xjx xg (genitive month name) in Hebrew calendar
1083 * xjn n (month number) in Hebrew calendar
1084 * xjY Y (full year) in Hebrew calendar
1086 * xmj j (day number) in Hijri calendar
1087 * xmF F (month name) in Hijri calendar
1088 * xmn n (month number) in Hijri calendar
1089 * xmY Y (full year) in Hijri calendar
1091 * xkY Y (full year) in Thai solar calendar. Months and days are
1092 * identical to the Gregorian calendar
1093 * xoY Y (full year) in Minguo calendar or Juche year.
1094 * Months and days are identical to the
1095 * Gregorian calendar
1096 * xtY Y (full year) in Japanese nengo. Months and days are
1097 * identical to the Gregorian calendar
1099 * Characters enclosed in double quotes will be considered literal (with
1100 * the quotes themselves removed). Unmatched quotes will be considered
1101 * literal quotes. Example:
1103 * "The month is" F => The month is January
1106 * Backslash escaping is also supported.
1108 * Input timestamp is assumed to be pre-normalized to the desired local
1109 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1110 * $ts is UTC if $zone is not given.
1112 * @param string $format
1113 * @param string $ts 14-character timestamp
1116 * @param DateTimeZone $zone Timezone of $ts
1117 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1118 * Only makes sense if $ts is the current time.
1119 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1121 * @throws MWException
1124 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1129 $dateTimeObj = false;
1138 $usedSecond = false;
1139 $usedMinute = false;
1146 $usedISOYear = false;
1147 $usedIsLeapYear = false;
1149 $usedHebrewMonth = false;
1150 $usedIranianMonth = false;
1151 $usedHijriMonth = false;
1152 $usedHebrewYear = false;
1153 $usedIranianYear = false;
1154 $usedHijriYear = false;
1155 $usedTennoYear = false;
1157 if ( strlen( $ts ) !== 14 ) {
1158 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1161 if ( !ctype_digit( $ts ) ) {
1162 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1165 $formatLength = strlen( $format );
1166 for ( $p = 0; $p < $formatLength; $p++
) {
1168 $code = $format[$p];
1169 if ( $code == 'x' && $p < $formatLength - 1 ) {
1170 $code .= $format[++
$p];
1173 if ( ( $code === 'xi'
1179 && $p < $formatLength - 1 ) {
1180 $code .= $format[++
$p];
1191 $rawToggle = !$rawToggle;
1201 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1204 $usedHebrewMonth = true;
1206 $hebrew = self
::tsToHebrew( $ts );
1208 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1212 $num = substr( $ts, 6, 2 );
1216 $s .= $this->getWeekdayAbbreviation( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1220 $num = intval( substr( $ts, 6, 2 ) );
1225 $iranian = self
::tsToIranian( $ts );
1232 $hijri = self
::tsToHijri( $ts );
1239 $hebrew = self
::tsToHebrew( $ts );
1245 $s .= $this->getWeekdayName( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1249 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1252 $usedIranianMonth = true;
1254 $iranian = self
::tsToIranian( $ts );
1256 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1259 $usedHijriMonth = true;
1261 $hijri = self
::tsToHijri( $ts );
1263 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1266 $usedHebrewMonth = true;
1268 $hebrew = self
::tsToHebrew( $ts );
1270 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1274 $num = substr( $ts, 4, 2 );
1278 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1282 $num = intval( substr( $ts, 4, 2 ) );
1285 $usedIranianMonth = true;
1287 $iranian = self
::tsToIranian( $ts );
1292 $usedHijriMonth = true;
1294 $hijri = self
::tsToHijri ( $ts );
1299 $usedHebrewMonth = true;
1301 $hebrew = self
::tsToHebrew( $ts );
1306 $usedHebrewMonth = true;
1308 $hebrew = self
::tsToHebrew( $ts );
1314 $num = substr( $ts, 0, 4 );
1317 $usedIranianYear = true;
1319 $iranian = self
::tsToIranian( $ts );
1324 $usedHijriYear = true;
1326 $hijri = self
::tsToHijri( $ts );
1331 $usedHebrewYear = true;
1333 $hebrew = self
::tsToHebrew( $ts );
1340 $thai = self
::tsToYear( $ts, 'thai' );
1347 $minguo = self
::tsToYear( $ts, 'minguo' );
1352 $usedTennoYear = true;
1354 $tenno = self
::tsToYear( $ts, 'tenno' );
1360 $num = substr( $ts, 2, 2 );
1363 $usedIranianYear = true;
1365 $iranian = self
::tsToIranian( $ts );
1367 $num = substr( $iranian[0], -2 );
1371 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1375 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1379 $h = substr( $ts, 8, 2 );
1380 $num = $h %
12 ?
$h %
12 : 12;
1384 $num = intval( substr( $ts, 8, 2 ) );
1388 $h = substr( $ts, 8, 2 );
1389 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1393 $num = substr( $ts, 8, 2 );
1397 $num = substr( $ts, 10, 2 );
1401 $num = substr( $ts, 12, 2 );
1411 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1417 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1421 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1425 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1428 $usedIsLeapYear = true;
1429 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1432 $usedISOYear = true;
1433 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1440 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1443 # Backslash escaping
1444 if ( $p < $formatLength - 1 ) {
1445 $s .= $format[++
$p];
1452 if ( $p < $formatLength - 1 ) {
1453 $endQuote = strpos( $format, '"', $p +
1 );
1454 if ( $endQuote === false ) {
1455 # No terminating quote, assume literal "
1458 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1462 # Quote at end of string, assume literal "
1469 if ( $num !== false ) {
1470 if ( $rawToggle ||
$raw ) {
1473 } elseif ( $roman ) {
1474 $s .= Language
::romanNumeral( $num );
1476 } elseif ( $hebrewNum ) {
1477 $s .= self
::hebrewNumeral( $num );
1480 $s .= $this->formatNum( $num, true );
1485 if ( $usedSecond ) {
1487 } elseif ( $usedMinute ) {
1488 $ttl = 60 - substr( $ts, 12, 2 );
1489 } elseif ( $usedHour ) {
1490 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1491 } elseif ( $usedAMPM ) {
1492 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1493 } elseif ( $usedDay ||
$usedHebrewMonth ||
$usedIranianMonth ||
$usedHijriMonth ||
$usedHebrewYear ||
$usedIranianYear ||
$usedHijriYear ||
$usedTennoYear ) {
1494 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1495 // so that they don't need purged every day.
1496 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1498 $possibleTtls = array();
1499 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1501 $possibleTtls[] = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1502 } elseif ( $usedISOYear ) {
1503 // December 28th falls on the last ISO week of the year, every year.
1504 // The last ISO week of a year can be 52 or 53.
1505 $lastWeekOfISOYear = DateTime
::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?
: new DateTimeZone( 'UTC' ) )->format( 'W' );
1506 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1507 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1508 $timeRemainingInWeek = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1509 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1513 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 +
$timeRemainingInDay;
1514 } elseif ( $usedYear ) {
1515 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1516 +
$timeRemainingInDay;
1517 } elseif ( $usedIsLeapYear ) {
1518 $year = substr( $ts, 0, 4 );
1519 $timeRemainingInYear = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1520 +
$timeRemainingInDay;
1522 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1523 // this isn't a leap year. see when the next one starts
1524 $nextCandidate = $year - $mod +
4;
1525 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1526 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
$timeRemainingInYear;
1528 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
$timeRemainingInYear;
1531 // this is a leap year, so the next year isn't
1532 $possibleTtls[] = $timeRemainingInYear;
1536 if ( $possibleTtls ) {
1537 $ttl = min( $possibleTtls );
1544 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1545 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1548 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1549 * Gregorian dates to Iranian dates. Originally written in C, it
1550 * is released under the terms of GNU Lesser General Public
1551 * License. Conversion to PHP was performed by Niklas Laxström.
1553 * Link: http://www.farsiweb.info/jalali/jalali.c
1559 private static function tsToIranian( $ts ) {
1560 $gy = substr( $ts, 0, 4 ) -1600;
1561 $gm = substr( $ts, 4, 2 ) -1;
1562 $gd = substr( $ts, 6, 2 ) -1;
1564 # Days passed from the beginning (including leap years)
1566 +
floor( ( $gy +
3 ) / 4 )
1567 - floor( ( $gy +
99 ) / 100 )
1568 +
floor( ( $gy +
399 ) / 400 );
1570 // Add days of the past months of this year
1571 for ( $i = 0; $i < $gm; $i++
) {
1572 $gDayNo +
= self
::$GREG_DAYS[$i];
1576 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1580 // Days passed in current month
1581 $gDayNo +
= (int)$gd;
1583 $jDayNo = $gDayNo - 79;
1585 $jNp = floor( $jDayNo / 12053 );
1588 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1591 if ( $jDayNo >= 366 ) {
1592 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1593 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1596 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1597 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1603 return array( $jy, $jm, $jd );
1607 * Converting Gregorian dates to Hijri dates.
1609 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1611 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1617 private static function tsToHijri( $ts ) {
1618 $year = substr( $ts, 0, 4 );
1619 $month = substr( $ts, 4, 2 );
1620 $day = substr( $ts, 6, 2 );
1628 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1629 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1631 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1632 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1633 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1636 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1637 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1640 $zl = $zjd -1948440 +
10632;
1641 $zn = (int)( ( $zl - 1 ) / 10631 );
1642 $zl = $zl - 10631 * $zn +
354;
1643 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1644 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1645 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1646 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1647 $zm = (int)( ( 24 * $zl ) / 709 );
1648 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1649 $zy = 30 * $zn +
$zj - 30;
1651 return array( $zy, $zm, $zd );
1655 * Converting Gregorian dates to Hebrew dates.
1657 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1658 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1659 * to translate the relevant functions into PHP and release them under
1662 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1663 * and Adar II is 14. In a non-leap year, Adar is 6.
1669 private static function tsToHebrew( $ts ) {
1671 $year = substr( $ts, 0, 4 );
1672 $month = substr( $ts, 4, 2 );
1673 $day = substr( $ts, 6, 2 );
1675 # Calculate Hebrew year
1676 $hebrewYear = $year +
3760;
1678 # Month number when September = 1, August = 12
1680 if ( $month > 12 ) {
1687 # Calculate day of year from 1 September
1689 for ( $i = 1; $i < $month; $i++
) {
1693 # Check if the year is leap
1694 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1697 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1704 # Calculate the start of the Hebrew year
1705 $start = self
::hebrewYearStart( $hebrewYear );
1707 # Calculate next year's start
1708 if ( $dayOfYear <= $start ) {
1709 # Day is before the start of the year - it is the previous year
1711 $nextStart = $start;
1715 # Add days since previous year's 1 September
1717 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1721 # Start of the new (previous) year
1722 $start = self
::hebrewYearStart( $hebrewYear );
1725 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1728 # Calculate Hebrew day of year
1729 $hebrewDayOfYear = $dayOfYear - $start;
1731 # Difference between year's days
1732 $diff = $nextStart - $start;
1733 # Add 12 (or 13 for leap years) days to ignore the difference between
1734 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1735 # difference is only about the year type
1736 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1742 # Check the year pattern, and is leap year
1743 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1744 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1745 # and non-leap years
1746 $yearPattern = $diff %
30;
1747 # Check if leap year
1748 $isLeap = $diff >= 30;
1750 # Calculate day in the month from number of day in the Hebrew year
1751 # Don't check Adar - if the day is not in Adar, we will stop before;
1752 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1753 $hebrewDay = $hebrewDayOfYear;
1756 while ( $hebrewMonth <= 12 ) {
1757 # Calculate days in this month
1758 if ( $isLeap && $hebrewMonth == 6 ) {
1759 # Adar in a leap year
1761 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1763 if ( $hebrewDay <= $days ) {
1767 # Subtract the days of Adar I
1768 $hebrewDay -= $days;
1771 if ( $hebrewDay <= $days ) {
1777 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1778 # Cheshvan in a complete year (otherwise as the rule below)
1780 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1781 # Kislev in an incomplete year (otherwise as the rule below)
1784 # Odd months have 30 days, even have 29
1785 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1787 if ( $hebrewDay <= $days ) {
1788 # In the current month
1791 # Subtract the days of the current month
1792 $hebrewDay -= $days;
1793 # Try in the next month
1798 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1802 * This calculates the Hebrew year start, as days since 1 September.
1803 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1804 * Used for Hebrew date.
1810 private static function hebrewYearStart( $year ) {
1811 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1812 $b = intval( ( $year - 1 ) %
4 );
1813 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1817 $Mar = intval( $m );
1823 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1824 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1826 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1828 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1832 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1837 * Algorithm to convert Gregorian dates to Thai solar dates,
1838 * Minguo dates or Minguo dates.
1840 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1841 * http://en.wikipedia.org/wiki/Minguo_calendar
1842 * http://en.wikipedia.org/wiki/Japanese_era_name
1844 * @param string $ts 14-character timestamp
1845 * @param string $cName Calender name
1846 * @return array Converted year, month, day
1848 private static function tsToYear( $ts, $cName ) {
1849 $gy = substr( $ts, 0, 4 );
1850 $gm = substr( $ts, 4, 2 );
1851 $gd = substr( $ts, 6, 2 );
1853 if ( !strcmp( $cName, 'thai' ) ) {
1855 # Add 543 years to the Gregorian calendar
1856 # Months and days are identical
1857 $gy_offset = $gy +
543;
1858 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1860 # Deduct 1911 years from the Gregorian calendar
1861 # Months and days are identical
1862 $gy_offset = $gy - 1911;
1863 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1864 # Nengō dates up to Meiji period
1865 # Deduct years from the Gregorian calendar
1866 # depending on the nengo periods
1867 # Months and days are identical
1869 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1870 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1873 $gy_gannen = $gy - 1868 +
1;
1874 $gy_offset = $gy_gannen;
1875 if ( $gy_gannen == 1 ) {
1878 $gy_offset = '明治' . $gy_offset;
1880 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1881 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1882 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1883 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1884 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1887 $gy_gannen = $gy - 1912 +
1;
1888 $gy_offset = $gy_gannen;
1889 if ( $gy_gannen == 1 ) {
1892 $gy_offset = '大正' . $gy_offset;
1894 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1895 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1896 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1899 $gy_gannen = $gy - 1926 +
1;
1900 $gy_offset = $gy_gannen;
1901 if ( $gy_gannen == 1 ) {
1904 $gy_offset = '昭和' . $gy_offset;
1907 $gy_gannen = $gy - 1989 +
1;
1908 $gy_offset = $gy_gannen;
1909 if ( $gy_gannen == 1 ) {
1912 $gy_offset = '平成' . $gy_offset;
1918 return array( $gy_offset, $gm, $gd );
1922 * Roman number formatting up to 10000
1928 static function romanNumeral( $num ) {
1929 static $table = array(
1930 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1931 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1932 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1933 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1934 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1937 $num = intval( $num );
1938 if ( $num > 10000 ||
$num <= 0 ) {
1943 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1944 if ( $num >= $pow10 ) {
1945 $s .= $table[$i][(int)floor( $num / $pow10 )];
1947 $num = $num %
$pow10;
1953 * Hebrew Gematria number formatting up to 9999
1959 static function hebrewNumeral( $num ) {
1960 static $table = array(
1961 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1962 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1963 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1964 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1967 $num = intval( $num );
1968 if ( $num > 9999 ||
$num <= 0 ) {
1973 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1974 if ( $num >= $pow10 ) {
1975 if ( $num == 15 ||
$num == 16 ) {
1976 $s .= $table[0][9] . $table[0][$num - 9];
1979 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1980 if ( $pow10 == 1000 ) {
1985 $num = $num %
$pow10;
1987 if ( strlen( $s ) == 2 ) {
1990 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1991 $str .= substr( $s, strlen( $s ) - 2, 2 );
1993 $start = substr( $str, 0, strlen( $str ) - 2 );
1994 $end = substr( $str, strlen( $str ) - 2 );
1997 $str = $start . 'ך';
2000 $str = $start . 'ם';
2003 $str = $start . 'ן';
2006 $str = $start . 'ף';
2009 $str = $start . 'ץ';
2016 * Used by date() and time() to adjust the time output.
2018 * @param string $ts The time in date('YmdHis') format
2019 * @param mixed $tz Adjust the time by this amount (default false, mean we
2020 * get user timecorrection setting)
2023 function userAdjust( $ts, $tz = false ) {
2024 global $wgUser, $wgLocalTZoffset;
2026 if ( $tz === false ) {
2027 $tz = $wgUser->getOption( 'timecorrection' );
2030 $data = explode( '|', $tz, 3 );
2032 if ( $data[0] == 'ZoneInfo' ) {
2033 wfSuppressWarnings();
2034 $userTZ = timezone_open( $data[2] );
2035 wfRestoreWarnings();
2036 if ( $userTZ !== false ) {
2037 $date = date_create( $ts, timezone_open( 'UTC' ) );
2038 date_timezone_set( $date, $userTZ );
2039 $date = date_format( $date, 'YmdHis' );
2042 # Unrecognized timezone, default to 'Offset' with the stored offset.
2043 $data[0] = 'Offset';
2046 if ( $data[0] == 'System' ||
$tz == '' ) {
2047 # Global offset in minutes.
2048 $minDiff = $wgLocalTZoffset;
2049 } elseif ( $data[0] == 'Offset' ) {
2050 $minDiff = intval( $data[1] );
2052 $data = explode( ':', $tz );
2053 if ( count( $data ) == 2 ) {
2054 $data[0] = intval( $data[0] );
2055 $data[1] = intval( $data[1] );
2056 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2057 if ( $data[0] < 0 ) {
2058 $minDiff = -$minDiff;
2061 $minDiff = intval( $data[0] ) * 60;
2065 # No difference ? Return time unchanged
2066 if ( 0 == $minDiff ) {
2070 wfSuppressWarnings(); // E_STRICT system time bitching
2071 # Generate an adjusted date; take advantage of the fact that mktime
2072 # will normalize out-of-range values so we don't have to split $minDiff
2073 # into hours and minutes.
2075 (int)substr( $ts, 8, 2 ) ), # Hours
2076 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2077 (int)substr( $ts, 12, 2 ), # Seconds
2078 (int)substr( $ts, 4, 2 ), # Month
2079 (int)substr( $ts, 6, 2 ), # Day
2080 (int)substr( $ts, 0, 4 ) ); # Year
2082 $date = date( 'YmdHis', $t );
2083 wfRestoreWarnings();
2089 * This is meant to be used by time(), date(), and timeanddate() to get
2090 * the date preference they're supposed to use, it should be used in
2094 * function timeanddate([...], $format = true) {
2095 * $datePreference = $this->dateFormat($format);
2100 * @param int|string|bool $usePrefs If true, the user's preference is used
2101 * if false, the site/language default is used
2102 * if int/string, assumed to be a format.
2105 function dateFormat( $usePrefs = true ) {
2108 if ( is_bool( $usePrefs ) ) {
2110 $datePreference = $wgUser->getDatePreference();
2112 $datePreference = (string)User
::getDefaultOption( 'date' );
2115 $datePreference = (string)$usePrefs;
2119 if ( $datePreference == '' ) {
2123 return $datePreference;
2127 * Get a format string for a given type and preference
2128 * @param string $type May be date, time or both
2129 * @param string $pref The format name as it appears in Messages*.php
2131 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2135 function getDateFormatString( $type, $pref ) {
2136 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2137 if ( $pref == 'default' ) {
2138 $pref = $this->getDefaultDateFormat();
2139 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2141 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2143 if ( $type === 'pretty' && $df === null ) {
2144 $df = $this->getDateFormatString( 'date', $pref );
2147 if ( $df === null ) {
2148 $pref = $this->getDefaultDateFormat();
2149 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2152 $this->dateFormatStrings
[$type][$pref] = $df;
2154 return $this->dateFormatStrings
[$type][$pref];
2158 * @param string $ts The time format which needs to be turned into a
2159 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2160 * @param bool $adj Whether to adjust the time output according to the
2161 * user configured offset ($timecorrection)
2162 * @param mixed $format True to use user's date format preference
2163 * @param string|bool $timecorrection The time offset as returned by
2164 * validateTimeZone() in Special:Preferences
2167 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2168 $ts = wfTimestamp( TS_MW
, $ts );
2170 $ts = $this->userAdjust( $ts, $timecorrection );
2172 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2173 return $this->sprintfDate( $df, $ts );
2177 * @param string $ts The time format which needs to be turned into a
2178 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2179 * @param bool $adj Whether to adjust the time output according to the
2180 * user configured offset ($timecorrection)
2181 * @param mixed $format True to use user's date format preference
2182 * @param string|bool $timecorrection The time offset as returned by
2183 * validateTimeZone() in Special:Preferences
2186 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2187 $ts = wfTimestamp( TS_MW
, $ts );
2189 $ts = $this->userAdjust( $ts, $timecorrection );
2191 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2192 return $this->sprintfDate( $df, $ts );
2196 * @param string $ts The time format which needs to be turned into a
2197 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2198 * @param bool $adj Whether to adjust the time output according to the
2199 * user configured offset ($timecorrection)
2200 * @param mixed $format What format to return, if it's false output the
2201 * default one (default true)
2202 * @param string|bool $timecorrection The time offset as returned by
2203 * validateTimeZone() in Special:Preferences
2206 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2207 $ts = wfTimestamp( TS_MW
, $ts );
2209 $ts = $this->userAdjust( $ts, $timecorrection );
2211 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2212 return $this->sprintfDate( $df, $ts );
2216 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2220 * @param int $seconds The amount of seconds.
2221 * @param array $chosenIntervals The intervals to enable.
2225 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2226 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2228 $segments = array();
2230 foreach ( $intervals as $intervalName => $intervalValue ) {
2231 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2232 // duration-years, duration-decades, duration-centuries, duration-millennia
2233 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2234 $segments[] = $message->inLanguage( $this )->escaped();
2237 return $this->listToText( $segments );
2241 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2242 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2246 * @param int $seconds The amount of seconds.
2247 * @param array $chosenIntervals The intervals to enable.
2251 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2252 if ( empty( $chosenIntervals ) ) {
2253 $chosenIntervals = array(
2265 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2266 $sortedNames = array_keys( $intervals );
2267 $smallestInterval = array_pop( $sortedNames );
2269 $segments = array();
2271 foreach ( $intervals as $name => $length ) {
2272 $value = floor( $seconds / $length );
2274 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2275 $seconds -= $value * $length;
2276 $segments[$name] = $value;
2284 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2286 * @param string $type Can be 'date', 'time' or 'both'
2287 * @param string $ts The time format which needs to be turned into a
2288 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2289 * @param User $user User object used to get preferences for timezone and format
2290 * @param array $options Array, can contain the following keys:
2291 * - 'timecorrection': time correction, can have the following values:
2292 * - true: use user's preference
2293 * - false: don't use time correction
2294 * - int: value of time correction in minutes
2295 * - 'format': format to use, can have the following values:
2296 * - true: use user's preference
2297 * - false: use default preference
2298 * - string: format to use
2302 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2303 $ts = wfTimestamp( TS_MW
, $ts );
2304 $options +
= array( 'timecorrection' => true, 'format' => true );
2305 if ( $options['timecorrection'] !== false ) {
2306 if ( $options['timecorrection'] === true ) {
2307 $offset = $user->getOption( 'timecorrection' );
2309 $offset = $options['timecorrection'];
2311 $ts = $this->userAdjust( $ts, $offset );
2313 if ( $options['format'] === true ) {
2314 $format = $user->getDatePreference();
2316 $format = $options['format'];
2318 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2319 return $this->sprintfDate( $df, $ts );
2323 * Get the formatted date for the given timestamp and formatted for
2326 * @param mixed $ts Mixed: the time format which needs to be turned into a
2327 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2328 * @param User $user User object used to get preferences for timezone and format
2329 * @param array $options Array, can contain the following keys:
2330 * - 'timecorrection': time correction, can have the following values:
2331 * - true: use user's preference
2332 * - false: don't use time correction
2333 * - int: value of time correction in minutes
2334 * - 'format': format to use, can have the following values:
2335 * - true: use user's preference
2336 * - false: use default preference
2337 * - string: format to use
2341 public function userDate( $ts, User
$user, array $options = array() ) {
2342 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2346 * Get the formatted time for the given timestamp and formatted for
2349 * @param mixed $ts The time format which needs to be turned into a
2350 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2351 * @param User $user User object used to get preferences for timezone and format
2352 * @param array $options Array, can contain the following keys:
2353 * - 'timecorrection': time correction, can have the following values:
2354 * - true: use user's preference
2355 * - false: don't use time correction
2356 * - int: value of time correction in minutes
2357 * - 'format': format to use, can have the following values:
2358 * - true: use user's preference
2359 * - false: use default preference
2360 * - string: format to use
2364 public function userTime( $ts, User
$user, array $options = array() ) {
2365 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2369 * Get the formatted date and time for the given timestamp and formatted for
2372 * @param mixed $ts The time format which needs to be turned into a
2373 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2374 * @param User $user User object used to get preferences for timezone and format
2375 * @param array $options Array, can contain the following keys:
2376 * - 'timecorrection': time correction, can have the following values:
2377 * - true: use user's preference
2378 * - false: don't use time correction
2379 * - int: value of time correction in minutes
2380 * - 'format': format to use, can have the following values:
2381 * - true: use user's preference
2382 * - false: use default preference
2383 * - string: format to use
2387 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2388 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2392 * Convert an MWTimestamp into a pretty human-readable timestamp using
2393 * the given user preferences and relative base time.
2395 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2396 * on your timestamp object, which will then call this function. Calling
2397 * this function directly will cause hooks to be skipped over.
2399 * @see MWTimestamp::getHumanTimestamp
2400 * @param MWTimestamp $ts Timestamp to prettify
2401 * @param MWTimestamp $relativeTo Base timestamp
2402 * @param User $user User preferences to use
2403 * @return string Human timestamp
2406 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2407 $diff = $ts->diff( $relativeTo );
2408 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2409 (int)$relativeTo->timestamp
->format( 'w' ) );
2410 $days = $diff->days ?
: (int)$diffDay;
2411 if ( $diff->invert ||
$days > 5
2412 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2414 // Timestamps are in different years: use full timestamp
2415 // Also do full timestamp for future dates
2417 * @todo FIXME: Add better handling of future timestamps.
2419 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2420 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2421 } elseif ( $days > 5 ) {
2422 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2423 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2424 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2425 } elseif ( $days > 1 ) {
2426 // Timestamp within the past week: show the day of the week and time
2427 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2428 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2430 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2431 $ts = wfMessage( "$weekday-at" )
2432 ->inLanguage( $this )
2433 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2435 } elseif ( $days == 1 ) {
2436 // Timestamp was yesterday: say 'yesterday' and the time.
2437 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2438 $ts = wfMessage( 'yesterday-at' )
2439 ->inLanguage( $this )
2440 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2442 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2443 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2444 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2445 $ts = wfMessage( 'today-at' )
2446 ->inLanguage( $this )
2447 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2450 // From here on in, the timestamp was soon enough ago so that we can simply say
2451 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2452 } elseif ( $diff->h
== 1 ) {
2453 // Less than 90 minutes, but more than an hour ago.
2454 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2455 } elseif ( $diff->i
>= 1 ) {
2456 // A few minutes ago.
2457 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2458 } elseif ( $diff->s
>= 30 ) {
2459 // Less than a minute, but more than 30 sec ago.
2460 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2462 // Less than 30 seconds ago.
2463 $ts = wfMessage( 'just-now' )->text();
2470 * @param string $key
2471 * @return array|null
2473 function getMessage( $key ) {
2474 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2480 function getAllMessages() {
2481 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2486 * @param string $out
2487 * @param string $string
2490 function iconv( $in, $out, $string ) {
2491 # This is a wrapper for iconv in all languages except esperanto,
2492 # which does some nasty x-conversions beforehand
2494 # Even with //IGNORE iconv can whine about illegal characters in
2495 # *input* string. We just ignore those too.
2496 # REF: http://bugs.php.net/bug.php?id=37166
2497 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2498 wfSuppressWarnings();
2499 $text = iconv( $in, $out . '//IGNORE', $string );
2500 wfRestoreWarnings();
2504 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2507 * @param array $matches
2508 * @return mixed|string
2510 function ucwordbreaksCallbackAscii( $matches ) {
2511 return $this->ucfirst( $matches[1] );
2515 * @param array $matches
2518 function ucwordbreaksCallbackMB( $matches ) {
2519 return mb_strtoupper( $matches[0] );
2523 * @param array $matches
2526 function ucCallback( $matches ) {
2527 list( $wikiUpperChars ) = self
::getCaseMaps();
2528 return strtr( $matches[1], $wikiUpperChars );
2532 * @param array $matches
2535 function lcCallback( $matches ) {
2536 list( , $wikiLowerChars ) = self
::getCaseMaps();
2537 return strtr( $matches[1], $wikiLowerChars );
2541 * @param array $matches
2544 function ucwordsCallbackMB( $matches ) {
2545 return mb_strtoupper( $matches[0] );
2549 * @param array $matches
2552 function ucwordsCallbackWiki( $matches ) {
2553 list( $wikiUpperChars ) = self
::getCaseMaps();
2554 return strtr( $matches[0], $wikiUpperChars );
2558 * Make a string's first character uppercase
2560 * @param string $str
2564 function ucfirst( $str ) {
2566 if ( $o < 96 ) { // if already uppercase...
2568 } elseif ( $o < 128 ) {
2569 return ucfirst( $str ); // use PHP's ucfirst()
2571 // fall back to more complex logic in case of multibyte strings
2572 return $this->uc( $str, true );
2577 * Convert a string to uppercase
2579 * @param string $str
2580 * @param bool $first
2584 function uc( $str, $first = false ) {
2585 if ( function_exists( 'mb_strtoupper' ) ) {
2587 if ( $this->isMultibyte( $str ) ) {
2588 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2590 return ucfirst( $str );
2593 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2596 if ( $this->isMultibyte( $str ) ) {
2597 $x = $first ?
'^' : '';
2598 return preg_replace_callback(
2599 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2600 array( $this, 'ucCallback' ),
2604 return $first ?
ucfirst( $str ) : strtoupper( $str );
2610 * @param string $str
2611 * @return mixed|string
2613 function lcfirst( $str ) {
2616 return strval( $str );
2617 } elseif ( $o >= 128 ) {
2618 return $this->lc( $str, true );
2619 } elseif ( $o > 96 ) {
2622 $str[0] = strtolower( $str[0] );
2628 * @param string $str
2629 * @param bool $first
2630 * @return mixed|string
2632 function lc( $str, $first = false ) {
2633 if ( function_exists( 'mb_strtolower' ) ) {
2635 if ( $this->isMultibyte( $str ) ) {
2636 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2638 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2641 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2644 if ( $this->isMultibyte( $str ) ) {
2645 $x = $first ?
'^' : '';
2646 return preg_replace_callback(
2647 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2648 array( $this, 'lcCallback' ),
2652 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2658 * @param string $str
2661 function isMultibyte( $str ) {
2662 return (bool)preg_match( '/[\x80-\xff]/', $str );
2666 * @param string $str
2667 * @return mixed|string
2669 function ucwords( $str ) {
2670 if ( $this->isMultibyte( $str ) ) {
2671 $str = $this->lc( $str );
2673 // regexp to find first letter in each word (i.e. after each space)
2674 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2676 // function to use to capitalize a single char
2677 if ( function_exists( 'mb_strtoupper' ) ) {
2678 return preg_replace_callback(
2680 array( $this, 'ucwordsCallbackMB' ),
2684 return preg_replace_callback(
2686 array( $this, 'ucwordsCallbackWiki' ),
2691 return ucwords( strtolower( $str ) );
2696 * capitalize words at word breaks
2698 * @param string $str
2701 function ucwordbreaks( $str ) {
2702 if ( $this->isMultibyte( $str ) ) {
2703 $str = $this->lc( $str );
2705 // since \b doesn't work for UTF-8, we explicitely define word break chars
2706 $breaks = "[ \-\(\)\}\{\.,\?!]";
2708 // find first letter after word break
2709 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2710 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2712 if ( function_exists( 'mb_strtoupper' ) ) {
2713 return preg_replace_callback(
2715 array( $this, 'ucwordbreaksCallbackMB' ),
2719 return preg_replace_callback(
2721 array( $this, 'ucwordsCallbackWiki' ),
2726 return preg_replace_callback(
2727 '/\b([\w\x80-\xff]+)\b/',
2728 array( $this, 'ucwordbreaksCallbackAscii' ),
2735 * Return a case-folded representation of $s
2737 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2738 * and $s2 are the same except for the case of their characters. It is not
2739 * necessary for the value returned to make sense when displayed.
2741 * Do *not* perform any other normalisation in this function. If a caller
2742 * uses this function when it should be using a more general normalisation
2743 * function, then fix the caller.
2749 function caseFold( $s ) {
2750 return $this->uc( $s );
2757 function checkTitleEncoding( $s ) {
2758 if ( is_array( $s ) ) {
2759 throw new MWException( 'Given array to checkTitleEncoding.' );
2761 if ( StringUtils
::isUtf8( $s ) ) {
2765 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2771 function fallback8bitEncoding() {
2772 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2776 * Most writing systems use whitespace to break up words.
2777 * Some languages such as Chinese don't conventionally do this,
2778 * which requires special handling when breaking up words for
2783 function hasWordBreaks() {
2788 * Some languages such as Chinese require word segmentation,
2789 * Specify such segmentation when overridden in derived class.
2791 * @param string $string
2794 function segmentByWord( $string ) {
2799 * Some languages have special punctuation need to be normalized.
2800 * Make such changes here.
2802 * @param string $string
2805 function normalizeForSearch( $string ) {
2806 return self
::convertDoubleWidth( $string );
2810 * convert double-width roman characters to single-width.
2811 * range: ff00-ff5f ~= 0020-007f
2813 * @param string $string
2817 protected static function convertDoubleWidth( $string ) {
2818 static $full = null;
2819 static $half = null;
2821 if ( $full === null ) {
2822 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2823 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2824 $full = str_split( $fullWidth, 3 );
2825 $half = str_split( $halfWidth );
2828 $string = str_replace( $full, $half, $string );
2833 * @param string $string
2834 * @param string $pattern
2837 protected static function insertSpace( $string, $pattern ) {
2838 $string = preg_replace( $pattern, " $1 ", $string );
2839 $string = preg_replace( '/ +/', ' ', $string );
2844 * @param array $termsArray
2847 function convertForSearchResult( $termsArray ) {
2848 # some languages, e.g. Chinese, need to do a conversion
2849 # in order for search results to be displayed correctly
2854 * Get the first character of a string.
2859 function firstChar( $s ) {
2862 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2863 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2868 if ( isset( $matches[1] ) ) {
2869 if ( strlen( $matches[1] ) != 3 ) {
2873 // Break down Hangul syllables to grab the first jamo
2874 $code = utf8ToCodepoint( $matches[1] );
2875 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2877 } elseif ( $code < 0xb098 ) {
2878 return "\xe3\x84\xb1";
2879 } elseif ( $code < 0xb2e4 ) {
2880 return "\xe3\x84\xb4";
2881 } elseif ( $code < 0xb77c ) {
2882 return "\xe3\x84\xb7";
2883 } elseif ( $code < 0xb9c8 ) {
2884 return "\xe3\x84\xb9";
2885 } elseif ( $code < 0xbc14 ) {
2886 return "\xe3\x85\x81";
2887 } elseif ( $code < 0xc0ac ) {
2888 return "\xe3\x85\x82";
2889 } elseif ( $code < 0xc544 ) {
2890 return "\xe3\x85\x85";
2891 } elseif ( $code < 0xc790 ) {
2892 return "\xe3\x85\x87";
2893 } elseif ( $code < 0xcc28 ) {
2894 return "\xe3\x85\x88";
2895 } elseif ( $code < 0xce74 ) {
2896 return "\xe3\x85\x8a";
2897 } elseif ( $code < 0xd0c0 ) {
2898 return "\xe3\x85\x8b";
2899 } elseif ( $code < 0xd30c ) {
2900 return "\xe3\x85\x8c";
2901 } elseif ( $code < 0xd558 ) {
2902 return "\xe3\x85\x8d";
2904 return "\xe3\x85\x8e";
2911 function initEncoding() {
2912 # Some languages may have an alternate char encoding option
2913 # (Esperanto X-coding, Japanese furigana conversion, etc)
2914 # If this language is used as the primary content language,
2915 # an override to the defaults can be set here on startup.
2922 function recodeForEdit( $s ) {
2923 # For some languages we'll want to explicitly specify
2924 # which characters make it into the edit box raw
2925 # or are converted in some way or another.
2926 global $wgEditEncoding;
2927 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2930 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2938 function recodeInput( $s ) {
2939 # Take the previous into account.
2940 global $wgEditEncoding;
2941 if ( $wgEditEncoding != '' ) {
2942 $enc = $wgEditEncoding;
2946 if ( $enc == 'UTF-8' ) {
2949 return $this->iconv( $enc, 'UTF-8', $s );
2954 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2955 * also cleans up certain backwards-compatible sequences, converting them
2956 * to the modern Unicode equivalent.
2958 * This is language-specific for performance reasons only.
2964 function normalize( $s ) {
2965 global $wgAllUnicodeFixes;
2966 $s = UtfNormal
::cleanUp( $s );
2967 if ( $wgAllUnicodeFixes ) {
2968 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2969 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2976 * Transform a string using serialized data stored in the given file (which
2977 * must be in the serialized subdirectory of $IP). The file contains pairs
2978 * mapping source characters to destination characters.
2980 * The data is cached in process memory. This will go faster if you have the
2981 * FastStringSearch extension.
2983 * @param string $file
2984 * @param string $string
2986 * @throws MWException
2989 function transformUsingPairFile( $file, $string ) {
2990 if ( !isset( $this->transformData
[$file] ) ) {
2991 $data = wfGetPrecompiledData( $file );
2992 if ( $data === false ) {
2993 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2995 $this->transformData
[$file] = new ReplacementArray( $data );
2997 return $this->transformData
[$file]->replace( $string );
3001 * For right-to-left language support
3006 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
3010 * Return the correct HTML 'dir' attribute value for this language.
3014 return $this->isRTL() ?
'rtl' : 'ltr';
3018 * Return 'left' or 'right' as appropriate alignment for line-start
3019 * for this language's text direction.
3021 * Should be equivalent to CSS3 'start' text-align value....
3025 function alignStart() {
3026 return $this->isRTL() ?
'right' : 'left';
3030 * Return 'right' or 'left' as appropriate alignment for line-end
3031 * for this language's text direction.
3033 * Should be equivalent to CSS3 'end' text-align value....
3037 function alignEnd() {
3038 return $this->isRTL() ?
'left' : 'right';
3042 * A hidden direction mark (LRM or RLM), depending on the language direction.
3043 * Unlike getDirMark(), this function returns the character as an HTML entity.
3044 * This function should be used when the output is guaranteed to be HTML,
3045 * because it makes the output HTML source code more readable. When
3046 * the output is plain text or can be escaped, getDirMark() should be used.
3048 * @param bool $opposite Get the direction mark opposite to your language
3052 function getDirMarkEntity( $opposite = false ) {
3054 return $this->isRTL() ?
'‎' : '‏';
3056 return $this->isRTL() ?
'‏' : '‎';
3060 * A hidden direction mark (LRM or RLM), depending on the language direction.
3061 * This function produces them as invisible Unicode characters and
3062 * the output may be hard to read and debug, so it should only be used
3063 * when the output is plain text or can be escaped. When the output is
3064 * HTML, use getDirMarkEntity() instead.
3066 * @param bool $opposite Get the direction mark opposite to your language
3069 function getDirMark( $opposite = false ) {
3070 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3071 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3073 return $this->isRTL() ?
$lrm : $rlm;
3075 return $this->isRTL() ?
$rlm : $lrm;
3081 function capitalizeAllNouns() {
3082 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3086 * An arrow, depending on the language direction.
3088 * @param string $direction The direction of the arrow: forwards (default),
3089 * backwards, left, right, up, down.
3092 function getArrow( $direction = 'forwards' ) {
3093 switch ( $direction ) {
3095 return $this->isRTL() ?
'←' : '→';
3097 return $this->isRTL() ?
'→' : '←';
3110 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3114 function linkPrefixExtension() {
3115 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3119 * Get all magic words from cache.
3122 function getMagicWords() {
3123 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3127 * Run the LanguageGetMagic hook once.
3129 protected function doMagicHook() {
3130 if ( $this->mMagicHookDone
) {
3133 $this->mMagicHookDone
= true;
3134 wfProfileIn( 'LanguageGetMagic' );
3135 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3136 wfProfileOut( 'LanguageGetMagic' );
3140 * Fill a MagicWord object with data from here
3142 * @param MagicWord $mw
3144 function getMagic( $mw ) {
3145 // Saves a function call
3146 if ( !$this->mMagicHookDone
) {
3147 $this->doMagicHook();
3150 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3151 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3153 $rawEntry = self
::$dataCache->getSubitem(
3154 $this->mCode
, 'magicWords', $mw->mId
);
3157 if ( !is_array( $rawEntry ) ) {
3158 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3160 $mw->mCaseSensitive
= $rawEntry[0];
3161 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3166 * Add magic words to the extension array
3168 * @param array $newWords
3170 function addMagicWordsByLang( $newWords ) {
3171 $fallbackChain = $this->getFallbackLanguages();
3172 $fallbackChain = array_reverse( $fallbackChain );
3173 foreach ( $fallbackChain as $code ) {
3174 if ( isset( $newWords[$code] ) ) {
3175 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3181 * Get special page names, as an associative array
3182 * case folded alias => real name
3185 function getSpecialPageAliases() {
3186 // Cache aliases because it may be slow to load them
3187 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3189 $this->mExtendedSpecialPageAliases
=
3190 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3191 wfRunHooks( 'LanguageGetSpecialPageAliases',
3192 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3195 return $this->mExtendedSpecialPageAliases
;
3199 * Italic is unsuitable for some languages
3201 * @param string $text The text to be emphasized.
3204 function emphasize( $text ) {
3205 return "<em>$text</em>";
3209 * Normally we output all numbers in plain en_US style, that is
3210 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3211 * point twohundredthirtyfive. However this is not suitable for all
3212 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3213 * Icelandic just want to use commas instead of dots, and dots instead
3214 * of commas like "293.291,235".
3216 * An example of this function being called:
3218 * wfMessage( 'message' )->numParams( $num )->text()
3221 * See $separatorTransformTable on MessageIs.php for
3222 * the , => . and . => , implementation.
3224 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3225 * @param int|float $number The string to be formatted, should be an integer
3226 * or a floating point number.
3227 * @param bool $nocommafy Set to true for special numbers like dates
3230 public function formatNum( $number, $nocommafy = false ) {
3231 global $wgTranslateNumerals;
3232 if ( !$nocommafy ) {
3233 $number = $this->commafy( $number );
3234 $s = $this->separatorTransformTable();
3236 $number = strtr( $number, $s );
3240 if ( $wgTranslateNumerals ) {
3241 $s = $this->digitTransformTable();
3243 $number = strtr( $number, $s );
3251 * Front-end for non-commafied formatNum
3253 * @param int|float $number The string to be formatted, should be an integer
3254 * or a floating point number.
3258 public function formatNumNoSeparators( $number ) {
3259 return $this->formatNum( $number, true );
3263 * @param string $number
3266 public function parseFormattedNumber( $number ) {
3267 $s = $this->digitTransformTable();
3269 // eliminate empty array values such as ''. (bug 64347)
3270 $s = array_filter( $s );
3271 $number = strtr( $number, array_flip( $s ) );
3274 $s = $this->separatorTransformTable();
3276 // eliminate empty array values such as ''. (bug 64347)
3277 $s = array_filter( $s );
3278 $number = strtr( $number, array_flip( $s ) );
3281 $number = strtr( $number, array( ',' => '' ) );
3286 * Adds commas to a given number
3288 * @param mixed $number
3291 function commafy( $number ) {
3292 $digitGroupingPattern = $this->digitGroupingPattern();
3293 if ( $number === null ) {
3297 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3298 // default grouping is at thousands, use the same for ###,###,### pattern too.
3299 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3301 // Ref: http://cldr.unicode.org/translation/number-patterns
3303 if ( intval( $number ) < 0 ) {
3304 // For negative numbers apply the algorithm like positive number and add sign.
3306 $number = substr( $number, 1 );
3308 $integerPart = array();
3309 $decimalPart = array();
3310 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3311 preg_match( "/\d+/", $number, $integerPart );
3312 preg_match( "/\.\d*/", $number, $decimalPart );
3313 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3314 if ( $groupedNumber === $number ) {
3315 // the string does not have any number part. Eg: .12345
3316 return $sign . $groupedNumber;
3318 $start = $end = strlen( $integerPart[0] );
3319 while ( $start > 0 ) {
3320 $match = $matches[0][$numMatches - 1];
3321 $matchLen = strlen( $match );
3322 $start = $end - $matchLen;
3326 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3328 if ( $numMatches > 1 ) {
3329 // use the last pattern for the rest of the number
3333 $groupedNumber = "," . $groupedNumber;
3336 return $sign . $groupedNumber;
3343 function digitGroupingPattern() {
3344 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3350 function digitTransformTable() {
3351 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3357 function separatorTransformTable() {
3358 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3362 * Take a list of strings and build a locale-friendly comma-separated
3363 * list, using the local comma-separator message.
3364 * The last two strings are chained with an "and".
3365 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3367 * @param string[] $l
3370 function listToText( array $l ) {
3371 $m = count( $l ) - 1;
3376 $and = $this->getMessageFromDB( 'and' );
3377 $space = $this->getMessageFromDB( 'word-separator' );
3379 $comma = $this->getMessageFromDB( 'comma-separator' );
3383 for ( $i = $m - 1; $i >= 0; $i-- ) {
3384 if ( $i == $m - 1 ) {
3385 $s = $l[$i] . $and . $space . $s;
3387 $s = $l[$i] . $comma . $s;
3394 * Take a list of strings and build a locale-friendly comma-separated
3395 * list, using the local comma-separator message.
3396 * @param string[] $list Array of strings to put in a comma list
3399 function commaList( array $list ) {
3401 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3407 * Take a list of strings and build a locale-friendly semicolon-separated
3408 * list, using the local semicolon-separator message.
3409 * @param string[] $list Array of strings to put in a semicolon list
3412 function semicolonList( array $list ) {
3414 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3420 * Same as commaList, but separate it with the pipe instead.
3421 * @param string[] $list Array of strings to put in a pipe list
3424 function pipeList( array $list ) {
3426 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3432 * Truncate a string to a specified length in bytes, appending an optional
3433 * string (e.g. for ellipses)
3435 * The database offers limited byte lengths for some columns in the database;
3436 * multi-byte character sets mean we need to ensure that only whole characters
3437 * are included, otherwise broken characters can be passed to the user
3439 * If $length is negative, the string will be truncated from the beginning
3441 * @param string $string String to truncate
3442 * @param int $length Maximum length (including ellipses)
3443 * @param string $ellipsis String to append to the truncated text
3444 * @param bool $adjustLength Subtract length of ellipsis from $length.
3445 * $adjustLength was introduced in 1.18, before that behaved as if false.
3448 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3449 # Use the localized ellipsis character
3450 if ( $ellipsis == '...' ) {
3451 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3453 # Check if there is no need to truncate
3454 if ( $length == 0 ) {
3455 return $ellipsis; // convention
3456 } elseif ( strlen( $string ) <= abs( $length ) ) {
3457 return $string; // no need to truncate
3459 $stringOriginal = $string;
3460 # If ellipsis length is >= $length then we can't apply $adjustLength
3461 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3462 $string = $ellipsis; // this can be slightly unexpected
3463 # Otherwise, truncate and add ellipsis...
3465 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3466 if ( $length > 0 ) {
3467 $length -= $eLength;
3468 $string = substr( $string, 0, $length ); // xyz...
3469 $string = $this->removeBadCharLast( $string );
3470 $string = rtrim( $string );
3471 $string = $string . $ellipsis;
3473 $length +
= $eLength;
3474 $string = substr( $string, $length ); // ...xyz
3475 $string = $this->removeBadCharFirst( $string );
3476 $string = ltrim( $string );
3477 $string = $ellipsis . $string;
3480 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3481 # This check is *not* redundant if $adjustLength, due to the single case where
3482 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3483 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3486 return $stringOriginal;
3491 * Remove bytes that represent an incomplete Unicode character
3492 * at the end of string (e.g. bytes of the char are missing)
3494 * @param string $string
3497 protected function removeBadCharLast( $string ) {
3498 if ( $string != '' ) {
3499 $char = ord( $string[strlen( $string ) - 1] );
3501 if ( $char >= 0xc0 ) {
3502 # We got the first byte only of a multibyte char; remove it.
3503 $string = substr( $string, 0, -1 );
3504 } elseif ( $char >= 0x80 &&
3505 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3506 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3508 # We chopped in the middle of a character; remove it
3516 * Remove bytes that represent an incomplete Unicode character
3517 * at the start of string (e.g. bytes of the char are missing)
3519 * @param string $string
3522 protected function removeBadCharFirst( $string ) {
3523 if ( $string != '' ) {
3524 $char = ord( $string[0] );
3525 if ( $char >= 0x80 && $char < 0xc0 ) {
3526 # We chopped in the middle of a character; remove the whole thing
3527 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3534 * Truncate a string of valid HTML to a specified length in bytes,
3535 * appending an optional string (e.g. for ellipses), and return valid HTML
3537 * This is only intended for styled/linked text, such as HTML with
3538 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3539 * Also, this will not detect things like "display:none" CSS.
3541 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3543 * @param string $text HTML string to truncate
3544 * @param int $length (zero/positive) Maximum length (including ellipses)
3545 * @param string $ellipsis String to append to the truncated text
3548 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3549 # Use the localized ellipsis character
3550 if ( $ellipsis == '...' ) {
3551 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3553 # Check if there is clearly no need to truncate
3554 if ( $length <= 0 ) {
3555 return $ellipsis; // no text shown, nothing to format (convention)
3556 } elseif ( strlen( $text ) <= $length ) {
3557 return $text; // string short enough even *with* HTML (short-circuit)
3560 $dispLen = 0; // innerHTML legth so far
3561 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3562 $tagType = 0; // 0-open, 1-close
3563 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3564 $entityState = 0; // 0-not entity, 1-entity
3565 $tag = $ret = ''; // accumulated tag name, accumulated result string
3566 $openTags = array(); // open tag stack
3567 $maybeState = null; // possible truncation state
3569 $textLen = strlen( $text );
3570 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3571 for ( $pos = 0; true; ++
$pos ) {
3572 # Consider truncation once the display length has reached the maximim.
3573 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3574 # Check that we're not in the middle of a bracket/entity...
3575 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3576 if ( !$testingEllipsis ) {
3577 $testingEllipsis = true;
3578 # Save where we are; we will truncate here unless there turn out to
3579 # be so few remaining characters that truncation is not necessary.
3580 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3581 $maybeState = array( $ret, $openTags ); // save state
3583 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3584 # String in fact does need truncation, the truncation point was OK.
3585 list( $ret, $openTags ) = $maybeState; // reload state
3586 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3587 $ret .= $ellipsis; // add ellipsis
3591 if ( $pos >= $textLen ) {
3592 break; // extra iteration just for above checks
3595 # Read the next char...
3597 $lastCh = $pos ?
$text[$pos - 1] : '';
3598 $ret .= $ch; // add to result string
3600 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3601 $entityState = 0; // for bad HTML
3602 $bracketState = 1; // tag started (checking for backslash)
3603 } elseif ( $ch == '>' ) {
3604 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3605 $entityState = 0; // for bad HTML
3606 $bracketState = 0; // out of brackets
3607 } elseif ( $bracketState == 1 ) {
3609 $tagType = 1; // close tag (e.g. "</span>")
3611 $tagType = 0; // open tag (e.g. "<span>")
3614 $bracketState = 2; // building tag name
3615 } elseif ( $bracketState == 2 ) {
3619 // Name found (e.g. "<a href=..."), add on tag attributes...
3620 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3622 } elseif ( $bracketState == 0 ) {
3623 if ( $entityState ) {
3626 $dispLen++
; // entity is one displayed char
3629 if ( $neLength == 0 && !$maybeState ) {
3630 // Save state without $ch. We want to *hit* the first
3631 // display char (to get tags) but not *use* it if truncating.
3632 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3635 $entityState = 1; // entity found, (e.g. " ")
3637 $dispLen++
; // this char is displayed
3638 // Add the next $max display text chars after this in one swoop...
3639 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3640 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3641 $dispLen +
= $skipped;
3647 // Close the last tag if left unclosed by bad HTML
3648 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3649 while ( count( $openTags ) > 0 ) {
3650 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3656 * truncateHtml() helper function
3657 * like strcspn() but adds the skipped chars to $ret
3659 * @param string $ret
3660 * @param string $text
3661 * @param string $search
3663 * @param null|int $len
3666 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3667 if ( $len === null ) {
3668 $len = -1; // -1 means "no limit" for strcspn
3669 } elseif ( $len < 0 ) {
3673 if ( $start < strlen( $text ) ) {
3674 $skipCount = strcspn( $text, $search, $start, $len );
3675 $ret .= substr( $text, $start, $skipCount );
3681 * truncateHtml() helper function
3682 * (a) push or pop $tag from $openTags as needed
3683 * (b) clear $tag value
3684 * @param string &$tag Current HTML tag name we are looking at
3685 * @param int $tagType (0-open tag, 1-close tag)
3686 * @param string $lastCh Character before the '>' that ended this tag
3687 * @param array &$openTags Open tag stack (not accounting for $tag)
3689 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3690 $tag = ltrim( $tag );
3692 if ( $tagType == 0 && $lastCh != '/' ) {
3693 $openTags[] = $tag; // tag opened (didn't close itself)
3694 } elseif ( $tagType == 1 ) {
3695 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3696 array_pop( $openTags ); // tag closed
3704 * Grammatical transformations, needed for inflected languages
3705 * Invoked by putting {{grammar:case|word}} in a message
3707 * @param string $word
3708 * @param string $case
3711 function convertGrammar( $word, $case ) {
3712 global $wgGrammarForms;
3713 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3714 return $wgGrammarForms[$this->getCode()][$case][$word];
3720 * Get the grammar forms for the content language
3721 * @return array Array of grammar forms
3724 function getGrammarForms() {
3725 global $wgGrammarForms;
3726 if ( isset( $wgGrammarForms[$this->getCode()] )
3727 && is_array( $wgGrammarForms[$this->getCode()] )
3729 return $wgGrammarForms[$this->getCode()];
3735 * Provides an alternative text depending on specified gender.
3736 * Usage {{gender:username|masculine|feminine|unknown}}.
3737 * username is optional, in which case the gender of current user is used,
3738 * but only in (some) interface messages; otherwise default gender is used.
3740 * If no forms are given, an empty string is returned. If only one form is
3741 * given, it will be returned unconditionally. These details are implied by
3742 * the caller and cannot be overridden in subclasses.
3744 * If three forms are given, the default is to use the third (unknown) form.
3745 * If fewer than three forms are given, the default is to use the first (masculine) form.
3746 * These details can be overridden in subclasses.
3748 * @param string $gender
3749 * @param array $forms
3753 function gender( $gender, $forms ) {
3754 if ( !count( $forms ) ) {
3757 $forms = $this->preConvertPlural( $forms, 2 );
3758 if ( $gender === 'male' ) {
3761 if ( $gender === 'female' ) {
3764 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3768 * Plural form transformations, needed for some languages.
3769 * For example, there are 3 form of plural in Russian and Polish,
3770 * depending on "count mod 10". See [[w:Plural]]
3771 * For English it is pretty simple.
3773 * Invoked by putting {{plural:count|wordform1|wordform2}}
3774 * or {{plural:count|wordform1|wordform2|wordform3}}
3776 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3778 * @param int $count Non-localized number
3779 * @param array $forms Different plural forms
3780 * @return string Correct form of plural for $count in this language
3782 function convertPlural( $count, $forms ) {
3783 // Handle explicit n=pluralform cases
3784 $forms = $this->handleExplicitPluralForms( $count, $forms );
3785 if ( is_string( $forms ) ) {
3788 if ( !count( $forms ) ) {
3792 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3793 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3794 return $forms[$pluralForm];
3798 * Handles explicit plural forms for Language::convertPlural()
3800 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3801 * If an explicitly defined plural form matches the $count, then
3802 * string value returned, otherwise array returned for further consideration
3803 * by CLDR rules or overridden convertPlural().
3807 * @param int $count Non-localized number
3808 * @param array $forms Different plural forms
3810 * @return array|string
3812 protected function handleExplicitPluralForms( $count, array $forms ) {
3813 foreach ( $forms as $index => $form ) {
3814 if ( preg_match( '/\d+=/i', $form ) ) {
3815 $pos = strpos( $form, '=' );
3816 if ( substr( $form, 0, $pos ) === (string)$count ) {
3817 return substr( $form, $pos +
1 );
3819 unset( $forms[$index] );
3822 return array_values( $forms );
3826 * Checks that convertPlural was given an array and pads it to requested
3827 * amount of forms by copying the last one.
3829 * @param array $forms Array of forms given to convertPlural
3830 * @param int $count How many forms should there be at least
3831 * @return array Padded array of forms or an exception if not an array
3833 protected function preConvertPlural( /* Array */ $forms, $count ) {
3834 while ( count( $forms ) < $count ) {
3835 $forms[] = $forms[count( $forms ) - 1];
3841 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3842 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3843 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3844 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3847 * @param string $str The validated block duration in English
3848 * @return string Somehow translated block duration
3849 * @see LanguageFi.php for example implementation
3851 function translateBlockExpiry( $str ) {
3852 $duration = SpecialBlock
::getSuggestedDurations( $this );
3853 foreach ( $duration as $show => $value ) {
3854 if ( strcmp( $str, $value ) == 0 ) {
3855 return htmlspecialchars( trim( $show ) );
3859 // Since usually only infinite or indefinite is only on list, so try
3860 // equivalents if still here.
3861 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3862 if ( in_array( $str, $indefs ) ) {
3863 foreach ( $indefs as $val ) {
3864 $show = array_search( $val, $duration, true );
3865 if ( $show !== false ) {
3866 return htmlspecialchars( trim( $show ) );
3871 // If all else fails, return a standard duration or timestamp description.
3872 $time = strtotime( $str, 0 );
3873 if ( $time === false ) { // Unknown format. Return it as-is in case.
3875 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3876 // $time is relative to 0 so it's a duration length.
3877 return $this->formatDuration( $time );
3878 } else { // It's an absolute timestamp.
3879 if ( $time === 0 ) {
3880 // wfTimestamp() handles 0 as current time instead of epoch.
3881 return $this->timeanddate( '19700101000000' );
3883 return $this->timeanddate( $time );
3889 * languages like Chinese need to be segmented in order for the diff
3892 * @param string $text
3895 public function segmentForDiff( $text ) {
3900 * and unsegment to show the result
3902 * @param string $text
3905 public function unsegmentForDiff( $text ) {
3910 * Return the LanguageConverter used in the Language
3913 * @return LanguageConverter
3915 public function getConverter() {
3916 return $this->mConverter
;
3920 * convert text to all supported variants
3922 * @param string $text
3925 public function autoConvertToAllVariants( $text ) {
3926 return $this->mConverter
->autoConvertToAllVariants( $text );
3930 * convert text to different variants of a language.
3932 * @param string $text
3935 public function convert( $text ) {
3936 return $this->mConverter
->convert( $text );
3940 * Convert a Title object to a string in the preferred variant
3942 * @param Title $title
3945 public function convertTitle( $title ) {
3946 return $this->mConverter
->convertTitle( $title );
3950 * Convert a namespace index to a string in the preferred variant
3955 public function convertNamespace( $ns ) {
3956 return $this->mConverter
->convertNamespace( $ns );
3960 * Check if this is a language with variants
3964 public function hasVariants() {
3965 return count( $this->getVariants() ) > 1;
3969 * Check if the language has the specific variant
3972 * @param string $variant
3975 public function hasVariant( $variant ) {
3976 return (bool)$this->mConverter
->validateVariant( $variant );
3980 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3982 * @param string $text
3984 * @deprecated since 1.22 is no longer used
3986 public function armourMath( $text ) {
3987 return $this->mConverter
->armourMath( $text );
3991 * Perform output conversion on a string, and encode for safe HTML output.
3992 * @param string $text Text to be converted
3993 * @param bool $isTitle Whether this conversion is for the article title
3995 * @todo this should get integrated somewhere sane
3997 public function convertHtml( $text, $isTitle = false ) {
3998 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4002 * @param string $key
4005 public function convertCategoryKey( $key ) {
4006 return $this->mConverter
->convertCategoryKey( $key );
4010 * Get the list of variants supported by this language
4011 * see sample implementation in LanguageZh.php
4013 * @return array An array of language codes
4015 public function getVariants() {
4016 return $this->mConverter
->getVariants();
4022 public function getPreferredVariant() {
4023 return $this->mConverter
->getPreferredVariant();
4029 public function getDefaultVariant() {
4030 return $this->mConverter
->getDefaultVariant();
4036 public function getURLVariant() {
4037 return $this->mConverter
->getURLVariant();
4041 * If a language supports multiple variants, it is
4042 * possible that non-existing link in one variant
4043 * actually exists in another variant. this function
4044 * tries to find it. See e.g. LanguageZh.php
4045 * The input parameters may be modified upon return
4047 * @param string &$link The name of the link
4048 * @param Title &$nt The title object of the link
4049 * @param bool $ignoreOtherCond To disable other conditions when
4050 * we need to transclude a template or update a category's link
4052 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4053 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4057 * returns language specific options used by User::getPageRenderHash()
4058 * for example, the preferred language variant
4062 function getExtraHashOptions() {
4063 return $this->mConverter
->getExtraHashOptions();
4067 * For languages that support multiple variants, the title of an
4068 * article may be displayed differently in different variants. this
4069 * function returns the apporiate title defined in the body of the article.
4073 public function getParsedTitle() {
4074 return $this->mConverter
->getParsedTitle();
4078 * Prepare external link text for conversion. When the text is
4079 * a URL, it shouldn't be converted, and it'll be wrapped in
4080 * the "raw" tag (-{R| }-) to prevent conversion.
4082 * This function is called "markNoConversion" for historical
4085 * @param string $text Text to be used for external link
4086 * @param bool $noParse Wrap it without confirming it's a real URL first
4087 * @return string The tagged text
4089 public function markNoConversion( $text, $noParse = false ) {
4090 // Excluding protocal-relative URLs may avoid many false positives.
4091 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4092 return $this->mConverter
->markNoConversion( $text );
4099 * A regular expression to match legal word-trailing characters
4100 * which should be merged onto a link of the form [[foo]]bar.
4104 public function linkTrail() {
4105 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4109 * A regular expression character set to match legal word-prefixing
4110 * characters which should be merged onto a link of the form foo[[bar]].
4114 public function linkPrefixCharset() {
4115 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4119 * @deprecated since 1.24, will be removed in 1.25
4122 function getLangObj() {
4123 wfDeprecated( __METHOD__
, '1.24' );
4128 * Get the "parent" language which has a converter to convert a "compatible" language
4129 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4131 * @return Language|null
4134 public function getParentLanguage() {
4135 if ( $this->mParentLanguage
!== false ) {
4136 return $this->mParentLanguage
;
4139 $pieces = explode( '-', $this->getCode() );
4141 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4142 $this->mParentLanguage
= null;
4145 $lang = Language
::factory( $code );
4146 if ( !$lang->hasVariant( $this->getCode() ) ) {
4147 $this->mParentLanguage
= null;
4151 $this->mParentLanguage
= $lang;
4156 * Get the RFC 3066 code for this language object
4158 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4159 * htmlspecialchars() or similar
4163 public function getCode() {
4164 return $this->mCode
;
4168 * Get the code in Bcp47 format which we can use
4169 * inside of html lang="" tags.
4171 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4172 * htmlspecialchars() or similar.
4177 public function getHtmlCode() {
4178 if ( is_null( $this->mHtmlCode
) ) {
4179 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4181 return $this->mHtmlCode
;
4185 * @param string $code
4187 public function setCode( $code ) {
4188 $this->mCode
= $code;
4189 // Ensure we don't leave incorrect cached data lying around
4190 $this->mHtmlCode
= null;
4191 $this->mParentLanguage
= false;
4195 * Get the name of a file for a certain language code
4196 * @param string $prefix Prepend this to the filename
4197 * @param string $code Language code
4198 * @param string $suffix Append this to the filename
4199 * @throws MWException
4200 * @return string $prefix . $mangledCode . $suffix
4202 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4203 if ( !self
::isValidBuiltInCode( $code ) ) {
4204 throw new MWException( "Invalid language code \"$code\"" );
4207 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4211 * Get the language code from a file name. Inverse of getFileName()
4212 * @param string $filename $prefix . $languageCode . $suffix
4213 * @param string $prefix Prefix before the language code
4214 * @param string $suffix Suffix after the language code
4215 * @return string Language code, or false if $prefix or $suffix isn't found
4217 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4219 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4220 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4221 if ( !count( $m ) ) {
4224 return str_replace( '_', '-', strtolower( $m[1] ) );
4228 * @param string $code
4231 public static function getMessagesFileName( $code ) {
4233 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4234 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4239 * @param string $code
4243 public static function getJsonMessagesFileName( $code ) {
4246 if ( !self
::isValidBuiltInCode( $code ) ) {
4247 throw new MWException( "Invalid language code \"$code\"" );
4250 return "$IP/languages/i18n/$code.json";
4254 * @param string $code
4257 public static function getClassFileName( $code ) {
4259 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4263 * Get the first fallback for a given language.
4265 * @param string $code
4267 * @return bool|string
4269 public static function getFallbackFor( $code ) {
4270 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4273 $fallbacks = self
::getFallbacksFor( $code );
4274 $first = array_shift( $fallbacks );
4280 * Get the ordered list of fallback languages.
4283 * @param string $code Language code
4286 public static function getFallbacksFor( $code ) {
4287 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4290 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4291 $v = array_map( 'trim', explode( ',', $v ) );
4292 if ( $v[count( $v ) - 1] !== 'en' ) {
4300 * Get the ordered list of fallback languages, ending with the fallback
4301 * language chain for the site language.
4304 * @param string $code Language code
4305 * @return array Array( fallbacks, site fallbacks )
4307 public static function getFallbacksIncludingSiteLanguage( $code ) {
4308 global $wgLanguageCode;
4310 // Usually, we will only store a tiny number of fallback chains, so we
4311 // keep them in static memory.
4312 $cacheKey = "{$code}-{$wgLanguageCode}";
4314 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4315 $fallbacks = self
::getFallbacksFor( $code );
4317 // Append the site's fallback chain, including the site language itself
4318 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4319 array_unshift( $siteFallbacks, $wgLanguageCode );
4321 // Eliminate any languages already included in the chain
4322 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4324 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4326 return self
::$fallbackLanguageCache[$cacheKey];
4330 * Get all messages for a given language
4331 * WARNING: this may take a long time. If you just need all message *keys*
4332 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4334 * @param string $code
4338 public static function getMessagesFor( $code ) {
4339 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4343 * Get a message for a given language
4345 * @param string $key
4346 * @param string $code
4350 public static function getMessageFor( $key, $code ) {
4351 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4355 * Get all message keys for a given language. This is a faster alternative to
4356 * array_keys( Language::getMessagesFor( $code ) )
4359 * @param string $code Language code
4360 * @return array Array of message keys (strings)
4362 public static function getMessageKeysFor( $code ) {
4363 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4367 * @param string $talk
4370 function fixVariableInNamespace( $talk ) {
4371 if ( strpos( $talk, '$1' ) === false ) {
4375 global $wgMetaNamespace;
4376 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4378 # Allow grammar transformations
4379 # Allowing full message-style parsing would make simple requests
4380 # such as action=raw much more expensive than they need to be.
4381 # This will hopefully cover most cases.
4382 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4383 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4384 return str_replace( ' ', '_', $talk );
4391 function replaceGrammarInNamespace( $m ) {
4392 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4396 * @throws MWException
4399 static function getCaseMaps() {
4400 static $wikiUpperChars, $wikiLowerChars;
4401 if ( isset( $wikiUpperChars ) ) {
4402 return array( $wikiUpperChars, $wikiLowerChars );
4405 wfProfileIn( __METHOD__
);
4406 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4407 if ( $arr === false ) {
4408 throw new MWException(
4409 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4411 $wikiUpperChars = $arr['wikiUpperChars'];
4412 $wikiLowerChars = $arr['wikiLowerChars'];
4413 wfProfileOut( __METHOD__
);
4414 return array( $wikiUpperChars, $wikiLowerChars );
4418 * Decode an expiry (block, protection, etc) which has come from the DB
4420 * @todo FIXME: why are we returnings DBMS-dependent strings???
4422 * @param string $expiry Database expiry String
4423 * @param bool|int $format True to process using language functions, or TS_ constant
4424 * to return the expiry in a given timestamp
4428 public function formatExpiry( $expiry, $format = true ) {
4430 if ( $infinity === null ) {
4431 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4434 if ( $expiry == '' ||
$expiry == $infinity ) {
4435 return $format === true
4436 ?
$this->getMessageFromDB( 'infiniteblock' )
4439 return $format === true
4440 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4441 : wfTimestamp( $format, $expiry );
4447 * @param int|float $seconds
4448 * @param array $format Optional
4449 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4450 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4451 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4453 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4454 * or 'avoidminutes'.
4457 function formatTimePeriod( $seconds, $format = array() ) {
4458 if ( !is_array( $format ) ) {
4459 $format = array( 'avoid' => $format ); // For backwards compatibility
4461 if ( !isset( $format['avoid'] ) ) {
4462 $format['avoid'] = false;
4464 if ( !isset( $format['noabbrevs'] ) ) {
4465 $format['noabbrevs'] = false;
4467 $secondsMsg = wfMessage(
4468 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4469 $minutesMsg = wfMessage(
4470 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4471 $hoursMsg = wfMessage(
4472 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4473 $daysMsg = wfMessage(
4474 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4476 if ( round( $seconds * 10 ) < 100 ) {
4477 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4478 $s = $secondsMsg->params( $s )->text();
4479 } elseif ( round( $seconds ) < 60 ) {
4480 $s = $this->formatNum( round( $seconds ) );
4481 $s = $secondsMsg->params( $s )->text();
4482 } elseif ( round( $seconds ) < 3600 ) {
4483 $minutes = floor( $seconds / 60 );
4484 $secondsPart = round( fmod( $seconds, 60 ) );
4485 if ( $secondsPart == 60 ) {
4489 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4491 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4492 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4493 $hours = floor( $seconds / 3600 );
4494 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4495 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4496 if ( $secondsPart == 60 ) {
4500 if ( $minutes == 60 ) {
4504 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4506 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4507 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4508 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4511 $days = floor( $seconds / 86400 );
4512 if ( $format['avoid'] === 'avoidminutes' ) {
4513 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4514 if ( $hours == 24 ) {
4518 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4520 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4521 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4522 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4523 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4524 if ( $minutes == 60 ) {
4528 if ( $hours == 24 ) {
4532 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4534 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4536 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4538 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4540 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4547 * Format a bitrate for output, using an appropriate
4548 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4549 * the magnitude in question.
4551 * This use base 1000. For base 1024 use formatSize(), for another base
4552 * see formatComputingNumbers().
4557 function formatBitrate( $bps ) {
4558 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4562 * @param int $size Size of the unit
4563 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4564 * @param string $messageKey Message key to be uesd
4567 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4569 return str_replace( '$1', $this->formatNum( $size ),
4570 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4573 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4576 $maxIndex = count( $sizes ) - 1;
4577 while ( $size >= $boundary && $index < $maxIndex ) {
4582 // For small sizes no decimal places necessary
4585 // For MB and bigger two decimal places are smarter
4588 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4590 $size = round( $size, $round );
4591 $text = $this->getMessageFromDB( $msg );
4592 return str_replace( '$1', $this->formatNum( $size ), $text );
4596 * Format a size in bytes for output, using an appropriate
4597 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4599 * This method use base 1024. For base 1000 use formatBitrate(), for
4600 * another base see formatComputingNumbers()
4602 * @param int $size Size to format
4603 * @return string Plain text (not HTML)
4605 function formatSize( $size ) {
4606 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4610 * Make a list item, used by various special pages
4612 * @param string $page Page link
4613 * @param string $details Text between brackets
4614 * @param bool $oppositedm Add the direction mark opposite to your
4615 * language, to display text properly
4618 function specialList( $page, $details, $oppositedm = true ) {
4619 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4620 $this->getDirMark();
4621 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4622 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4623 return $page . $details;
4627 * Generate (prev x| next x) (20|50|100...) type links for paging
4629 * @param Title $title Title object to link
4630 * @param int $offset
4632 * @param array $query Optional URL query parameter string
4633 * @param bool $atend Optional param for specified if this is the last page
4636 public function viewPrevNext( Title
$title, $offset, $limit,
4637 array $query = array(), $atend = false
4639 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4641 # Make 'previous' link
4642 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4643 if ( $offset > 0 ) {
4644 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4645 $query, $prev, 'prevn-title', 'mw-prevlink' );
4647 $plink = htmlspecialchars( $prev );
4651 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4653 $nlink = htmlspecialchars( $next );
4655 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4656 $query, $next, 'nextn-title', 'mw-nextlink' );
4659 # Make links to set number of items per page
4660 $numLinks = array();
4661 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4662 $numLinks[] = $this->numLink( $title, $offset, $num,
4663 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4666 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4667 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4671 * Helper function for viewPrevNext() that generates links
4673 * @param Title $title Title object to link
4674 * @param int $offset
4676 * @param array $query Extra query parameters
4677 * @param string $link Text to use for the link; will be escaped
4678 * @param string $tooltipMsg Name of the message to use as tooltip
4679 * @param string $class Value of the "class" attribute of the link
4680 * @return string HTML fragment
4682 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4685 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4686 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4687 ->numParams( $limit )->text();
4689 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4690 'title' => $tooltip, 'class' => $class ), $link );
4694 * Get the conversion rule title, if any.
4698 public function getConvRuleTitle() {
4699 return $this->mConverter
->getConvRuleTitle();
4703 * Get the compiled plural rules for the language
4705 * @return array Associative array with plural form, and plural rule as key-value pairs
4707 public function getCompiledPluralRules() {
4708 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4709 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4710 if ( !$pluralRules ) {
4711 foreach ( $fallbacks as $fallbackCode ) {
4712 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4713 if ( $pluralRules ) {
4718 return $pluralRules;
4722 * Get the plural rules for the language
4724 * @return array Associative array with plural form number and plural rule as key-value pairs
4726 public function getPluralRules() {
4727 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4728 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4729 if ( !$pluralRules ) {
4730 foreach ( $fallbacks as $fallbackCode ) {
4731 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4732 if ( $pluralRules ) {
4737 return $pluralRules;
4741 * Get the plural rule types for the language
4743 * @return array Associative array with plural form number and plural rule type as key-value pairs
4745 public function getPluralRuleTypes() {
4746 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4747 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4748 if ( !$pluralRuleTypes ) {
4749 foreach ( $fallbacks as $fallbackCode ) {
4750 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4751 if ( $pluralRuleTypes ) {
4756 return $pluralRuleTypes;
4760 * Find the index number of the plural rule appropriate for the given number
4761 * @param int $number
4762 * @return int The index number of the plural rule
4764 public function getPluralRuleIndexNumber( $number ) {
4765 $pluralRules = $this->getCompiledPluralRules();
4766 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4771 * Find the plural rule type appropriate for the given number
4772 * For example, if the language is set to Arabic, getPluralType(5) should
4775 * @param int $number
4776 * @return string The name of the plural rule type, e.g. one, two, few, many
4778 public function getPluralRuleType( $number ) {
4779 $index = $this->getPluralRuleIndexNumber( $number );
4780 $pluralRuleTypes = $this->getPluralRuleTypes();
4781 if ( isset( $pluralRuleTypes[$index] ) ) {
4782 return $pluralRuleTypes[$index];