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 );
790 function getExtraUserToggles() {
791 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
798 function getUserToggle( $tog ) {
799 return $this->getMessageFromDB( "tog-$tog" );
803 * Get native language names, indexed by code.
804 * Only those defined in MediaWiki, no other data like CLDR.
805 * If $customisedOnly is true, only returns codes with a messages file
807 * @param bool $customisedOnly
810 * @deprecated since 1.20, use fetchLanguageNames()
812 public static function getLanguageNames( $customisedOnly = false ) {
813 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
817 * Get translated language names. This is done on best effort and
818 * by default this is exactly the same as Language::getLanguageNames.
819 * The CLDR extension provides translated names.
820 * @param string $code Language code.
821 * @return array Language code => language name
823 * @deprecated since 1.20, use fetchLanguageNames()
825 public static function getTranslatedLanguageNames( $code ) {
826 return self
::fetchLanguageNames( $code, 'all' );
830 * Get an array of language names, indexed by code.
831 * @param null|string $inLanguage Code of language in which to return the names
832 * Use null for autonyms (native names)
833 * @param string $include One of:
834 * 'all' all available languages
835 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
836 * 'mwfile' only if the language is in 'mw' *and* has a message file
837 * @return array Language code => language name
840 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
841 global $wgExtraLanguageNames;
842 static $coreLanguageNames;
844 if ( $coreLanguageNames === null ) {
846 include "$IP/languages/Names.php";
849 // If passed an invalid language code to use, fallback to en
850 if ( $inLanguage !== null && !Language
::isValidCode( $inLanguage ) ) {
857 # TODO: also include when $inLanguage is null, when this code is more efficient
858 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
861 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
862 foreach ( $mwNames as $mwCode => $mwName ) {
863 # - Prefer own MediaWiki native name when not using the hook
864 # - For other names just add if not added through the hook
865 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
866 $names[$mwCode] = $mwName;
870 if ( $include === 'all' ) {
875 $coreCodes = array_keys( $mwNames );
876 foreach ( $coreCodes as $coreCode ) {
877 $returnMw[$coreCode] = $names[$coreCode];
880 if ( $include === 'mwfile' ) {
881 $namesMwFile = array();
882 # We do this using a foreach over the codes instead of a directory
883 # loop so that messages files in extensions will work correctly.
884 foreach ( $returnMw as $code => $value ) {
885 if ( is_readable( self
::getMessagesFileName( $code ) )
886 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
888 $namesMwFile[$code] = $names[$code];
895 # 'mw' option; default if it's not one of the other two options (all/mwfile)
900 * @param string $code The code of the language for which to get the name
901 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
902 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
903 * @return string Language name or empty
906 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
907 $code = strtolower( $code );
908 $array = self
::fetchLanguageNames( $inLanguage, $include );
909 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
913 * Get a message from the MediaWiki namespace.
915 * @param string $msg Message name
918 function getMessageFromDB( $msg ) {
919 return wfMessage( $msg )->inLanguage( $this )->text();
923 * Get the native language name of $code.
924 * Only if defined in MediaWiki, no other data like CLDR.
925 * @param string $code
927 * @deprecated since 1.20, use fetchLanguageName()
929 function getLanguageName( $code ) {
930 return self
::fetchLanguageName( $code );
937 function getMonthName( $key ) {
938 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
944 function getMonthNamesArray() {
945 $monthNames = array( '' );
946 for ( $i = 1; $i < 13; $i++
) {
947 $monthNames[] = $this->getMonthName( $i );
956 function getMonthNameGen( $key ) {
957 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
964 function getMonthAbbreviation( $key ) {
965 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
971 function getMonthAbbreviationsArray() {
972 $monthNames = array( '' );
973 for ( $i = 1; $i < 13; $i++
) {
974 $monthNames[] = $this->getMonthAbbreviation( $i );
983 function getWeekdayName( $key ) {
984 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
991 function getWeekdayAbbreviation( $key ) {
992 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
999 function getIranianCalendarMonthName( $key ) {
1000 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1004 * @param string $key
1007 function getHebrewCalendarMonthName( $key ) {
1008 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1012 * @param string $key
1015 function getHebrewCalendarMonthNameGen( $key ) {
1016 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1020 * @param string $key
1023 function getHijriCalendarMonthName( $key ) {
1024 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1028 * Pass through result from $dateTimeObj->format()
1029 * @param DateTime|bool|null &$dateTimeObj
1031 * @param DateTimeZone|bool|null $zone
1032 * @param string $code
1035 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1036 if ( !$dateTimeObj ) {
1037 $dateTimeObj = DateTime
::createFromFormat(
1038 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1041 return $dateTimeObj->format( $code );
1045 * This is a workalike of PHP's date() function, but with better
1046 * internationalisation, a reduced set of format characters, and a better
1049 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1050 * the PHP manual for definitions. There are a number of extensions, which
1053 * xn Do not translate digits of the next numeric format character
1054 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1055 * xr Use roman numerals for the next numeric format character
1056 * xh Use hebrew numerals for the next numeric format character
1058 * xg Genitive month name
1060 * xij j (day number) in Iranian calendar
1061 * xiF F (month name) in Iranian calendar
1062 * xin n (month number) in Iranian calendar
1063 * xiy y (two digit year) in Iranian calendar
1064 * xiY Y (full year) in Iranian calendar
1066 * xjj j (day number) in Hebrew calendar
1067 * xjF F (month name) in Hebrew calendar
1068 * xjt t (days in month) in Hebrew calendar
1069 * xjx xg (genitive month name) in Hebrew calendar
1070 * xjn n (month number) in Hebrew calendar
1071 * xjY Y (full year) in Hebrew calendar
1073 * xmj j (day number) in Hijri calendar
1074 * xmF F (month name) in Hijri calendar
1075 * xmn n (month number) in Hijri calendar
1076 * xmY Y (full year) in Hijri calendar
1078 * xkY Y (full year) in Thai solar calendar. Months and days are
1079 * identical to the Gregorian calendar
1080 * xoY Y (full year) in Minguo calendar or Juche year.
1081 * Months and days are identical to the
1082 * Gregorian calendar
1083 * xtY Y (full year) in Japanese nengo. Months and days are
1084 * identical to the Gregorian calendar
1086 * Characters enclosed in double quotes will be considered literal (with
1087 * the quotes themselves removed). Unmatched quotes will be considered
1088 * literal quotes. Example:
1090 * "The month is" F => The month is January
1093 * Backslash escaping is also supported.
1095 * Input timestamp is assumed to be pre-normalized to the desired local
1096 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1097 * $ts is UTC if $zone is not given.
1099 * @param string $format
1100 * @param string $ts 14-character timestamp
1103 * @param DateTimeZone $zone Timezone of $ts
1104 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1105 * Only makes sense if $ts is the current time.
1106 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1108 * @throws MWException
1111 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1116 $dateTimeObj = false;
1125 $usedSecond = false;
1126 $usedMinute = false;
1133 $usedISOYear = false;
1134 $usedIsLeapYear = false;
1136 $usedHebrewMonth = false;
1137 $usedIranianMonth = false;
1138 $usedHijriMonth = false;
1139 $usedHebrewYear = false;
1140 $usedIranianYear = false;
1141 $usedHijriYear = false;
1142 $usedTennoYear = false;
1144 if ( strlen( $ts ) !== 14 ) {
1145 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1148 if ( !ctype_digit( $ts ) ) {
1149 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1152 $formatLength = strlen( $format );
1153 for ( $p = 0; $p < $formatLength; $p++
) {
1155 $code = $format[$p];
1156 if ( $code == 'x' && $p < $formatLength - 1 ) {
1157 $code .= $format[++
$p];
1160 if ( ( $code === 'xi'
1166 && $p < $formatLength - 1 ) {
1167 $code .= $format[++
$p];
1178 $rawToggle = !$rawToggle;
1188 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1191 $usedHebrewMonth = true;
1193 $hebrew = self
::tsToHebrew( $ts );
1195 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1199 $num = substr( $ts, 6, 2 );
1203 $s .= $this->getWeekdayAbbreviation( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1207 $num = intval( substr( $ts, 6, 2 ) );
1212 $iranian = self
::tsToIranian( $ts );
1219 $hijri = self
::tsToHijri( $ts );
1226 $hebrew = self
::tsToHebrew( $ts );
1232 $s .= $this->getWeekdayName( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1236 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1239 $usedIranianMonth = true;
1241 $iranian = self
::tsToIranian( $ts );
1243 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1246 $usedHijriMonth = true;
1248 $hijri = self
::tsToHijri( $ts );
1250 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1253 $usedHebrewMonth = true;
1255 $hebrew = self
::tsToHebrew( $ts );
1257 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1261 $num = substr( $ts, 4, 2 );
1265 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1269 $num = intval( substr( $ts, 4, 2 ) );
1272 $usedIranianMonth = true;
1274 $iranian = self
::tsToIranian( $ts );
1279 $usedHijriMonth = true;
1281 $hijri = self
::tsToHijri ( $ts );
1286 $usedHebrewMonth = true;
1288 $hebrew = self
::tsToHebrew( $ts );
1293 $usedHebrewMonth = true;
1295 $hebrew = self
::tsToHebrew( $ts );
1301 $num = substr( $ts, 0, 4 );
1304 $usedIranianYear = true;
1306 $iranian = self
::tsToIranian( $ts );
1311 $usedHijriYear = true;
1313 $hijri = self
::tsToHijri( $ts );
1318 $usedHebrewYear = true;
1320 $hebrew = self
::tsToHebrew( $ts );
1327 $thai = self
::tsToYear( $ts, 'thai' );
1334 $minguo = self
::tsToYear( $ts, 'minguo' );
1339 $usedTennoYear = true;
1341 $tenno = self
::tsToYear( $ts, 'tenno' );
1347 $num = substr( $ts, 2, 2 );
1350 $usedIranianYear = true;
1352 $iranian = self
::tsToIranian( $ts );
1354 $num = substr( $iranian[0], -2 );
1358 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1362 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1366 $h = substr( $ts, 8, 2 );
1367 $num = $h %
12 ?
$h %
12 : 12;
1371 $num = intval( substr( $ts, 8, 2 ) );
1375 $h = substr( $ts, 8, 2 );
1376 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1380 $num = substr( $ts, 8, 2 );
1384 $num = substr( $ts, 10, 2 );
1388 $num = substr( $ts, 12, 2 );
1398 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1404 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1408 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1412 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1415 $usedIsLeapYear = true;
1416 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1419 $usedISOYear = true;
1420 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1427 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1430 # Backslash escaping
1431 if ( $p < $formatLength - 1 ) {
1432 $s .= $format[++
$p];
1439 if ( $p < $formatLength - 1 ) {
1440 $endQuote = strpos( $format, '"', $p +
1 );
1441 if ( $endQuote === false ) {
1442 # No terminating quote, assume literal "
1445 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1449 # Quote at end of string, assume literal "
1456 if ( $num !== false ) {
1457 if ( $rawToggle ||
$raw ) {
1460 } elseif ( $roman ) {
1461 $s .= Language
::romanNumeral( $num );
1463 } elseif ( $hebrewNum ) {
1464 $s .= self
::hebrewNumeral( $num );
1467 $s .= $this->formatNum( $num, true );
1472 if ( $usedSecond ) {
1474 } elseif ( $usedMinute ) {
1475 $ttl = 60 - substr( $ts, 12, 2 );
1476 } elseif ( $usedHour ) {
1477 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1478 } elseif ( $usedAMPM ) {
1479 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1480 } elseif ( $usedDay ||
$usedHebrewMonth ||
$usedIranianMonth ||
$usedHijriMonth ||
$usedHebrewYear ||
$usedIranianYear ||
$usedHijriYear ||
$usedTennoYear ) {
1481 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1482 // so that they don't need purged every day.
1483 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1485 $possibleTtls = array();
1486 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1488 $possibleTtls[] = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1489 } elseif ( $usedISOYear ) {
1490 // December 28th falls on the last ISO week of the year, every year.
1491 // The last ISO week of a year can be 52 or 53.
1492 $lastWeekOfISOYear = DateTime
::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?
: new DateTimeZone( 'UTC' ) )->format( 'W' );
1493 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1494 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1495 $timeRemainingInWeek = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1496 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1500 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 +
$timeRemainingInDay;
1501 } elseif ( $usedYear ) {
1502 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1503 +
$timeRemainingInDay;
1504 } elseif ( $usedIsLeapYear ) {
1505 $year = substr( $ts, 0, 4 );
1506 $timeRemainingInYear = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1507 +
$timeRemainingInDay;
1509 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1510 // this isn't a leap year. see when the next one starts
1511 $nextCandidate = $year - $mod +
4;
1512 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1513 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
$timeRemainingInYear;
1515 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
$timeRemainingInYear;
1518 // this is a leap year, so the next year isn't
1519 $possibleTtls[] = $timeRemainingInYear;
1523 if ( $possibleTtls ) {
1524 $ttl = min( $possibleTtls );
1531 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1532 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1535 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1536 * Gregorian dates to Iranian dates. Originally written in C, it
1537 * is released under the terms of GNU Lesser General Public
1538 * License. Conversion to PHP was performed by Niklas Laxström.
1540 * Link: http://www.farsiweb.info/jalali/jalali.c
1546 private static function tsToIranian( $ts ) {
1547 $gy = substr( $ts, 0, 4 ) -1600;
1548 $gm = substr( $ts, 4, 2 ) -1;
1549 $gd = substr( $ts, 6, 2 ) -1;
1551 # Days passed from the beginning (including leap years)
1553 +
floor( ( $gy +
3 ) / 4 )
1554 - floor( ( $gy +
99 ) / 100 )
1555 +
floor( ( $gy +
399 ) / 400 );
1557 // Add days of the past months of this year
1558 for ( $i = 0; $i < $gm; $i++
) {
1559 $gDayNo +
= self
::$GREG_DAYS[$i];
1563 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1567 // Days passed in current month
1568 $gDayNo +
= (int)$gd;
1570 $jDayNo = $gDayNo - 79;
1572 $jNp = floor( $jDayNo / 12053 );
1575 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1578 if ( $jDayNo >= 366 ) {
1579 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1580 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1583 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1584 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1590 return array( $jy, $jm, $jd );
1594 * Converting Gregorian dates to Hijri dates.
1596 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1598 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1604 private static function tsToHijri( $ts ) {
1605 $year = substr( $ts, 0, 4 );
1606 $month = substr( $ts, 4, 2 );
1607 $day = substr( $ts, 6, 2 );
1615 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1616 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1618 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1619 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1620 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1623 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1624 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1627 $zl = $zjd -1948440 +
10632;
1628 $zn = (int)( ( $zl - 1 ) / 10631 );
1629 $zl = $zl - 10631 * $zn +
354;
1630 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1631 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1632 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1633 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1634 $zm = (int)( ( 24 * $zl ) / 709 );
1635 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1636 $zy = 30 * $zn +
$zj - 30;
1638 return array( $zy, $zm, $zd );
1642 * Converting Gregorian dates to Hebrew dates.
1644 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1645 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1646 * to translate the relevant functions into PHP and release them under
1649 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1650 * and Adar II is 14. In a non-leap year, Adar is 6.
1656 private static function tsToHebrew( $ts ) {
1658 $year = substr( $ts, 0, 4 );
1659 $month = substr( $ts, 4, 2 );
1660 $day = substr( $ts, 6, 2 );
1662 # Calculate Hebrew year
1663 $hebrewYear = $year +
3760;
1665 # Month number when September = 1, August = 12
1667 if ( $month > 12 ) {
1674 # Calculate day of year from 1 September
1676 for ( $i = 1; $i < $month; $i++
) {
1680 # Check if the year is leap
1681 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1684 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1691 # Calculate the start of the Hebrew year
1692 $start = self
::hebrewYearStart( $hebrewYear );
1694 # Calculate next year's start
1695 if ( $dayOfYear <= $start ) {
1696 # Day is before the start of the year - it is the previous year
1698 $nextStart = $start;
1702 # Add days since previous year's 1 September
1704 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1708 # Start of the new (previous) year
1709 $start = self
::hebrewYearStart( $hebrewYear );
1712 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1715 # Calculate Hebrew day of year
1716 $hebrewDayOfYear = $dayOfYear - $start;
1718 # Difference between year's days
1719 $diff = $nextStart - $start;
1720 # Add 12 (or 13 for leap years) days to ignore the difference between
1721 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1722 # difference is only about the year type
1723 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1729 # Check the year pattern, and is leap year
1730 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1731 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1732 # and non-leap years
1733 $yearPattern = $diff %
30;
1734 # Check if leap year
1735 $isLeap = $diff >= 30;
1737 # Calculate day in the month from number of day in the Hebrew year
1738 # Don't check Adar - if the day is not in Adar, we will stop before;
1739 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1740 $hebrewDay = $hebrewDayOfYear;
1743 while ( $hebrewMonth <= 12 ) {
1744 # Calculate days in this month
1745 if ( $isLeap && $hebrewMonth == 6 ) {
1746 # Adar in a leap year
1748 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1750 if ( $hebrewDay <= $days ) {
1754 # Subtract the days of Adar I
1755 $hebrewDay -= $days;
1758 if ( $hebrewDay <= $days ) {
1764 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1765 # Cheshvan in a complete year (otherwise as the rule below)
1767 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1768 # Kislev in an incomplete year (otherwise as the rule below)
1771 # Odd months have 30 days, even have 29
1772 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1774 if ( $hebrewDay <= $days ) {
1775 # In the current month
1778 # Subtract the days of the current month
1779 $hebrewDay -= $days;
1780 # Try in the next month
1785 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1789 * This calculates the Hebrew year start, as days since 1 September.
1790 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1791 * Used for Hebrew date.
1797 private static function hebrewYearStart( $year ) {
1798 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1799 $b = intval( ( $year - 1 ) %
4 );
1800 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1804 $Mar = intval( $m );
1810 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1811 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1813 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1815 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1819 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1824 * Algorithm to convert Gregorian dates to Thai solar dates,
1825 * Minguo dates or Minguo dates.
1827 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1828 * http://en.wikipedia.org/wiki/Minguo_calendar
1829 * http://en.wikipedia.org/wiki/Japanese_era_name
1831 * @param string $ts 14-character timestamp
1832 * @param string $cName Calender name
1833 * @return array Converted year, month, day
1835 private static function tsToYear( $ts, $cName ) {
1836 $gy = substr( $ts, 0, 4 );
1837 $gm = substr( $ts, 4, 2 );
1838 $gd = substr( $ts, 6, 2 );
1840 if ( !strcmp( $cName, 'thai' ) ) {
1842 # Add 543 years to the Gregorian calendar
1843 # Months and days are identical
1844 $gy_offset = $gy +
543;
1845 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1847 # Deduct 1911 years from the Gregorian calendar
1848 # Months and days are identical
1849 $gy_offset = $gy - 1911;
1850 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1851 # Nengō dates up to Meiji period
1852 # Deduct years from the Gregorian calendar
1853 # depending on the nengo periods
1854 # Months and days are identical
1856 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1857 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1860 $gy_gannen = $gy - 1868 +
1;
1861 $gy_offset = $gy_gannen;
1862 if ( $gy_gannen == 1 ) {
1865 $gy_offset = '明治' . $gy_offset;
1867 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1868 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1869 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1870 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1871 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1874 $gy_gannen = $gy - 1912 +
1;
1875 $gy_offset = $gy_gannen;
1876 if ( $gy_gannen == 1 ) {
1879 $gy_offset = '大正' . $gy_offset;
1881 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1882 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1883 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1886 $gy_gannen = $gy - 1926 +
1;
1887 $gy_offset = $gy_gannen;
1888 if ( $gy_gannen == 1 ) {
1891 $gy_offset = '昭和' . $gy_offset;
1894 $gy_gannen = $gy - 1989 +
1;
1895 $gy_offset = $gy_gannen;
1896 if ( $gy_gannen == 1 ) {
1899 $gy_offset = '平成' . $gy_offset;
1905 return array( $gy_offset, $gm, $gd );
1909 * Roman number formatting up to 10000
1915 static function romanNumeral( $num ) {
1916 static $table = array(
1917 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1918 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1919 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1920 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1921 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1924 $num = intval( $num );
1925 if ( $num > 10000 ||
$num <= 0 ) {
1930 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1931 if ( $num >= $pow10 ) {
1932 $s .= $table[$i][(int)floor( $num / $pow10 )];
1934 $num = $num %
$pow10;
1940 * Hebrew Gematria number formatting up to 9999
1946 static function hebrewNumeral( $num ) {
1947 static $table = array(
1948 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1949 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1950 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1951 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1954 $num = intval( $num );
1955 if ( $num > 9999 ||
$num <= 0 ) {
1960 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1961 if ( $num >= $pow10 ) {
1962 if ( $num == 15 ||
$num == 16 ) {
1963 $s .= $table[0][9] . $table[0][$num - 9];
1966 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1967 if ( $pow10 == 1000 ) {
1972 $num = $num %
$pow10;
1974 if ( strlen( $s ) == 2 ) {
1977 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1978 $str .= substr( $s, strlen( $s ) - 2, 2 );
1980 $start = substr( $str, 0, strlen( $str ) - 2 );
1981 $end = substr( $str, strlen( $str ) - 2 );
1984 $str = $start . 'ך';
1987 $str = $start . 'ם';
1990 $str = $start . 'ן';
1993 $str = $start . 'ף';
1996 $str = $start . 'ץ';
2003 * Used by date() and time() to adjust the time output.
2005 * @param string $ts The time in date('YmdHis') format
2006 * @param mixed $tz Adjust the time by this amount (default false, mean we
2007 * get user timecorrection setting)
2010 function userAdjust( $ts, $tz = false ) {
2011 global $wgUser, $wgLocalTZoffset;
2013 if ( $tz === false ) {
2014 $tz = $wgUser->getOption( 'timecorrection' );
2017 $data = explode( '|', $tz, 3 );
2019 if ( $data[0] == 'ZoneInfo' ) {
2020 wfSuppressWarnings();
2021 $userTZ = timezone_open( $data[2] );
2022 wfRestoreWarnings();
2023 if ( $userTZ !== false ) {
2024 $date = date_create( $ts, timezone_open( 'UTC' ) );
2025 date_timezone_set( $date, $userTZ );
2026 $date = date_format( $date, 'YmdHis' );
2029 # Unrecognized timezone, default to 'Offset' with the stored offset.
2030 $data[0] = 'Offset';
2033 if ( $data[0] == 'System' ||
$tz == '' ) {
2034 # Global offset in minutes.
2035 $minDiff = $wgLocalTZoffset;
2036 } elseif ( $data[0] == 'Offset' ) {
2037 $minDiff = intval( $data[1] );
2039 $data = explode( ':', $tz );
2040 if ( count( $data ) == 2 ) {
2041 $data[0] = intval( $data[0] );
2042 $data[1] = intval( $data[1] );
2043 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2044 if ( $data[0] < 0 ) {
2045 $minDiff = -$minDiff;
2048 $minDiff = intval( $data[0] ) * 60;
2052 # No difference ? Return time unchanged
2053 if ( 0 == $minDiff ) {
2057 wfSuppressWarnings(); // E_STRICT system time bitching
2058 # Generate an adjusted date; take advantage of the fact that mktime
2059 # will normalize out-of-range values so we don't have to split $minDiff
2060 # into hours and minutes.
2062 (int)substr( $ts, 8, 2 ) ), # Hours
2063 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2064 (int)substr( $ts, 12, 2 ), # Seconds
2065 (int)substr( $ts, 4, 2 ), # Month
2066 (int)substr( $ts, 6, 2 ), # Day
2067 (int)substr( $ts, 0, 4 ) ); # Year
2069 $date = date( 'YmdHis', $t );
2070 wfRestoreWarnings();
2076 * This is meant to be used by time(), date(), and timeanddate() to get
2077 * the date preference they're supposed to use, it should be used in
2081 * function timeanddate([...], $format = true) {
2082 * $datePreference = $this->dateFormat($format);
2087 * @param int|string|bool $usePrefs If true, the user's preference is used
2088 * if false, the site/language default is used
2089 * if int/string, assumed to be a format.
2092 function dateFormat( $usePrefs = true ) {
2095 if ( is_bool( $usePrefs ) ) {
2097 $datePreference = $wgUser->getDatePreference();
2099 $datePreference = (string)User
::getDefaultOption( 'date' );
2102 $datePreference = (string)$usePrefs;
2106 if ( $datePreference == '' ) {
2110 return $datePreference;
2114 * Get a format string for a given type and preference
2115 * @param string $type May be date, time or both
2116 * @param string $pref The format name as it appears in Messages*.php
2118 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2122 function getDateFormatString( $type, $pref ) {
2123 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2124 if ( $pref == 'default' ) {
2125 $pref = $this->getDefaultDateFormat();
2126 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2128 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2130 if ( $type === 'pretty' && $df === null ) {
2131 $df = $this->getDateFormatString( 'date', $pref );
2134 if ( $df === null ) {
2135 $pref = $this->getDefaultDateFormat();
2136 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2139 $this->dateFormatStrings
[$type][$pref] = $df;
2141 return $this->dateFormatStrings
[$type][$pref];
2145 * @param string $ts The time format which needs to be turned into a
2146 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2147 * @param bool $adj Whether to adjust the time output according to the
2148 * user configured offset ($timecorrection)
2149 * @param mixed $format True to use user's date format preference
2150 * @param string|bool $timecorrection The time offset as returned by
2151 * validateTimeZone() in Special:Preferences
2154 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2155 $ts = wfTimestamp( TS_MW
, $ts );
2157 $ts = $this->userAdjust( $ts, $timecorrection );
2159 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2160 return $this->sprintfDate( $df, $ts );
2164 * @param string $ts The time format which needs to be turned into a
2165 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2166 * @param bool $adj Whether to adjust the time output according to the
2167 * user configured offset ($timecorrection)
2168 * @param mixed $format True to use user's date format preference
2169 * @param string|bool $timecorrection The time offset as returned by
2170 * validateTimeZone() in Special:Preferences
2173 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2174 $ts = wfTimestamp( TS_MW
, $ts );
2176 $ts = $this->userAdjust( $ts, $timecorrection );
2178 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2179 return $this->sprintfDate( $df, $ts );
2183 * @param string $ts The time format which needs to be turned into a
2184 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2185 * @param bool $adj Whether to adjust the time output according to the
2186 * user configured offset ($timecorrection)
2187 * @param mixed $format What format to return, if it's false output the
2188 * default one (default true)
2189 * @param string|bool $timecorrection The time offset as returned by
2190 * validateTimeZone() in Special:Preferences
2193 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2194 $ts = wfTimestamp( TS_MW
, $ts );
2196 $ts = $this->userAdjust( $ts, $timecorrection );
2198 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2199 return $this->sprintfDate( $df, $ts );
2203 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2207 * @param int $seconds The amount of seconds.
2208 * @param array $chosenIntervals The intervals to enable.
2212 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2213 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2215 $segments = array();
2217 foreach ( $intervals as $intervalName => $intervalValue ) {
2218 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2219 // duration-years, duration-decades, duration-centuries, duration-millennia
2220 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2221 $segments[] = $message->inLanguage( $this )->escaped();
2224 return $this->listToText( $segments );
2228 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2229 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2233 * @param int $seconds The amount of seconds.
2234 * @param array $chosenIntervals The intervals to enable.
2238 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2239 if ( empty( $chosenIntervals ) ) {
2240 $chosenIntervals = array(
2252 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2253 $sortedNames = array_keys( $intervals );
2254 $smallestInterval = array_pop( $sortedNames );
2256 $segments = array();
2258 foreach ( $intervals as $name => $length ) {
2259 $value = floor( $seconds / $length );
2261 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2262 $seconds -= $value * $length;
2263 $segments[$name] = $value;
2271 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2273 * @param string $type Can be 'date', 'time' or 'both'
2274 * @param string $ts The time format which needs to be turned into a
2275 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2276 * @param User $user User object used to get preferences for timezone and format
2277 * @param array $options Array, can contain the following keys:
2278 * - 'timecorrection': time correction, can have the following values:
2279 * - true: use user's preference
2280 * - false: don't use time correction
2281 * - int: value of time correction in minutes
2282 * - 'format': format to use, can have the following values:
2283 * - true: use user's preference
2284 * - false: use default preference
2285 * - string: format to use
2289 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2290 $ts = wfTimestamp( TS_MW
, $ts );
2291 $options +
= array( 'timecorrection' => true, 'format' => true );
2292 if ( $options['timecorrection'] !== false ) {
2293 if ( $options['timecorrection'] === true ) {
2294 $offset = $user->getOption( 'timecorrection' );
2296 $offset = $options['timecorrection'];
2298 $ts = $this->userAdjust( $ts, $offset );
2300 if ( $options['format'] === true ) {
2301 $format = $user->getDatePreference();
2303 $format = $options['format'];
2305 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2306 return $this->sprintfDate( $df, $ts );
2310 * Get the formatted date for the given timestamp and formatted for
2313 * @param mixed $ts Mixed: the time format which needs to be turned into a
2314 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2315 * @param User $user User object used to get preferences for timezone and format
2316 * @param array $options Array, can contain the following keys:
2317 * - 'timecorrection': time correction, can have the following values:
2318 * - true: use user's preference
2319 * - false: don't use time correction
2320 * - int: value of time correction in minutes
2321 * - 'format': format to use, can have the following values:
2322 * - true: use user's preference
2323 * - false: use default preference
2324 * - string: format to use
2328 public function userDate( $ts, User
$user, array $options = array() ) {
2329 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2333 * Get the formatted time for the given timestamp and formatted for
2336 * @param mixed $ts The time format which needs to be turned into a
2337 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2338 * @param User $user User object used to get preferences for timezone and format
2339 * @param array $options Array, can contain the following keys:
2340 * - 'timecorrection': time correction, can have the following values:
2341 * - true: use user's preference
2342 * - false: don't use time correction
2343 * - int: value of time correction in minutes
2344 * - 'format': format to use, can have the following values:
2345 * - true: use user's preference
2346 * - false: use default preference
2347 * - string: format to use
2351 public function userTime( $ts, User
$user, array $options = array() ) {
2352 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2356 * Get the formatted date and time for the given timestamp and formatted for
2359 * @param mixed $ts The time format which needs to be turned into a
2360 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2361 * @param User $user User object used to get preferences for timezone and format
2362 * @param array $options Array, can contain the following keys:
2363 * - 'timecorrection': time correction, can have the following values:
2364 * - true: use user's preference
2365 * - false: don't use time correction
2366 * - int: value of time correction in minutes
2367 * - 'format': format to use, can have the following values:
2368 * - true: use user's preference
2369 * - false: use default preference
2370 * - string: format to use
2374 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2375 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2379 * Convert an MWTimestamp into a pretty human-readable timestamp using
2380 * the given user preferences and relative base time.
2382 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2383 * on your timestamp object, which will then call this function. Calling
2384 * this function directly will cause hooks to be skipped over.
2386 * @see MWTimestamp::getHumanTimestamp
2387 * @param MWTimestamp $ts Timestamp to prettify
2388 * @param MWTimestamp $relativeTo Base timestamp
2389 * @param User $user User preferences to use
2390 * @return string Human timestamp
2393 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2394 $diff = $ts->diff( $relativeTo );
2395 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2396 (int)$relativeTo->timestamp
->format( 'w' ) );
2397 $days = $diff->days ?
: (int)$diffDay;
2398 if ( $diff->invert ||
$days > 5
2399 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2401 // Timestamps are in different years: use full timestamp
2402 // Also do full timestamp for future dates
2404 * @todo FIXME: Add better handling of future timestamps.
2406 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2407 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2408 } elseif ( $days > 5 ) {
2409 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2410 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2411 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2412 } elseif ( $days > 1 ) {
2413 // Timestamp within the past week: show the day of the week and time
2414 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2415 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2417 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2418 $ts = wfMessage( "$weekday-at" )
2419 ->inLanguage( $this )
2420 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2422 } elseif ( $days == 1 ) {
2423 // Timestamp was yesterday: say 'yesterday' and the time.
2424 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2425 $ts = wfMessage( 'yesterday-at' )
2426 ->inLanguage( $this )
2427 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2429 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2430 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2431 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2432 $ts = wfMessage( 'today-at' )
2433 ->inLanguage( $this )
2434 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2437 // From here on in, the timestamp was soon enough ago so that we can simply say
2438 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2439 } elseif ( $diff->h
== 1 ) {
2440 // Less than 90 minutes, but more than an hour ago.
2441 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2442 } elseif ( $diff->i
>= 1 ) {
2443 // A few minutes ago.
2444 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2445 } elseif ( $diff->s
>= 30 ) {
2446 // Less than a minute, but more than 30 sec ago.
2447 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2449 // Less than 30 seconds ago.
2450 $ts = wfMessage( 'just-now' )->text();
2457 * @param string $key
2458 * @return array|null
2460 function getMessage( $key ) {
2461 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2467 function getAllMessages() {
2468 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2473 * @param string $out
2474 * @param string $string
2477 function iconv( $in, $out, $string ) {
2478 # This is a wrapper for iconv in all languages except esperanto,
2479 # which does some nasty x-conversions beforehand
2481 # Even with //IGNORE iconv can whine about illegal characters in
2482 # *input* string. We just ignore those too.
2483 # REF: http://bugs.php.net/bug.php?id=37166
2484 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2485 wfSuppressWarnings();
2486 $text = iconv( $in, $out . '//IGNORE', $string );
2487 wfRestoreWarnings();
2491 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2494 * @param array $matches
2495 * @return mixed|string
2497 function ucwordbreaksCallbackAscii( $matches ) {
2498 return $this->ucfirst( $matches[1] );
2502 * @param array $matches
2505 function ucwordbreaksCallbackMB( $matches ) {
2506 return mb_strtoupper( $matches[0] );
2510 * @param array $matches
2513 function ucCallback( $matches ) {
2514 list( $wikiUpperChars ) = self
::getCaseMaps();
2515 return strtr( $matches[1], $wikiUpperChars );
2519 * @param array $matches
2522 function lcCallback( $matches ) {
2523 list( , $wikiLowerChars ) = self
::getCaseMaps();
2524 return strtr( $matches[1], $wikiLowerChars );
2528 * @param array $matches
2531 function ucwordsCallbackMB( $matches ) {
2532 return mb_strtoupper( $matches[0] );
2536 * @param array $matches
2539 function ucwordsCallbackWiki( $matches ) {
2540 list( $wikiUpperChars ) = self
::getCaseMaps();
2541 return strtr( $matches[0], $wikiUpperChars );
2545 * Make a string's first character uppercase
2547 * @param string $str
2551 function ucfirst( $str ) {
2553 if ( $o < 96 ) { // if already uppercase...
2555 } elseif ( $o < 128 ) {
2556 return ucfirst( $str ); // use PHP's ucfirst()
2558 // fall back to more complex logic in case of multibyte strings
2559 return $this->uc( $str, true );
2564 * Convert a string to uppercase
2566 * @param string $str
2567 * @param bool $first
2571 function uc( $str, $first = false ) {
2572 if ( function_exists( 'mb_strtoupper' ) ) {
2574 if ( $this->isMultibyte( $str ) ) {
2575 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2577 return ucfirst( $str );
2580 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2583 if ( $this->isMultibyte( $str ) ) {
2584 $x = $first ?
'^' : '';
2585 return preg_replace_callback(
2586 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2587 array( $this, 'ucCallback' ),
2591 return $first ?
ucfirst( $str ) : strtoupper( $str );
2597 * @param string $str
2598 * @return mixed|string
2600 function lcfirst( $str ) {
2603 return strval( $str );
2604 } elseif ( $o >= 128 ) {
2605 return $this->lc( $str, true );
2606 } elseif ( $o > 96 ) {
2609 $str[0] = strtolower( $str[0] );
2615 * @param string $str
2616 * @param bool $first
2617 * @return mixed|string
2619 function lc( $str, $first = false ) {
2620 if ( function_exists( 'mb_strtolower' ) ) {
2622 if ( $this->isMultibyte( $str ) ) {
2623 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2625 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2628 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2631 if ( $this->isMultibyte( $str ) ) {
2632 $x = $first ?
'^' : '';
2633 return preg_replace_callback(
2634 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2635 array( $this, 'lcCallback' ),
2639 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2645 * @param string $str
2648 function isMultibyte( $str ) {
2649 return (bool)preg_match( '/[\x80-\xff]/', $str );
2653 * @param string $str
2654 * @return mixed|string
2656 function ucwords( $str ) {
2657 if ( $this->isMultibyte( $str ) ) {
2658 $str = $this->lc( $str );
2660 // regexp to find first letter in each word (i.e. after each space)
2661 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2663 // function to use to capitalize a single char
2664 if ( function_exists( 'mb_strtoupper' ) ) {
2665 return preg_replace_callback(
2667 array( $this, 'ucwordsCallbackMB' ),
2671 return preg_replace_callback(
2673 array( $this, 'ucwordsCallbackWiki' ),
2678 return ucwords( strtolower( $str ) );
2683 * capitalize words at word breaks
2685 * @param string $str
2688 function ucwordbreaks( $str ) {
2689 if ( $this->isMultibyte( $str ) ) {
2690 $str = $this->lc( $str );
2692 // since \b doesn't work for UTF-8, we explicitely define word break chars
2693 $breaks = "[ \-\(\)\}\{\.,\?!]";
2695 // find first letter after word break
2696 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2697 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2699 if ( function_exists( 'mb_strtoupper' ) ) {
2700 return preg_replace_callback(
2702 array( $this, 'ucwordbreaksCallbackMB' ),
2706 return preg_replace_callback(
2708 array( $this, 'ucwordsCallbackWiki' ),
2713 return preg_replace_callback(
2714 '/\b([\w\x80-\xff]+)\b/',
2715 array( $this, 'ucwordbreaksCallbackAscii' ),
2722 * Return a case-folded representation of $s
2724 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2725 * and $s2 are the same except for the case of their characters. It is not
2726 * necessary for the value returned to make sense when displayed.
2728 * Do *not* perform any other normalisation in this function. If a caller
2729 * uses this function when it should be using a more general normalisation
2730 * function, then fix the caller.
2736 function caseFold( $s ) {
2737 return $this->uc( $s );
2744 function checkTitleEncoding( $s ) {
2745 if ( is_array( $s ) ) {
2746 throw new MWException( 'Given array to checkTitleEncoding.' );
2748 if ( StringUtils
::isUtf8( $s ) ) {
2752 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2758 function fallback8bitEncoding() {
2759 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2763 * Most writing systems use whitespace to break up words.
2764 * Some languages such as Chinese don't conventionally do this,
2765 * which requires special handling when breaking up words for
2770 function hasWordBreaks() {
2775 * Some languages such as Chinese require word segmentation,
2776 * Specify such segmentation when overridden in derived class.
2778 * @param string $string
2781 function segmentByWord( $string ) {
2786 * Some languages have special punctuation need to be normalized.
2787 * Make such changes here.
2789 * @param string $string
2792 function normalizeForSearch( $string ) {
2793 return self
::convertDoubleWidth( $string );
2797 * convert double-width roman characters to single-width.
2798 * range: ff00-ff5f ~= 0020-007f
2800 * @param string $string
2804 protected static function convertDoubleWidth( $string ) {
2805 static $full = null;
2806 static $half = null;
2808 if ( $full === null ) {
2809 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2810 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2811 $full = str_split( $fullWidth, 3 );
2812 $half = str_split( $halfWidth );
2815 $string = str_replace( $full, $half, $string );
2820 * @param string $string
2821 * @param string $pattern
2824 protected static function insertSpace( $string, $pattern ) {
2825 $string = preg_replace( $pattern, " $1 ", $string );
2826 $string = preg_replace( '/ +/', ' ', $string );
2831 * @param array $termsArray
2834 function convertForSearchResult( $termsArray ) {
2835 # some languages, e.g. Chinese, need to do a conversion
2836 # in order for search results to be displayed correctly
2841 * Get the first character of a string.
2846 function firstChar( $s ) {
2849 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2850 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2855 if ( isset( $matches[1] ) ) {
2856 if ( strlen( $matches[1] ) != 3 ) {
2860 // Break down Hangul syllables to grab the first jamo
2861 $code = utf8ToCodepoint( $matches[1] );
2862 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2864 } elseif ( $code < 0xb098 ) {
2865 return "\xe3\x84\xb1";
2866 } elseif ( $code < 0xb2e4 ) {
2867 return "\xe3\x84\xb4";
2868 } elseif ( $code < 0xb77c ) {
2869 return "\xe3\x84\xb7";
2870 } elseif ( $code < 0xb9c8 ) {
2871 return "\xe3\x84\xb9";
2872 } elseif ( $code < 0xbc14 ) {
2873 return "\xe3\x85\x81";
2874 } elseif ( $code < 0xc0ac ) {
2875 return "\xe3\x85\x82";
2876 } elseif ( $code < 0xc544 ) {
2877 return "\xe3\x85\x85";
2878 } elseif ( $code < 0xc790 ) {
2879 return "\xe3\x85\x87";
2880 } elseif ( $code < 0xcc28 ) {
2881 return "\xe3\x85\x88";
2882 } elseif ( $code < 0xce74 ) {
2883 return "\xe3\x85\x8a";
2884 } elseif ( $code < 0xd0c0 ) {
2885 return "\xe3\x85\x8b";
2886 } elseif ( $code < 0xd30c ) {
2887 return "\xe3\x85\x8c";
2888 } elseif ( $code < 0xd558 ) {
2889 return "\xe3\x85\x8d";
2891 return "\xe3\x85\x8e";
2898 function initEncoding() {
2899 # Some languages may have an alternate char encoding option
2900 # (Esperanto X-coding, Japanese furigana conversion, etc)
2901 # If this language is used as the primary content language,
2902 # an override to the defaults can be set here on startup.
2909 function recodeForEdit( $s ) {
2910 # For some languages we'll want to explicitly specify
2911 # which characters make it into the edit box raw
2912 # or are converted in some way or another.
2913 global $wgEditEncoding;
2914 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2917 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2925 function recodeInput( $s ) {
2926 # Take the previous into account.
2927 global $wgEditEncoding;
2928 if ( $wgEditEncoding != '' ) {
2929 $enc = $wgEditEncoding;
2933 if ( $enc == 'UTF-8' ) {
2936 return $this->iconv( $enc, 'UTF-8', $s );
2941 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2942 * also cleans up certain backwards-compatible sequences, converting them
2943 * to the modern Unicode equivalent.
2945 * This is language-specific for performance reasons only.
2951 function normalize( $s ) {
2952 global $wgAllUnicodeFixes;
2953 $s = UtfNormal
::cleanUp( $s );
2954 if ( $wgAllUnicodeFixes ) {
2955 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2956 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2963 * Transform a string using serialized data stored in the given file (which
2964 * must be in the serialized subdirectory of $IP). The file contains pairs
2965 * mapping source characters to destination characters.
2967 * The data is cached in process memory. This will go faster if you have the
2968 * FastStringSearch extension.
2970 * @param string $file
2971 * @param string $string
2973 * @throws MWException
2976 function transformUsingPairFile( $file, $string ) {
2977 if ( !isset( $this->transformData
[$file] ) ) {
2978 $data = wfGetPrecompiledData( $file );
2979 if ( $data === false ) {
2980 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2982 $this->transformData
[$file] = new ReplacementArray( $data );
2984 return $this->transformData
[$file]->replace( $string );
2988 * For right-to-left language support
2993 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2997 * Return the correct HTML 'dir' attribute value for this language.
3001 return $this->isRTL() ?
'rtl' : 'ltr';
3005 * Return 'left' or 'right' as appropriate alignment for line-start
3006 * for this language's text direction.
3008 * Should be equivalent to CSS3 'start' text-align value....
3012 function alignStart() {
3013 return $this->isRTL() ?
'right' : 'left';
3017 * Return 'right' or 'left' as appropriate alignment for line-end
3018 * for this language's text direction.
3020 * Should be equivalent to CSS3 'end' text-align value....
3024 function alignEnd() {
3025 return $this->isRTL() ?
'left' : 'right';
3029 * A hidden direction mark (LRM or RLM), depending on the language direction.
3030 * Unlike getDirMark(), this function returns the character as an HTML entity.
3031 * This function should be used when the output is guaranteed to be HTML,
3032 * because it makes the output HTML source code more readable. When
3033 * the output is plain text or can be escaped, getDirMark() should be used.
3035 * @param bool $opposite Get the direction mark opposite to your language
3039 function getDirMarkEntity( $opposite = false ) {
3041 return $this->isRTL() ?
'‎' : '‏';
3043 return $this->isRTL() ?
'‏' : '‎';
3047 * A hidden direction mark (LRM or RLM), depending on the language direction.
3048 * This function produces them as invisible Unicode characters and
3049 * the output may be hard to read and debug, so it should only be used
3050 * when the output is plain text or can be escaped. When the output is
3051 * HTML, use getDirMarkEntity() instead.
3053 * @param bool $opposite Get the direction mark opposite to your language
3056 function getDirMark( $opposite = false ) {
3057 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3058 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3060 return $this->isRTL() ?
$lrm : $rlm;
3062 return $this->isRTL() ?
$rlm : $lrm;
3068 function capitalizeAllNouns() {
3069 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3073 * An arrow, depending on the language direction.
3075 * @param string $direction The direction of the arrow: forwards (default),
3076 * backwards, left, right, up, down.
3079 function getArrow( $direction = 'forwards' ) {
3080 switch ( $direction ) {
3082 return $this->isRTL() ?
'←' : '→';
3084 return $this->isRTL() ?
'→' : '←';
3097 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3101 function linkPrefixExtension() {
3102 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3106 * Get all magic words from cache.
3109 function getMagicWords() {
3110 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3114 * Run the LanguageGetMagic hook once.
3116 protected function doMagicHook() {
3117 if ( $this->mMagicHookDone
) {
3120 $this->mMagicHookDone
= true;
3121 wfProfileIn( 'LanguageGetMagic' );
3122 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3123 wfProfileOut( 'LanguageGetMagic' );
3127 * Fill a MagicWord object with data from here
3129 * @param MagicWord $mw
3131 function getMagic( $mw ) {
3132 // Saves a function call
3133 if ( !$this->mMagicHookDone
) {
3134 $this->doMagicHook();
3137 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3138 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3140 $rawEntry = self
::$dataCache->getSubitem(
3141 $this->mCode
, 'magicWords', $mw->mId
);
3144 if ( !is_array( $rawEntry ) ) {
3145 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3147 $mw->mCaseSensitive
= $rawEntry[0];
3148 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3153 * Add magic words to the extension array
3155 * @param array $newWords
3157 function addMagicWordsByLang( $newWords ) {
3158 $fallbackChain = $this->getFallbackLanguages();
3159 $fallbackChain = array_reverse( $fallbackChain );
3160 foreach ( $fallbackChain as $code ) {
3161 if ( isset( $newWords[$code] ) ) {
3162 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3168 * Get special page names, as an associative array
3169 * case folded alias => real name
3172 function getSpecialPageAliases() {
3173 // Cache aliases because it may be slow to load them
3174 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3176 $this->mExtendedSpecialPageAliases
=
3177 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3178 wfRunHooks( 'LanguageGetSpecialPageAliases',
3179 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3182 return $this->mExtendedSpecialPageAliases
;
3186 * Italic is unsuitable for some languages
3188 * @param string $text The text to be emphasized.
3191 function emphasize( $text ) {
3192 return "<em>$text</em>";
3196 * Normally we output all numbers in plain en_US style, that is
3197 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3198 * point twohundredthirtyfive. However this is not suitable for all
3199 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3200 * Icelandic just want to use commas instead of dots, and dots instead
3201 * of commas like "293.291,235".
3203 * An example of this function being called:
3205 * wfMessage( 'message' )->numParams( $num )->text()
3208 * See $separatorTransformTable on MessageIs.php for
3209 * the , => . and . => , implementation.
3211 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3212 * @param int|float $number The string to be formatted, should be an integer
3213 * or a floating point number.
3214 * @param bool $nocommafy Set to true for special numbers like dates
3217 public function formatNum( $number, $nocommafy = false ) {
3218 global $wgTranslateNumerals;
3219 if ( !$nocommafy ) {
3220 $number = $this->commafy( $number );
3221 $s = $this->separatorTransformTable();
3223 $number = strtr( $number, $s );
3227 if ( $wgTranslateNumerals ) {
3228 $s = $this->digitTransformTable();
3230 $number = strtr( $number, $s );
3238 * Front-end for non-commafied formatNum
3240 * @param int|float $number The string to be formatted, should be an integer
3241 * or a floating point number.
3245 public function formatNumNoSeparators( $number ) {
3246 return $this->formatNum( $number, true );
3250 * @param string $number
3253 public function parseFormattedNumber( $number ) {
3254 $s = $this->digitTransformTable();
3256 // eliminate empty array values such as ''. (bug 64347)
3257 $s = array_filter( $s );
3258 $number = strtr( $number, array_flip( $s ) );
3261 $s = $this->separatorTransformTable();
3263 // eliminate empty array values such as ''. (bug 64347)
3264 $s = array_filter( $s );
3265 $number = strtr( $number, array_flip( $s ) );
3268 $number = strtr( $number, array( ',' => '' ) );
3273 * Adds commas to a given number
3275 * @param mixed $number
3278 function commafy( $number ) {
3279 $digitGroupingPattern = $this->digitGroupingPattern();
3280 if ( $number === null ) {
3284 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3285 // default grouping is at thousands, use the same for ###,###,### pattern too.
3286 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3288 // Ref: http://cldr.unicode.org/translation/number-patterns
3290 if ( intval( $number ) < 0 ) {
3291 // For negative numbers apply the algorithm like positive number and add sign.
3293 $number = substr( $number, 1 );
3295 $integerPart = array();
3296 $decimalPart = array();
3297 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3298 preg_match( "/\d+/", $number, $integerPart );
3299 preg_match( "/\.\d*/", $number, $decimalPart );
3300 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3301 if ( $groupedNumber === $number ) {
3302 // the string does not have any number part. Eg: .12345
3303 return $sign . $groupedNumber;
3305 $start = $end = strlen( $integerPart[0] );
3306 while ( $start > 0 ) {
3307 $match = $matches[0][$numMatches - 1];
3308 $matchLen = strlen( $match );
3309 $start = $end - $matchLen;
3313 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3315 if ( $numMatches > 1 ) {
3316 // use the last pattern for the rest of the number
3320 $groupedNumber = "," . $groupedNumber;
3323 return $sign . $groupedNumber;
3330 function digitGroupingPattern() {
3331 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3337 function digitTransformTable() {
3338 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3344 function separatorTransformTable() {
3345 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3349 * Take a list of strings and build a locale-friendly comma-separated
3350 * list, using the local comma-separator message.
3351 * The last two strings are chained with an "and".
3352 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3354 * @param string[] $l
3357 function listToText( array $l ) {
3358 $m = count( $l ) - 1;
3363 $and = $this->getMessageFromDB( 'and' );
3364 $space = $this->getMessageFromDB( 'word-separator' );
3366 $comma = $this->getMessageFromDB( 'comma-separator' );
3370 for ( $i = $m - 1; $i >= 0; $i-- ) {
3371 if ( $i == $m - 1 ) {
3372 $s = $l[$i] . $and . $space . $s;
3374 $s = $l[$i] . $comma . $s;
3381 * Take a list of strings and build a locale-friendly comma-separated
3382 * list, using the local comma-separator message.
3383 * @param string[] $list Array of strings to put in a comma list
3386 function commaList( array $list ) {
3388 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3394 * Take a list of strings and build a locale-friendly semicolon-separated
3395 * list, using the local semicolon-separator message.
3396 * @param string[] $list Array of strings to put in a semicolon list
3399 function semicolonList( array $list ) {
3401 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3407 * Same as commaList, but separate it with the pipe instead.
3408 * @param string[] $list Array of strings to put in a pipe list
3411 function pipeList( array $list ) {
3413 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3419 * Truncate a string to a specified length in bytes, appending an optional
3420 * string (e.g. for ellipses)
3422 * The database offers limited byte lengths for some columns in the database;
3423 * multi-byte character sets mean we need to ensure that only whole characters
3424 * are included, otherwise broken characters can be passed to the user
3426 * If $length is negative, the string will be truncated from the beginning
3428 * @param string $string String to truncate
3429 * @param int $length Maximum length (including ellipses)
3430 * @param string $ellipsis String to append to the truncated text
3431 * @param bool $adjustLength Subtract length of ellipsis from $length.
3432 * $adjustLength was introduced in 1.18, before that behaved as if false.
3435 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3436 # Use the localized ellipsis character
3437 if ( $ellipsis == '...' ) {
3438 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3440 # Check if there is no need to truncate
3441 if ( $length == 0 ) {
3442 return $ellipsis; // convention
3443 } elseif ( strlen( $string ) <= abs( $length ) ) {
3444 return $string; // no need to truncate
3446 $stringOriginal = $string;
3447 # If ellipsis length is >= $length then we can't apply $adjustLength
3448 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3449 $string = $ellipsis; // this can be slightly unexpected
3450 # Otherwise, truncate and add ellipsis...
3452 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3453 if ( $length > 0 ) {
3454 $length -= $eLength;
3455 $string = substr( $string, 0, $length ); // xyz...
3456 $string = $this->removeBadCharLast( $string );
3457 $string = rtrim( $string );
3458 $string = $string . $ellipsis;
3460 $length +
= $eLength;
3461 $string = substr( $string, $length ); // ...xyz
3462 $string = $this->removeBadCharFirst( $string );
3463 $string = ltrim( $string );
3464 $string = $ellipsis . $string;
3467 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3468 # This check is *not* redundant if $adjustLength, due to the single case where
3469 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3470 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3473 return $stringOriginal;
3478 * Remove bytes that represent an incomplete Unicode character
3479 * at the end of string (e.g. bytes of the char are missing)
3481 * @param string $string
3484 protected function removeBadCharLast( $string ) {
3485 if ( $string != '' ) {
3486 $char = ord( $string[strlen( $string ) - 1] );
3488 if ( $char >= 0xc0 ) {
3489 # We got the first byte only of a multibyte char; remove it.
3490 $string = substr( $string, 0, -1 );
3491 } elseif ( $char >= 0x80 &&
3492 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3493 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3495 # We chopped in the middle of a character; remove it
3503 * Remove bytes that represent an incomplete Unicode character
3504 * at the start of string (e.g. bytes of the char are missing)
3506 * @param string $string
3509 protected function removeBadCharFirst( $string ) {
3510 if ( $string != '' ) {
3511 $char = ord( $string[0] );
3512 if ( $char >= 0x80 && $char < 0xc0 ) {
3513 # We chopped in the middle of a character; remove the whole thing
3514 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3521 * Truncate a string of valid HTML to a specified length in bytes,
3522 * appending an optional string (e.g. for ellipses), and return valid HTML
3524 * This is only intended for styled/linked text, such as HTML with
3525 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3526 * Also, this will not detect things like "display:none" CSS.
3528 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3530 * @param string $text HTML string to truncate
3531 * @param int $length (zero/positive) Maximum length (including ellipses)
3532 * @param string $ellipsis String to append to the truncated text
3535 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3536 # Use the localized ellipsis character
3537 if ( $ellipsis == '...' ) {
3538 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3540 # Check if there is clearly no need to truncate
3541 if ( $length <= 0 ) {
3542 return $ellipsis; // no text shown, nothing to format (convention)
3543 } elseif ( strlen( $text ) <= $length ) {
3544 return $text; // string short enough even *with* HTML (short-circuit)
3547 $dispLen = 0; // innerHTML legth so far
3548 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3549 $tagType = 0; // 0-open, 1-close
3550 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3551 $entityState = 0; // 0-not entity, 1-entity
3552 $tag = $ret = ''; // accumulated tag name, accumulated result string
3553 $openTags = array(); // open tag stack
3554 $maybeState = null; // possible truncation state
3556 $textLen = strlen( $text );
3557 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3558 for ( $pos = 0; true; ++
$pos ) {
3559 # Consider truncation once the display length has reached the maximim.
3560 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3561 # Check that we're not in the middle of a bracket/entity...
3562 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3563 if ( !$testingEllipsis ) {
3564 $testingEllipsis = true;
3565 # Save where we are; we will truncate here unless there turn out to
3566 # be so few remaining characters that truncation is not necessary.
3567 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3568 $maybeState = array( $ret, $openTags ); // save state
3570 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3571 # String in fact does need truncation, the truncation point was OK.
3572 list( $ret, $openTags ) = $maybeState; // reload state
3573 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3574 $ret .= $ellipsis; // add ellipsis
3578 if ( $pos >= $textLen ) {
3579 break; // extra iteration just for above checks
3582 # Read the next char...
3584 $lastCh = $pos ?
$text[$pos - 1] : '';
3585 $ret .= $ch; // add to result string
3587 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3588 $entityState = 0; // for bad HTML
3589 $bracketState = 1; // tag started (checking for backslash)
3590 } elseif ( $ch == '>' ) {
3591 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3592 $entityState = 0; // for bad HTML
3593 $bracketState = 0; // out of brackets
3594 } elseif ( $bracketState == 1 ) {
3596 $tagType = 1; // close tag (e.g. "</span>")
3598 $tagType = 0; // open tag (e.g. "<span>")
3601 $bracketState = 2; // building tag name
3602 } elseif ( $bracketState == 2 ) {
3606 // Name found (e.g. "<a href=..."), add on tag attributes...
3607 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3609 } elseif ( $bracketState == 0 ) {
3610 if ( $entityState ) {
3613 $dispLen++
; // entity is one displayed char
3616 if ( $neLength == 0 && !$maybeState ) {
3617 // Save state without $ch. We want to *hit* the first
3618 // display char (to get tags) but not *use* it if truncating.
3619 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3622 $entityState = 1; // entity found, (e.g. " ")
3624 $dispLen++
; // this char is displayed
3625 // Add the next $max display text chars after this in one swoop...
3626 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3627 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3628 $dispLen +
= $skipped;
3634 // Close the last tag if left unclosed by bad HTML
3635 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3636 while ( count( $openTags ) > 0 ) {
3637 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3643 * truncateHtml() helper function
3644 * like strcspn() but adds the skipped chars to $ret
3646 * @param string $ret
3647 * @param string $text
3648 * @param string $search
3650 * @param null|int $len
3653 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3654 if ( $len === null ) {
3655 $len = -1; // -1 means "no limit" for strcspn
3656 } elseif ( $len < 0 ) {
3660 if ( $start < strlen( $text ) ) {
3661 $skipCount = strcspn( $text, $search, $start, $len );
3662 $ret .= substr( $text, $start, $skipCount );
3668 * truncateHtml() helper function
3669 * (a) push or pop $tag from $openTags as needed
3670 * (b) clear $tag value
3671 * @param string &$tag Current HTML tag name we are looking at
3672 * @param int $tagType (0-open tag, 1-close tag)
3673 * @param string $lastCh Character before the '>' that ended this tag
3674 * @param array &$openTags Open tag stack (not accounting for $tag)
3676 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3677 $tag = ltrim( $tag );
3679 if ( $tagType == 0 && $lastCh != '/' ) {
3680 $openTags[] = $tag; // tag opened (didn't close itself)
3681 } elseif ( $tagType == 1 ) {
3682 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3683 array_pop( $openTags ); // tag closed
3691 * Grammatical transformations, needed for inflected languages
3692 * Invoked by putting {{grammar:case|word}} in a message
3694 * @param string $word
3695 * @param string $case
3698 function convertGrammar( $word, $case ) {
3699 global $wgGrammarForms;
3700 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3701 return $wgGrammarForms[$this->getCode()][$case][$word];
3707 * Get the grammar forms for the content language
3708 * @return array Array of grammar forms
3711 function getGrammarForms() {
3712 global $wgGrammarForms;
3713 if ( isset( $wgGrammarForms[$this->getCode()] )
3714 && is_array( $wgGrammarForms[$this->getCode()] )
3716 return $wgGrammarForms[$this->getCode()];
3722 * Provides an alternative text depending on specified gender.
3723 * Usage {{gender:username|masculine|feminine|unknown}}.
3724 * username is optional, in which case the gender of current user is used,
3725 * but only in (some) interface messages; otherwise default gender is used.
3727 * If no forms are given, an empty string is returned. If only one form is
3728 * given, it will be returned unconditionally. These details are implied by
3729 * the caller and cannot be overridden in subclasses.
3731 * If three forms are given, the default is to use the third (unknown) form.
3732 * If fewer than three forms are given, the default is to use the first (masculine) form.
3733 * These details can be overridden in subclasses.
3735 * @param string $gender
3736 * @param array $forms
3740 function gender( $gender, $forms ) {
3741 if ( !count( $forms ) ) {
3744 $forms = $this->preConvertPlural( $forms, 2 );
3745 if ( $gender === 'male' ) {
3748 if ( $gender === 'female' ) {
3751 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3755 * Plural form transformations, needed for some languages.
3756 * For example, there are 3 form of plural in Russian and Polish,
3757 * depending on "count mod 10". See [[w:Plural]]
3758 * For English it is pretty simple.
3760 * Invoked by putting {{plural:count|wordform1|wordform2}}
3761 * or {{plural:count|wordform1|wordform2|wordform3}}
3763 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3765 * @param int $count Non-localized number
3766 * @param array $forms Different plural forms
3767 * @return string Correct form of plural for $count in this language
3769 function convertPlural( $count, $forms ) {
3770 // Handle explicit n=pluralform cases
3771 $forms = $this->handleExplicitPluralForms( $count, $forms );
3772 if ( is_string( $forms ) ) {
3775 if ( !count( $forms ) ) {
3779 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3780 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3781 return $forms[$pluralForm];
3785 * Handles explicit plural forms for Language::convertPlural()
3787 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3788 * If an explicitly defined plural form matches the $count, then
3789 * string value returned, otherwise array returned for further consideration
3790 * by CLDR rules or overridden convertPlural().
3794 * @param int $count Non-localized number
3795 * @param array $forms Different plural forms
3797 * @return array|string
3799 protected function handleExplicitPluralForms( $count, array $forms ) {
3800 foreach ( $forms as $index => $form ) {
3801 if ( preg_match( '/\d+=/i', $form ) ) {
3802 $pos = strpos( $form, '=' );
3803 if ( substr( $form, 0, $pos ) === (string)$count ) {
3804 return substr( $form, $pos +
1 );
3806 unset( $forms[$index] );
3809 return array_values( $forms );
3813 * Checks that convertPlural was given an array and pads it to requested
3814 * amount of forms by copying the last one.
3816 * @param array $forms Array of forms given to convertPlural
3817 * @param int $count How many forms should there be at least
3818 * @return array Padded array of forms or an exception if not an array
3820 protected function preConvertPlural( /* Array */ $forms, $count ) {
3821 while ( count( $forms ) < $count ) {
3822 $forms[] = $forms[count( $forms ) - 1];
3828 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3829 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3830 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3831 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3834 * @param string $str The validated block duration in English
3835 * @return string Somehow translated block duration
3836 * @see LanguageFi.php for example implementation
3838 function translateBlockExpiry( $str ) {
3839 $duration = SpecialBlock
::getSuggestedDurations( $this );
3840 foreach ( $duration as $show => $value ) {
3841 if ( strcmp( $str, $value ) == 0 ) {
3842 return htmlspecialchars( trim( $show ) );
3846 // Since usually only infinite or indefinite is only on list, so try
3847 // equivalents if still here.
3848 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3849 if ( in_array( $str, $indefs ) ) {
3850 foreach ( $indefs as $val ) {
3851 $show = array_search( $val, $duration, true );
3852 if ( $show !== false ) {
3853 return htmlspecialchars( trim( $show ) );
3858 // If all else fails, return a standard duration or timestamp description.
3859 $time = strtotime( $str, 0 );
3860 if ( $time === false ) { // Unknown format. Return it as-is in case.
3862 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3863 // $time is relative to 0 so it's a duration length.
3864 return $this->formatDuration( $time );
3865 } else { // It's an absolute timestamp.
3866 if ( $time === 0 ) {
3867 // wfTimestamp() handles 0 as current time instead of epoch.
3868 return $this->timeanddate( '19700101000000' );
3870 return $this->timeanddate( $time );
3876 * languages like Chinese need to be segmented in order for the diff
3879 * @param string $text
3882 public function segmentForDiff( $text ) {
3887 * and unsegment to show the result
3889 * @param string $text
3892 public function unsegmentForDiff( $text ) {
3897 * Return the LanguageConverter used in the Language
3900 * @return LanguageConverter
3902 public function getConverter() {
3903 return $this->mConverter
;
3907 * convert text to all supported variants
3909 * @param string $text
3912 public function autoConvertToAllVariants( $text ) {
3913 return $this->mConverter
->autoConvertToAllVariants( $text );
3917 * convert text to different variants of a language.
3919 * @param string $text
3922 public function convert( $text ) {
3923 return $this->mConverter
->convert( $text );
3927 * Convert a Title object to a string in the preferred variant
3929 * @param Title $title
3932 public function convertTitle( $title ) {
3933 return $this->mConverter
->convertTitle( $title );
3937 * Convert a namespace index to a string in the preferred variant
3942 public function convertNamespace( $ns ) {
3943 return $this->mConverter
->convertNamespace( $ns );
3947 * Check if this is a language with variants
3951 public function hasVariants() {
3952 return count( $this->getVariants() ) > 1;
3956 * Check if the language has the specific variant
3959 * @param string $variant
3962 public function hasVariant( $variant ) {
3963 return (bool)$this->mConverter
->validateVariant( $variant );
3967 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3969 * @param string $text
3971 * @deprecated since 1.22 is no longer used
3973 public function armourMath( $text ) {
3974 return $this->mConverter
->armourMath( $text );
3978 * Perform output conversion on a string, and encode for safe HTML output.
3979 * @param string $text Text to be converted
3980 * @param bool $isTitle Whether this conversion is for the article title
3982 * @todo this should get integrated somewhere sane
3984 public function convertHtml( $text, $isTitle = false ) {
3985 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3989 * @param string $key
3992 public function convertCategoryKey( $key ) {
3993 return $this->mConverter
->convertCategoryKey( $key );
3997 * Get the list of variants supported by this language
3998 * see sample implementation in LanguageZh.php
4000 * @return array An array of language codes
4002 public function getVariants() {
4003 return $this->mConverter
->getVariants();
4009 public function getPreferredVariant() {
4010 return $this->mConverter
->getPreferredVariant();
4016 public function getDefaultVariant() {
4017 return $this->mConverter
->getDefaultVariant();
4023 public function getURLVariant() {
4024 return $this->mConverter
->getURLVariant();
4028 * If a language supports multiple variants, it is
4029 * possible that non-existing link in one variant
4030 * actually exists in another variant. this function
4031 * tries to find it. See e.g. LanguageZh.php
4032 * The input parameters may be modified upon return
4034 * @param string &$link The name of the link
4035 * @param Title &$nt The title object of the link
4036 * @param bool $ignoreOtherCond To disable other conditions when
4037 * we need to transclude a template or update a category's link
4039 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4040 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4044 * returns language specific options used by User::getPageRenderHash()
4045 * for example, the preferred language variant
4049 function getExtraHashOptions() {
4050 return $this->mConverter
->getExtraHashOptions();
4054 * For languages that support multiple variants, the title of an
4055 * article may be displayed differently in different variants. this
4056 * function returns the apporiate title defined in the body of the article.
4060 public function getParsedTitle() {
4061 return $this->mConverter
->getParsedTitle();
4065 * Prepare external link text for conversion. When the text is
4066 * a URL, it shouldn't be converted, and it'll be wrapped in
4067 * the "raw" tag (-{R| }-) to prevent conversion.
4069 * This function is called "markNoConversion" for historical
4072 * @param string $text Text to be used for external link
4073 * @param bool $noParse Wrap it without confirming it's a real URL first
4074 * @return string The tagged text
4076 public function markNoConversion( $text, $noParse = false ) {
4077 // Excluding protocal-relative URLs may avoid many false positives.
4078 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4079 return $this->mConverter
->markNoConversion( $text );
4086 * A regular expression to match legal word-trailing characters
4087 * which should be merged onto a link of the form [[foo]]bar.
4091 public function linkTrail() {
4092 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4096 * A regular expression character set to match legal word-prefixing
4097 * characters which should be merged onto a link of the form foo[[bar]].
4101 public function linkPrefixCharset() {
4102 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4106 * @deprecated since 1.24, will be removed in 1.25
4109 function getLangObj() {
4110 wfDeprecated( __METHOD__
, '1.24' );
4115 * Get the "parent" language which has a converter to convert a "compatible" language
4116 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4118 * @return Language|null
4121 public function getParentLanguage() {
4122 if ( $this->mParentLanguage
!== false ) {
4123 return $this->mParentLanguage
;
4126 $pieces = explode( '-', $this->getCode() );
4128 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4129 $this->mParentLanguage
= null;
4132 $lang = Language
::factory( $code );
4133 if ( !$lang->hasVariant( $this->getCode() ) ) {
4134 $this->mParentLanguage
= null;
4138 $this->mParentLanguage
= $lang;
4143 * Get the RFC 3066 code for this language object
4145 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4146 * htmlspecialchars() or similar
4150 public function getCode() {
4151 return $this->mCode
;
4155 * Get the code in Bcp47 format which we can use
4156 * inside of html lang="" tags.
4158 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4159 * htmlspecialchars() or similar.
4164 public function getHtmlCode() {
4165 if ( is_null( $this->mHtmlCode
) ) {
4166 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4168 return $this->mHtmlCode
;
4172 * @param string $code
4174 public function setCode( $code ) {
4175 $this->mCode
= $code;
4176 // Ensure we don't leave incorrect cached data lying around
4177 $this->mHtmlCode
= null;
4178 $this->mParentLanguage
= false;
4182 * Get the name of a file for a certain language code
4183 * @param string $prefix Prepend this to the filename
4184 * @param string $code Language code
4185 * @param string $suffix Append this to the filename
4186 * @throws MWException
4187 * @return string $prefix . $mangledCode . $suffix
4189 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4190 if ( !self
::isValidBuiltInCode( $code ) ) {
4191 throw new MWException( "Invalid language code \"$code\"" );
4194 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4198 * Get the language code from a file name. Inverse of getFileName()
4199 * @param string $filename $prefix . $languageCode . $suffix
4200 * @param string $prefix Prefix before the language code
4201 * @param string $suffix Suffix after the language code
4202 * @return string Language code, or false if $prefix or $suffix isn't found
4204 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4206 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4207 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4208 if ( !count( $m ) ) {
4211 return str_replace( '_', '-', strtolower( $m[1] ) );
4215 * @param string $code
4218 public static function getMessagesFileName( $code ) {
4220 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4221 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4226 * @param string $code
4230 public static function getJsonMessagesFileName( $code ) {
4233 if ( !self
::isValidBuiltInCode( $code ) ) {
4234 throw new MWException( "Invalid language code \"$code\"" );
4237 return "$IP/languages/i18n/$code.json";
4241 * @param string $code
4244 public static function getClassFileName( $code ) {
4246 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4250 * Get the first fallback for a given language.
4252 * @param string $code
4254 * @return bool|string
4256 public static function getFallbackFor( $code ) {
4257 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4260 $fallbacks = self
::getFallbacksFor( $code );
4261 $first = array_shift( $fallbacks );
4267 * Get the ordered list of fallback languages.
4270 * @param string $code Language code
4273 public static function getFallbacksFor( $code ) {
4274 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4277 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4278 $v = array_map( 'trim', explode( ',', $v ) );
4279 if ( $v[count( $v ) - 1] !== 'en' ) {
4287 * Get the ordered list of fallback languages, ending with the fallback
4288 * language chain for the site language.
4291 * @param string $code Language code
4292 * @return array Array( fallbacks, site fallbacks )
4294 public static function getFallbacksIncludingSiteLanguage( $code ) {
4295 global $wgLanguageCode;
4297 // Usually, we will only store a tiny number of fallback chains, so we
4298 // keep them in static memory.
4299 $cacheKey = "{$code}-{$wgLanguageCode}";
4301 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4302 $fallbacks = self
::getFallbacksFor( $code );
4304 // Append the site's fallback chain, including the site language itself
4305 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4306 array_unshift( $siteFallbacks, $wgLanguageCode );
4308 // Eliminate any languages already included in the chain
4309 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4311 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4313 return self
::$fallbackLanguageCache[$cacheKey];
4317 * Get all messages for a given language
4318 * WARNING: this may take a long time. If you just need all message *keys*
4319 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4321 * @param string $code
4325 public static function getMessagesFor( $code ) {
4326 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4330 * Get a message for a given language
4332 * @param string $key
4333 * @param string $code
4337 public static function getMessageFor( $key, $code ) {
4338 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4342 * Get all message keys for a given language. This is a faster alternative to
4343 * array_keys( Language::getMessagesFor( $code ) )
4346 * @param string $code Language code
4347 * @return array Array of message keys (strings)
4349 public static function getMessageKeysFor( $code ) {
4350 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4354 * @param string $talk
4357 function fixVariableInNamespace( $talk ) {
4358 if ( strpos( $talk, '$1' ) === false ) {
4362 global $wgMetaNamespace;
4363 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4365 # Allow grammar transformations
4366 # Allowing full message-style parsing would make simple requests
4367 # such as action=raw much more expensive than they need to be.
4368 # This will hopefully cover most cases.
4369 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4370 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4371 return str_replace( ' ', '_', $talk );
4378 function replaceGrammarInNamespace( $m ) {
4379 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4383 * @throws MWException
4386 static function getCaseMaps() {
4387 static $wikiUpperChars, $wikiLowerChars;
4388 if ( isset( $wikiUpperChars ) ) {
4389 return array( $wikiUpperChars, $wikiLowerChars );
4392 wfProfileIn( __METHOD__
);
4393 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4394 if ( $arr === false ) {
4395 throw new MWException(
4396 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4398 $wikiUpperChars = $arr['wikiUpperChars'];
4399 $wikiLowerChars = $arr['wikiLowerChars'];
4400 wfProfileOut( __METHOD__
);
4401 return array( $wikiUpperChars, $wikiLowerChars );
4405 * Decode an expiry (block, protection, etc) which has come from the DB
4407 * @todo FIXME: why are we returnings DBMS-dependent strings???
4409 * @param string $expiry Database expiry String
4410 * @param bool|int $format True to process using language functions, or TS_ constant
4411 * to return the expiry in a given timestamp
4415 public function formatExpiry( $expiry, $format = true ) {
4417 if ( $infinity === null ) {
4418 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4421 if ( $expiry == '' ||
$expiry == $infinity ) {
4422 return $format === true
4423 ?
$this->getMessageFromDB( 'infiniteblock' )
4426 return $format === true
4427 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4428 : wfTimestamp( $format, $expiry );
4434 * @param int|float $seconds
4435 * @param array $format Optional
4436 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4437 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4438 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4440 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4441 * or 'avoidminutes'.
4444 function formatTimePeriod( $seconds, $format = array() ) {
4445 if ( !is_array( $format ) ) {
4446 $format = array( 'avoid' => $format ); // For backwards compatibility
4448 if ( !isset( $format['avoid'] ) ) {
4449 $format['avoid'] = false;
4451 if ( !isset( $format['noabbrevs'] ) ) {
4452 $format['noabbrevs'] = false;
4454 $secondsMsg = wfMessage(
4455 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4456 $minutesMsg = wfMessage(
4457 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4458 $hoursMsg = wfMessage(
4459 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4460 $daysMsg = wfMessage(
4461 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4463 if ( round( $seconds * 10 ) < 100 ) {
4464 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4465 $s = $secondsMsg->params( $s )->text();
4466 } elseif ( round( $seconds ) < 60 ) {
4467 $s = $this->formatNum( round( $seconds ) );
4468 $s = $secondsMsg->params( $s )->text();
4469 } elseif ( round( $seconds ) < 3600 ) {
4470 $minutes = floor( $seconds / 60 );
4471 $secondsPart = round( fmod( $seconds, 60 ) );
4472 if ( $secondsPart == 60 ) {
4476 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4478 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4479 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4480 $hours = floor( $seconds / 3600 );
4481 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4482 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4483 if ( $secondsPart == 60 ) {
4487 if ( $minutes == 60 ) {
4491 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4493 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4494 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4495 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4498 $days = floor( $seconds / 86400 );
4499 if ( $format['avoid'] === 'avoidminutes' ) {
4500 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4501 if ( $hours == 24 ) {
4505 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4507 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4508 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4509 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4510 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4511 if ( $minutes == 60 ) {
4515 if ( $hours == 24 ) {
4519 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4521 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4523 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4525 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4527 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4534 * Format a bitrate for output, using an appropriate
4535 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4536 * the magnitude in question.
4538 * This use base 1000. For base 1024 use formatSize(), for another base
4539 * see formatComputingNumbers().
4544 function formatBitrate( $bps ) {
4545 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4549 * @param int $size Size of the unit
4550 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4551 * @param string $messageKey Message key to be uesd
4554 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4556 return str_replace( '$1', $this->formatNum( $size ),
4557 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4560 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4563 $maxIndex = count( $sizes ) - 1;
4564 while ( $size >= $boundary && $index < $maxIndex ) {
4569 // For small sizes no decimal places necessary
4572 // For MB and bigger two decimal places are smarter
4575 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4577 $size = round( $size, $round );
4578 $text = $this->getMessageFromDB( $msg );
4579 return str_replace( '$1', $this->formatNum( $size ), $text );
4583 * Format a size in bytes for output, using an appropriate
4584 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4586 * This method use base 1024. For base 1000 use formatBitrate(), for
4587 * another base see formatComputingNumbers()
4589 * @param int $size Size to format
4590 * @return string Plain text (not HTML)
4592 function formatSize( $size ) {
4593 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4597 * Make a list item, used by various special pages
4599 * @param string $page Page link
4600 * @param string $details Text between brackets
4601 * @param bool $oppositedm Add the direction mark opposite to your
4602 * language, to display text properly
4605 function specialList( $page, $details, $oppositedm = true ) {
4606 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4607 $this->getDirMark();
4608 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4609 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4610 return $page . $details;
4614 * Generate (prev x| next x) (20|50|100...) type links for paging
4616 * @param Title $title Title object to link
4617 * @param int $offset
4619 * @param array $query Optional URL query parameter string
4620 * @param bool $atend Optional param for specified if this is the last page
4623 public function viewPrevNext( Title
$title, $offset, $limit,
4624 array $query = array(), $atend = false
4626 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4628 # Make 'previous' link
4629 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4630 if ( $offset > 0 ) {
4631 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4632 $query, $prev, 'prevn-title', 'mw-prevlink' );
4634 $plink = htmlspecialchars( $prev );
4638 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4640 $nlink = htmlspecialchars( $next );
4642 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4643 $query, $next, 'nextn-title', 'mw-nextlink' );
4646 # Make links to set number of items per page
4647 $numLinks = array();
4648 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4649 $numLinks[] = $this->numLink( $title, $offset, $num,
4650 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4653 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4654 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4658 * Helper function for viewPrevNext() that generates links
4660 * @param Title $title Title object to link
4661 * @param int $offset
4663 * @param array $query Extra query parameters
4664 * @param string $link Text to use for the link; will be escaped
4665 * @param string $tooltipMsg Name of the message to use as tooltip
4666 * @param string $class Value of the "class" attribute of the link
4667 * @return string HTML fragment
4669 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4672 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4673 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4674 ->numParams( $limit )->text();
4676 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4677 'title' => $tooltip, 'class' => $class ), $link );
4681 * Get the conversion rule title, if any.
4685 public function getConvRuleTitle() {
4686 return $this->mConverter
->getConvRuleTitle();
4690 * Get the compiled plural rules for the language
4692 * @return array Associative array with plural form, and plural rule as key-value pairs
4694 public function getCompiledPluralRules() {
4695 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4696 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4697 if ( !$pluralRules ) {
4698 foreach ( $fallbacks as $fallbackCode ) {
4699 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4700 if ( $pluralRules ) {
4705 return $pluralRules;
4709 * Get the plural rules for the language
4711 * @return array Associative array with plural form number and plural rule as key-value pairs
4713 public function getPluralRules() {
4714 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4715 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4716 if ( !$pluralRules ) {
4717 foreach ( $fallbacks as $fallbackCode ) {
4718 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4719 if ( $pluralRules ) {
4724 return $pluralRules;
4728 * Get the plural rule types for the language
4730 * @return array Associative array with plural form number and plural rule type as key-value pairs
4732 public function getPluralRuleTypes() {
4733 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4734 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4735 if ( !$pluralRuleTypes ) {
4736 foreach ( $fallbacks as $fallbackCode ) {
4737 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4738 if ( $pluralRuleTypes ) {
4743 return $pluralRuleTypes;
4747 * Find the index number of the plural rule appropriate for the given number
4748 * @param int $number
4749 * @return int The index number of the plural rule
4751 public function getPluralRuleIndexNumber( $number ) {
4752 $pluralRules = $this->getCompiledPluralRules();
4753 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4758 * Find the plural rule type appropriate for the given number
4759 * For example, if the language is set to Arabic, getPluralType(5) should
4762 * @param int $number
4763 * @return string The name of the plural rule type, e.g. one, two, few, many
4765 public function getPluralRuleType( $number ) {
4766 $index = $this->getPluralRuleIndexNumber( $number );
4767 $pluralRuleTypes = $this->getPluralRuleTypes();
4768 if ( isset( $pluralRuleTypes[$index] ) ) {
4769 return $pluralRuleTypes[$index];