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,}$/i', $code );
346 * Returns true if a language code is an IETF tag known to MediaWiki.
348 * @param string $code
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() {
447 * Same as getFallbacksFor for current language.
449 * @deprecated since 1.19
451 function getFallbackLanguageCode() {
452 wfDeprecated( __METHOD__
, '1.19' );
454 return self
::getFallbackFor( $this->mCode
);
461 function getFallbackLanguages() {
462 return self
::getFallbacksFor( $this->mCode
);
466 * Exports $wgBookstoreListEn
469 function getBookstoreList() {
470 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
474 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
475 * available in localised form, it will be included in English.
479 public function getNamespaces() {
480 if ( is_null( $this->namespaceNames
) ) {
481 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
483 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
484 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
486 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
488 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
489 if ( $wgMetaNamespaceTalk ) {
490 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
492 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
493 $this->namespaceNames
[NS_PROJECT_TALK
] =
494 $this->fixVariableInNamespace( $talk );
497 # Sometimes a language will be localised but not actually exist on this wiki.
498 foreach ( $this->namespaceNames
as $key => $text ) {
499 if ( !isset( $validNamespaces[$key] ) ) {
500 unset( $this->namespaceNames
[$key] );
504 # The above mixing may leave namespaces out of canonical order.
505 # Re-order by namespace ID number...
506 ksort( $this->namespaceNames
);
508 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
511 return $this->namespaceNames
;
515 * Arbitrarily set all of the namespace names at once. Mainly used for testing
516 * @param array $namespaces Array of namespaces (id => name)
518 public function setNamespaces( array $namespaces ) {
519 $this->namespaceNames
= $namespaces;
520 $this->mNamespaceIds
= null;
524 * Resets all of the namespace caches. Mainly used for testing
526 public function resetNamespaces() {
527 $this->namespaceNames
= null;
528 $this->mNamespaceIds
= null;
529 $this->namespaceAliases
= null;
533 * A convenience function that returns the same thing as
534 * getNamespaces() except with the array values changed to ' '
535 * where it found '_', useful for producing output to be displayed
536 * e.g. in <select> forms.
540 function getFormattedNamespaces() {
541 $ns = $this->getNamespaces();
542 foreach ( $ns as $k => $v ) {
543 $ns[$k] = strtr( $v, '_', ' ' );
549 * Get a namespace value by key
551 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
552 * echo $mw_ns; // prints 'MediaWiki'
555 * @param int $index The array key of the namespace to return
556 * @return string|bool String if the namespace value exists, otherwise false
558 function getNsText( $index ) {
559 $ns = $this->getNamespaces();
561 return isset( $ns[$index] ) ?
$ns[$index] : false;
565 * A convenience function that returns the same thing as
566 * getNsText() except with '_' changed to ' ', useful for
570 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
571 * echo $mw_ns; // prints 'MediaWiki talk'
574 * @param int $index The array key of the namespace to return
575 * @return string Namespace name without underscores (empty string if namespace does not exist)
577 function getFormattedNsText( $index ) {
578 $ns = $this->getNsText( $index );
580 return strtr( $ns, '_', ' ' );
584 * Returns gender-dependent namespace alias if available.
585 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
586 * @param int $index Namespace index
587 * @param string $gender Gender key (male, female... )
591 function getGenderNsText( $index, $gender ) {
592 global $wgExtraGenderNamespaces;
594 $ns = $wgExtraGenderNamespaces +
595 self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
597 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
601 * Whether this language uses gender-dependent namespace aliases.
602 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
606 function needsGenderDistinction() {
607 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
608 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
609 // $wgExtraGenderNamespaces overrides everything
611 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
612 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
613 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
616 // Check what is in i18n files
617 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
618 return count( $aliases ) > 0;
623 * Get a namespace key by value, case insensitive.
624 * Only matches namespace names for the current language, not the
625 * canonical ones defined in Namespace.php.
627 * @param string $text
628 * @return int|bool An integer if $text is a valid value otherwise false
630 function getLocalNsIndex( $text ) {
631 $lctext = $this->lc( $text );
632 $ids = $this->getNamespaceIds();
633 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
639 function getNamespaceAliases() {
640 if ( is_null( $this->namespaceAliases
) ) {
641 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
645 foreach ( $aliases as $name => $index ) {
646 if ( $index === NS_PROJECT_TALK
) {
647 unset( $aliases[$name] );
648 $name = $this->fixVariableInNamespace( $name );
649 $aliases[$name] = $index;
654 global $wgExtraGenderNamespaces;
655 $genders = $wgExtraGenderNamespaces +
656 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
657 foreach ( $genders as $index => $forms ) {
658 foreach ( $forms as $alias ) {
659 $aliases[$alias] = $index;
663 # Also add converted namespace names as aliases, to avoid confusion.
664 $convertedNames = array();
665 foreach ( $this->getVariants() as $variant ) {
666 if ( $variant === $this->mCode
) {
669 foreach ( $this->getNamespaces() as $ns => $_ ) {
670 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
674 $this->namespaceAliases
= $aliases +
$convertedNames;
677 return $this->namespaceAliases
;
683 function getNamespaceIds() {
684 if ( is_null( $this->mNamespaceIds
) ) {
685 global $wgNamespaceAliases;
686 # Put namespace names and aliases into a hashtable.
687 # If this is too slow, then we should arrange it so that it is done
688 # before caching. The catch is that at pre-cache time, the above
689 # class-specific fixup hasn't been done.
690 $this->mNamespaceIds
= array();
691 foreach ( $this->getNamespaces() as $index => $name ) {
692 $this->mNamespaceIds
[$this->lc( $name )] = $index;
694 foreach ( $this->getNamespaceAliases() as $name => $index ) {
695 $this->mNamespaceIds
[$this->lc( $name )] = $index;
697 if ( $wgNamespaceAliases ) {
698 foreach ( $wgNamespaceAliases as $name => $index ) {
699 $this->mNamespaceIds
[$this->lc( $name )] = $index;
703 return $this->mNamespaceIds
;
707 * Get a namespace key by value, case insensitive. Canonical namespace
708 * names override custom ones defined for the current language.
710 * @param string $text
711 * @return int|bool An integer if $text is a valid value otherwise false
713 function getNsIndex( $text ) {
714 $lctext = $this->lc( $text );
715 $ns = MWNamespace
::getCanonicalIndex( $lctext );
716 if ( $ns !== null ) {
719 $ids = $this->getNamespaceIds();
720 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
724 * short names for language variants used for language conversion links.
726 * @param string $code
727 * @param bool $usemsg Use the "variantname-xyz" message if it exists
730 function getVariantname( $code, $usemsg = true ) {
731 $msg = "variantname-$code";
732 if ( $usemsg && wfMessage( $msg )->exists() ) {
733 return $this->getMessageFromDB( $msg );
735 $name = self
::fetchLanguageName( $code );
737 return $name; # if it's defined as a language name, show that
739 # otherwise, output the language code
745 * @param string $name
748 function specialPage( $name ) {
749 $aliases = $this->getSpecialPageAliases();
750 if ( isset( $aliases[$name][0] ) ) {
751 $name = $aliases[$name][0];
753 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
759 function getDatePreferences() {
760 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
766 function getDateFormats() {
767 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
771 * @return array|string
773 function getDefaultDateFormat() {
774 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
775 if ( $df === 'dmy or mdy' ) {
776 global $wgAmericanDates;
777 return $wgAmericanDates ?
'mdy' : 'dmy';
786 function getDatePreferenceMigrationMap() {
787 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
791 * @param string $image
794 function getImageFile( $image ) {
795 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
801 function getExtraUserToggles() {
802 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
809 function getUserToggle( $tog ) {
810 return $this->getMessageFromDB( "tog-$tog" );
814 * Get native language names, indexed by code.
815 * Only those defined in MediaWiki, no other data like CLDR.
816 * If $customisedOnly is true, only returns codes with a messages file
818 * @param bool $customisedOnly
821 * @deprecated since 1.20, use fetchLanguageNames()
823 public static function getLanguageNames( $customisedOnly = false ) {
824 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
828 * Get translated language names. This is done on best effort and
829 * by default this is exactly the same as Language::getLanguageNames.
830 * The CLDR extension provides translated names.
831 * @param string $code Language code.
832 * @return array Language code => language name
834 * @deprecated since 1.20, use fetchLanguageNames()
836 public static function getTranslatedLanguageNames( $code ) {
837 return self
::fetchLanguageNames( $code, 'all' );
841 * Get an array of language names, indexed by code.
842 * @param null|string $inLanguage Code of language in which to return the names
843 * Use null for autonyms (native names)
844 * @param string $include One of:
845 * 'all' all available languages
846 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
847 * 'mwfile' only if the language is in 'mw' *and* has a message file
848 * @return array Language code => language name
851 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
852 global $wgExtraLanguageNames;
853 static $coreLanguageNames;
855 if ( $coreLanguageNames === null ) {
857 include "$IP/languages/Names.php";
863 # TODO: also include when $inLanguage is null, when this code is more efficient
864 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
867 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
868 foreach ( $mwNames as $mwCode => $mwName ) {
869 # - Prefer own MediaWiki native name when not using the hook
870 # - For other names just add if not added through the hook
871 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
872 $names[$mwCode] = $mwName;
876 if ( $include === 'all' ) {
881 $coreCodes = array_keys( $mwNames );
882 foreach ( $coreCodes as $coreCode ) {
883 $returnMw[$coreCode] = $names[$coreCode];
886 if ( $include === 'mwfile' ) {
887 $namesMwFile = array();
888 # We do this using a foreach over the codes instead of a directory
889 # loop so that messages files in extensions will work correctly.
890 foreach ( $returnMw as $code => $value ) {
891 if ( is_readable( self
::getMessagesFileName( $code ) )
892 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
894 $namesMwFile[$code] = $names[$code];
901 # 'mw' option; default if it's not one of the other two options (all/mwfile)
906 * @param string $code The code of the language for which to get the name
907 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
908 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
909 * @return string Language name or empty
912 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
913 $code = strtolower( $code );
914 $array = self
::fetchLanguageNames( $inLanguage, $include );
915 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
919 * Get a message from the MediaWiki namespace.
921 * @param string $msg Message name
924 function getMessageFromDB( $msg ) {
925 return wfMessage( $msg )->inLanguage( $this )->text();
929 * Get the native language name of $code.
930 * Only if defined in MediaWiki, no other data like CLDR.
931 * @param string $code
933 * @deprecated since 1.20, use fetchLanguageName()
935 function getLanguageName( $code ) {
936 return self
::fetchLanguageName( $code );
943 function getMonthName( $key ) {
944 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
950 function getMonthNamesArray() {
951 $monthNames = array( '' );
952 for ( $i = 1; $i < 13; $i++
) {
953 $monthNames[] = $this->getMonthName( $i );
962 function getMonthNameGen( $key ) {
963 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
970 function getMonthAbbreviation( $key ) {
971 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
977 function getMonthAbbreviationsArray() {
978 $monthNames = array( '' );
979 for ( $i = 1; $i < 13; $i++
) {
980 $monthNames[] = $this->getMonthAbbreviation( $i );
989 function getWeekdayName( $key ) {
990 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
997 function getWeekdayAbbreviation( $key ) {
998 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1002 * @param string $key
1005 function getIranianCalendarMonthName( $key ) {
1006 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1010 * @param string $key
1013 function getHebrewCalendarMonthName( $key ) {
1014 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1018 * @param string $key
1021 function getHebrewCalendarMonthNameGen( $key ) {
1022 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1026 * @param string $key
1029 function getHijriCalendarMonthName( $key ) {
1030 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1034 * Pass through result from $dateTimeObj->format()
1036 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1037 if ( !$dateTimeObj ) {
1038 $dateTimeObj = DateTime
::createFromFormat(
1039 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1042 return $dateTimeObj->format( $code );
1046 * This is a workalike of PHP's date() function, but with better
1047 * internationalisation, a reduced set of format characters, and a better
1050 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1051 * the PHP manual for definitions. There are a number of extensions, which
1054 * xn Do not translate digits of the next numeric format character
1055 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1056 * xr Use roman numerals for the next numeric format character
1057 * xh Use hebrew numerals for the next numeric format character
1059 * xg Genitive month name
1061 * xij j (day number) in Iranian calendar
1062 * xiF F (month name) in Iranian calendar
1063 * xin n (month number) in Iranian calendar
1064 * xiy y (two digit year) in Iranian calendar
1065 * xiY Y (full year) in Iranian calendar
1067 * xjj j (day number) in Hebrew calendar
1068 * xjF F (month name) in Hebrew calendar
1069 * xjt t (days in month) in Hebrew calendar
1070 * xjx xg (genitive month name) in Hebrew calendar
1071 * xjn n (month number) in Hebrew calendar
1072 * xjY Y (full year) in Hebrew calendar
1074 * xmj j (day number) in Hijri calendar
1075 * xmF F (month name) in Hijri calendar
1076 * xmn n (month number) in Hijri calendar
1077 * xmY Y (full year) in Hijri calendar
1079 * xkY Y (full year) in Thai solar calendar. Months and days are
1080 * identical to the Gregorian calendar
1081 * xoY Y (full year) in Minguo calendar or Juche year.
1082 * Months and days are identical to the
1083 * Gregorian calendar
1084 * xtY Y (full year) in Japanese nengo. Months and days are
1085 * identical to the Gregorian calendar
1087 * Characters enclosed in double quotes will be considered literal (with
1088 * the quotes themselves removed). Unmatched quotes will be considered
1089 * literal quotes. Example:
1091 * "The month is" F => The month is January
1094 * Backslash escaping is also supported.
1096 * Input timestamp is assumed to be pre-normalized to the desired local
1097 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1098 * $ts is UTC if $zone is not given.
1100 * @param string $format
1101 * @param string $ts 14-character timestamp
1104 * @param DateTimeZone $zone Timezone of $ts
1105 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1106 * Only makes sense if $ts is the current time.
1107 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1109 * @throws MWException
1112 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1117 $dateTimeObj = false;
1126 $usedSecond = false;
1127 $usedMinute = false;
1134 $usedISOYear = false;
1135 $usedIsLeapYear = false;
1137 $usedHebrewMonth = false;
1138 $usedIranianMonth = false;
1139 $usedHijriMonth = false;
1140 $usedHebrewYear = false;
1141 $usedIranianYear = false;
1142 $usedHijriYear = false;
1143 $usedTennoYear = false;
1145 if ( strlen( $ts ) !== 14 ) {
1146 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1149 if ( !ctype_digit( $ts ) ) {
1150 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1153 $formatLength = strlen( $format );
1154 for ( $p = 0; $p < $formatLength; $p++
) {
1156 $code = $format[$p];
1157 if ( $code == 'x' && $p < $formatLength - 1 ) {
1158 $code .= $format[++
$p];
1161 if ( ( $code === 'xi'
1167 && $p < $formatLength - 1 ) {
1168 $code .= $format[++
$p];
1179 $rawToggle = !$rawToggle;
1189 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1192 $usedHebrewMonth = true;
1194 $hebrew = self
::tsToHebrew( $ts );
1196 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1200 $num = substr( $ts, 6, 2 );
1204 $s .= $this->getWeekdayAbbreviation( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1208 $num = intval( substr( $ts, 6, 2 ) );
1213 $iranian = self
::tsToIranian( $ts );
1220 $hijri = self
::tsToHijri( $ts );
1227 $hebrew = self
::tsToHebrew( $ts );
1233 $s .= $this->getWeekdayName( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1237 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1240 $usedIranianMonth = true;
1242 $iranian = self
::tsToIranian( $ts );
1244 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1247 $usedHijriMonth = true;
1249 $hijri = self
::tsToHijri( $ts );
1251 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1254 $usedHebrewMonth = true;
1256 $hebrew = self
::tsToHebrew( $ts );
1258 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1262 $num = substr( $ts, 4, 2 );
1266 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1270 $num = intval( substr( $ts, 4, 2 ) );
1273 $usedIranianMonth = true;
1275 $iranian = self
::tsToIranian( $ts );
1280 $usedHijriMonth = true;
1282 $hijri = self
::tsToHijri ( $ts );
1287 $usedHebrewMonth = true;
1289 $hebrew = self
::tsToHebrew( $ts );
1294 $usedHebrewMonth = true;
1296 $hebrew = self
::tsToHebrew( $ts );
1302 $num = substr( $ts, 0, 4 );
1305 $usedIranianYear = true;
1307 $iranian = self
::tsToIranian( $ts );
1312 $usedHijriYear = true;
1314 $hijri = self
::tsToHijri( $ts );
1319 $usedHebrewYear = true;
1321 $hebrew = self
::tsToHebrew( $ts );
1328 $thai = self
::tsToYear( $ts, 'thai' );
1335 $minguo = self
::tsToYear( $ts, 'minguo' );
1340 $usedTennoYear = true;
1342 $tenno = self
::tsToYear( $ts, 'tenno' );
1348 $num = substr( $ts, 2, 2 );
1351 $usedIranianYear = true;
1353 $iranian = self
::tsToIranian( $ts );
1355 $num = substr( $iranian[0], -2 );
1359 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1363 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1367 $h = substr( $ts, 8, 2 );
1368 $num = $h %
12 ?
$h %
12 : 12;
1372 $num = intval( substr( $ts, 8, 2 ) );
1376 $h = substr( $ts, 8, 2 );
1377 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1381 $num = substr( $ts, 8, 2 );
1385 $num = substr( $ts, 10, 2 );
1389 $num = substr( $ts, 12, 2 );
1399 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1405 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1409 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1413 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1416 $usedIsLeapYear = true;
1417 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1420 $usedISOYear = true;
1421 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1428 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1431 # Backslash escaping
1432 if ( $p < $formatLength - 1 ) {
1433 $s .= $format[++
$p];
1440 if ( $p < $formatLength - 1 ) {
1441 $endQuote = strpos( $format, '"', $p +
1 );
1442 if ( $endQuote === false ) {
1443 # No terminating quote, assume literal "
1446 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1450 # Quote at end of string, assume literal "
1457 if ( $num !== false ) {
1458 if ( $rawToggle ||
$raw ) {
1461 } elseif ( $roman ) {
1462 $s .= Language
::romanNumeral( $num );
1464 } elseif ( $hebrewNum ) {
1465 $s .= self
::hebrewNumeral( $num );
1468 $s .= $this->formatNum( $num, true );
1473 if ( $usedSecond ) {
1475 } elseif ( $usedMinute ) {
1476 $ttl = 60 - substr( $ts, 12, 2 );
1477 } elseif ( $usedHour ) {
1478 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1479 } elseif ( $usedAMPM ) {
1480 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1481 } elseif ( $usedDay ||
$usedHebrewMonth ||
$usedIranianMonth ||
$usedHijriMonth ||
$usedHebrewYear ||
$usedIranianYear ||
$usedHijriYear ||
$usedTennoYear ) {
1482 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1483 // so that they don't need purged every day.
1484 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1486 $possibleTtls = array();
1487 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1489 $possibleTtls[] = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1490 } elseif ( $usedISOYear ) {
1491 // December 28th falls on the last ISO week of the year, every year.
1492 // The last ISO week of a year can be 52 or 53.
1493 $lastWeekOfISOYear = DateTime
::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?
: new DateTimeZone( 'UTC' ) )->format( 'W' );
1494 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1495 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1496 $timeRemainingInWeek = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1497 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1501 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 +
$timeRemainingInDay;
1502 } elseif ( $usedYear ) {
1503 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1504 +
$timeRemainingInDay;
1505 } elseif ( $usedIsLeapYear ) {
1506 $year = substr( $ts, 0, 4 );
1507 $timeRemainingInYear = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1508 +
$timeRemainingInDay;
1510 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1511 // this isn't a leap year. see when the next one starts
1512 $nextCandidate = $year - $mod +
4;
1513 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1514 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
$timeRemainingInYear;
1516 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
$timeRemainingInYear;
1519 // this is a leap year, so the next year isn't
1520 $possibleTtls[] = $timeRemainingInYear;
1524 if ( $possibleTtls ) {
1525 $ttl = min( $possibleTtls );
1532 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1533 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1536 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1537 * Gregorian dates to Iranian dates. Originally written in C, it
1538 * is released under the terms of GNU Lesser General Public
1539 * License. Conversion to PHP was performed by Niklas Laxström.
1541 * Link: http://www.farsiweb.info/jalali/jalali.c
1547 private static function tsToIranian( $ts ) {
1548 $gy = substr( $ts, 0, 4 ) -1600;
1549 $gm = substr( $ts, 4, 2 ) -1;
1550 $gd = substr( $ts, 6, 2 ) -1;
1552 # Days passed from the beginning (including leap years)
1554 +
floor( ( $gy +
3 ) / 4 )
1555 - floor( ( $gy +
99 ) / 100 )
1556 +
floor( ( $gy +
399 ) / 400 );
1558 // Add days of the past months of this year
1559 for ( $i = 0; $i < $gm; $i++
) {
1560 $gDayNo +
= self
::$GREG_DAYS[$i];
1564 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1568 // Days passed in current month
1569 $gDayNo +
= (int)$gd;
1571 $jDayNo = $gDayNo - 79;
1573 $jNp = floor( $jDayNo / 12053 );
1576 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1579 if ( $jDayNo >= 366 ) {
1580 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1581 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1584 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1585 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1591 return array( $jy, $jm, $jd );
1595 * Converting Gregorian dates to Hijri dates.
1597 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1599 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1605 private static function tsToHijri( $ts ) {
1606 $year = substr( $ts, 0, 4 );
1607 $month = substr( $ts, 4, 2 );
1608 $day = substr( $ts, 6, 2 );
1616 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1617 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1619 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1620 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1621 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1624 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1625 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1628 $zl = $zjd -1948440 +
10632;
1629 $zn = (int)( ( $zl - 1 ) / 10631 );
1630 $zl = $zl - 10631 * $zn +
354;
1631 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1632 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1633 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1634 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1635 $zm = (int)( ( 24 * $zl ) / 709 );
1636 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1637 $zy = 30 * $zn +
$zj - 30;
1639 return array( $zy, $zm, $zd );
1643 * Converting Gregorian dates to Hebrew dates.
1645 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1646 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1647 * to translate the relevant functions into PHP and release them under
1650 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1651 * and Adar II is 14. In a non-leap year, Adar is 6.
1657 private static function tsToHebrew( $ts ) {
1659 $year = substr( $ts, 0, 4 );
1660 $month = substr( $ts, 4, 2 );
1661 $day = substr( $ts, 6, 2 );
1663 # Calculate Hebrew year
1664 $hebrewYear = $year +
3760;
1666 # Month number when September = 1, August = 12
1668 if ( $month > 12 ) {
1675 # Calculate day of year from 1 September
1677 for ( $i = 1; $i < $month; $i++
) {
1681 # Check if the year is leap
1682 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1685 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1692 # Calculate the start of the Hebrew year
1693 $start = self
::hebrewYearStart( $hebrewYear );
1695 # Calculate next year's start
1696 if ( $dayOfYear <= $start ) {
1697 # Day is before the start of the year - it is the previous year
1699 $nextStart = $start;
1703 # Add days since previous year's 1 September
1705 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1709 # Start of the new (previous) year
1710 $start = self
::hebrewYearStart( $hebrewYear );
1713 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1716 # Calculate Hebrew day of year
1717 $hebrewDayOfYear = $dayOfYear - $start;
1719 # Difference between year's days
1720 $diff = $nextStart - $start;
1721 # Add 12 (or 13 for leap years) days to ignore the difference between
1722 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1723 # difference is only about the year type
1724 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1730 # Check the year pattern, and is leap year
1731 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1732 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1733 # and non-leap years
1734 $yearPattern = $diff %
30;
1735 # Check if leap year
1736 $isLeap = $diff >= 30;
1738 # Calculate day in the month from number of day in the Hebrew year
1739 # Don't check Adar - if the day is not in Adar, we will stop before;
1740 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1741 $hebrewDay = $hebrewDayOfYear;
1744 while ( $hebrewMonth <= 12 ) {
1745 # Calculate days in this month
1746 if ( $isLeap && $hebrewMonth == 6 ) {
1747 # Adar in a leap year
1749 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1751 if ( $hebrewDay <= $days ) {
1755 # Subtract the days of Adar I
1756 $hebrewDay -= $days;
1759 if ( $hebrewDay <= $days ) {
1765 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1766 # Cheshvan in a complete year (otherwise as the rule below)
1768 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1769 # Kislev in an incomplete year (otherwise as the rule below)
1772 # Odd months have 30 days, even have 29
1773 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1775 if ( $hebrewDay <= $days ) {
1776 # In the current month
1779 # Subtract the days of the current month
1780 $hebrewDay -= $days;
1781 # Try in the next month
1786 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1790 * This calculates the Hebrew year start, as days since 1 September.
1791 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1792 * Used for Hebrew date.
1798 private static function hebrewYearStart( $year ) {
1799 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1800 $b = intval( ( $year - 1 ) %
4 );
1801 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1805 $Mar = intval( $m );
1811 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1812 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1814 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1816 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1820 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1825 * Algorithm to convert Gregorian dates to Thai solar dates,
1826 * Minguo dates or Minguo dates.
1828 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1829 * http://en.wikipedia.org/wiki/Minguo_calendar
1830 * http://en.wikipedia.org/wiki/Japanese_era_name
1832 * @param string $ts 14-character timestamp
1833 * @param string $cName Calender name
1834 * @return array Converted year, month, day
1836 private static function tsToYear( $ts, $cName ) {
1837 $gy = substr( $ts, 0, 4 );
1838 $gm = substr( $ts, 4, 2 );
1839 $gd = substr( $ts, 6, 2 );
1841 if ( !strcmp( $cName, 'thai' ) ) {
1843 # Add 543 years to the Gregorian calendar
1844 # Months and days are identical
1845 $gy_offset = $gy +
543;
1846 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1848 # Deduct 1911 years from the Gregorian calendar
1849 # Months and days are identical
1850 $gy_offset = $gy - 1911;
1851 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1852 # Nengō dates up to Meiji period
1853 # Deduct years from the Gregorian calendar
1854 # depending on the nengo periods
1855 # Months and days are identical
1857 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1858 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1861 $gy_gannen = $gy - 1868 +
1;
1862 $gy_offset = $gy_gannen;
1863 if ( $gy_gannen == 1 ) {
1866 $gy_offset = '明治' . $gy_offset;
1868 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1869 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1870 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1871 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1872 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1875 $gy_gannen = $gy - 1912 +
1;
1876 $gy_offset = $gy_gannen;
1877 if ( $gy_gannen == 1 ) {
1880 $gy_offset = '大正' . $gy_offset;
1882 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1883 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1884 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1887 $gy_gannen = $gy - 1926 +
1;
1888 $gy_offset = $gy_gannen;
1889 if ( $gy_gannen == 1 ) {
1892 $gy_offset = '昭和' . $gy_offset;
1895 $gy_gannen = $gy - 1989 +
1;
1896 $gy_offset = $gy_gannen;
1897 if ( $gy_gannen == 1 ) {
1900 $gy_offset = '平成' . $gy_offset;
1906 return array( $gy_offset, $gm, $gd );
1910 * Roman number formatting up to 10000
1916 static function romanNumeral( $num ) {
1917 static $table = array(
1918 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1919 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1920 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1921 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1922 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1925 $num = intval( $num );
1926 if ( $num > 10000 ||
$num <= 0 ) {
1931 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1932 if ( $num >= $pow10 ) {
1933 $s .= $table[$i][(int)floor( $num / $pow10 )];
1935 $num = $num %
$pow10;
1941 * Hebrew Gematria number formatting up to 9999
1947 static function hebrewNumeral( $num ) {
1948 static $table = array(
1949 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1950 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1951 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1952 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1955 $num = intval( $num );
1956 if ( $num > 9999 ||
$num <= 0 ) {
1961 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1962 if ( $num >= $pow10 ) {
1963 if ( $num == 15 ||
$num == 16 ) {
1964 $s .= $table[0][9] . $table[0][$num - 9];
1967 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1968 if ( $pow10 == 1000 ) {
1973 $num = $num %
$pow10;
1975 if ( strlen( $s ) == 2 ) {
1978 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1979 $str .= substr( $s, strlen( $s ) - 2, 2 );
1981 $start = substr( $str, 0, strlen( $str ) - 2 );
1982 $end = substr( $str, strlen( $str ) - 2 );
1985 $str = $start . 'ך';
1988 $str = $start . 'ם';
1991 $str = $start . 'ן';
1994 $str = $start . 'ף';
1997 $str = $start . 'ץ';
2004 * Used by date() and time() to adjust the time output.
2006 * @param string $ts The time in date('YmdHis') format
2007 * @param mixed $tz Adjust the time by this amount (default false, mean we
2008 * get user timecorrection setting)
2011 function userAdjust( $ts, $tz = false ) {
2012 global $wgUser, $wgLocalTZoffset;
2014 if ( $tz === false ) {
2015 $tz = $wgUser->getOption( 'timecorrection' );
2018 $data = explode( '|', $tz, 3 );
2020 if ( $data[0] == 'ZoneInfo' ) {
2021 wfSuppressWarnings();
2022 $userTZ = timezone_open( $data[2] );
2023 wfRestoreWarnings();
2024 if ( $userTZ !== false ) {
2025 $date = date_create( $ts, timezone_open( 'UTC' ) );
2026 date_timezone_set( $date, $userTZ );
2027 $date = date_format( $date, 'YmdHis' );
2030 # Unrecognized timezone, default to 'Offset' with the stored offset.
2031 $data[0] = 'Offset';
2034 if ( $data[0] == 'System' ||
$tz == '' ) {
2035 # Global offset in minutes.
2036 $minDiff = $wgLocalTZoffset;
2037 } elseif ( $data[0] == 'Offset' ) {
2038 $minDiff = intval( $data[1] );
2040 $data = explode( ':', $tz );
2041 if ( count( $data ) == 2 ) {
2042 $data[0] = intval( $data[0] );
2043 $data[1] = intval( $data[1] );
2044 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2045 if ( $data[0] < 0 ) {
2046 $minDiff = -$minDiff;
2049 $minDiff = intval( $data[0] ) * 60;
2053 # No difference ? Return time unchanged
2054 if ( 0 == $minDiff ) {
2058 wfSuppressWarnings(); // E_STRICT system time bitching
2059 # Generate an adjusted date; take advantage of the fact that mktime
2060 # will normalize out-of-range values so we don't have to split $minDiff
2061 # into hours and minutes.
2063 (int)substr( $ts, 8, 2 ) ), # Hours
2064 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2065 (int)substr( $ts, 12, 2 ), # Seconds
2066 (int)substr( $ts, 4, 2 ), # Month
2067 (int)substr( $ts, 6, 2 ), # Day
2068 (int)substr( $ts, 0, 4 ) ); # Year
2070 $date = date( 'YmdHis', $t );
2071 wfRestoreWarnings();
2077 * This is meant to be used by time(), date(), and timeanddate() to get
2078 * the date preference they're supposed to use, it should be used in
2082 * function timeanddate([...], $format = true) {
2083 * $datePreference = $this->dateFormat($format);
2088 * @param int|string|bool $usePrefs If true, the user's preference is used
2089 * if false, the site/language default is used
2090 * if int/string, assumed to be a format.
2093 function dateFormat( $usePrefs = true ) {
2096 if ( is_bool( $usePrefs ) ) {
2098 $datePreference = $wgUser->getDatePreference();
2100 $datePreference = (string)User
::getDefaultOption( 'date' );
2103 $datePreference = (string)$usePrefs;
2107 if ( $datePreference == '' ) {
2111 return $datePreference;
2115 * Get a format string for a given type and preference
2116 * @param string $type May be date, time or both
2117 * @param string $pref The format name as it appears in Messages*.php
2119 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2123 function getDateFormatString( $type, $pref ) {
2124 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2125 if ( $pref == 'default' ) {
2126 $pref = $this->getDefaultDateFormat();
2127 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2129 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2131 if ( $type === 'pretty' && $df === null ) {
2132 $df = $this->getDateFormatString( 'date', $pref );
2135 if ( $df === null ) {
2136 $pref = $this->getDefaultDateFormat();
2137 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2140 $this->dateFormatStrings
[$type][$pref] = $df;
2142 return $this->dateFormatStrings
[$type][$pref];
2146 * @param string $ts The time format which needs to be turned into a
2147 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2148 * @param bool $adj Whether to adjust the time output according to the
2149 * user configured offset ($timecorrection)
2150 * @param mixed $format True to use user's date format preference
2151 * @param string|bool $timecorrection The time offset as returned by
2152 * validateTimeZone() in Special:Preferences
2155 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2156 $ts = wfTimestamp( TS_MW
, $ts );
2158 $ts = $this->userAdjust( $ts, $timecorrection );
2160 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2161 return $this->sprintfDate( $df, $ts );
2165 * @param string $ts The time format which needs to be turned into a
2166 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2167 * @param bool $adj Whether to adjust the time output according to the
2168 * user configured offset ($timecorrection)
2169 * @param mixed $format True to use user's date format preference
2170 * @param string|bool $timecorrection The time offset as returned by
2171 * validateTimeZone() in Special:Preferences
2174 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2175 $ts = wfTimestamp( TS_MW
, $ts );
2177 $ts = $this->userAdjust( $ts, $timecorrection );
2179 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2180 return $this->sprintfDate( $df, $ts );
2184 * @param string $ts The time format which needs to be turned into a
2185 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2186 * @param bool $adj Whether to adjust the time output according to the
2187 * user configured offset ($timecorrection)
2188 * @param mixed $format What format to return, if it's false output the
2189 * default one (default true)
2190 * @param string|bool $timecorrection The time offset as returned by
2191 * validateTimeZone() in Special:Preferences
2194 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2195 $ts = wfTimestamp( TS_MW
, $ts );
2197 $ts = $this->userAdjust( $ts, $timecorrection );
2199 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2200 return $this->sprintfDate( $df, $ts );
2204 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2208 * @param int $seconds The amount of seconds.
2209 * @param array $chosenIntervals The intervals to enable.
2213 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2214 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2216 $segments = array();
2218 foreach ( $intervals as $intervalName => $intervalValue ) {
2219 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2220 // duration-years, duration-decades, duration-centuries, duration-millennia
2221 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2222 $segments[] = $message->inLanguage( $this )->escaped();
2225 return $this->listToText( $segments );
2229 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2230 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2234 * @param int $seconds The amount of seconds.
2235 * @param array $chosenIntervals The intervals to enable.
2239 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2240 if ( empty( $chosenIntervals ) ) {
2241 $chosenIntervals = array(
2253 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2254 $sortedNames = array_keys( $intervals );
2255 $smallestInterval = array_pop( $sortedNames );
2257 $segments = array();
2259 foreach ( $intervals as $name => $length ) {
2260 $value = floor( $seconds / $length );
2262 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2263 $seconds -= $value * $length;
2264 $segments[$name] = $value;
2272 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2274 * @param string $type Can be 'date', 'time' or 'both'
2275 * @param string $ts The time format which needs to be turned into a
2276 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2277 * @param User $user User object used to get preferences for timezone and format
2278 * @param array $options Array, can contain the following keys:
2279 * - 'timecorrection': time correction, can have the following values:
2280 * - true: use user's preference
2281 * - false: don't use time correction
2282 * - int: value of time correction in minutes
2283 * - 'format': format to use, can have the following values:
2284 * - true: use user's preference
2285 * - false: use default preference
2286 * - string: format to use
2290 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2291 $ts = wfTimestamp( TS_MW
, $ts );
2292 $options +
= array( 'timecorrection' => true, 'format' => true );
2293 if ( $options['timecorrection'] !== false ) {
2294 if ( $options['timecorrection'] === true ) {
2295 $offset = $user->getOption( 'timecorrection' );
2297 $offset = $options['timecorrection'];
2299 $ts = $this->userAdjust( $ts, $offset );
2301 if ( $options['format'] === true ) {
2302 $format = $user->getDatePreference();
2304 $format = $options['format'];
2306 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2307 return $this->sprintfDate( $df, $ts );
2311 * Get the formatted date for the given timestamp and formatted for
2314 * @param mixed $ts Mixed: the time format which needs to be turned into a
2315 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2316 * @param User $user User object used to get preferences for timezone and format
2317 * @param array $options Array, can contain the following keys:
2318 * - 'timecorrection': time correction, can have the following values:
2319 * - true: use user's preference
2320 * - false: don't use time correction
2321 * - int: value of time correction in minutes
2322 * - 'format': format to use, can have the following values:
2323 * - true: use user's preference
2324 * - false: use default preference
2325 * - string: format to use
2329 public function userDate( $ts, User
$user, array $options = array() ) {
2330 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2334 * Get the formatted time for the given timestamp and formatted for
2337 * @param mixed $ts The time format which needs to be turned into a
2338 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2339 * @param User $user User object used to get preferences for timezone and format
2340 * @param array $options Array, can contain the following keys:
2341 * - 'timecorrection': time correction, can have the following values:
2342 * - true: use user's preference
2343 * - false: don't use time correction
2344 * - int: value of time correction in minutes
2345 * - 'format': format to use, can have the following values:
2346 * - true: use user's preference
2347 * - false: use default preference
2348 * - string: format to use
2352 public function userTime( $ts, User
$user, array $options = array() ) {
2353 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2357 * Get the formatted date and time for the given timestamp and formatted for
2360 * @param mixed $ts the time format which needs to be turned into a
2361 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2362 * @param User $user User object used to get preferences for timezone and format
2363 * @param array $options Array, can contain the following keys:
2364 * - 'timecorrection': time correction, can have the following values:
2365 * - true: use user's preference
2366 * - false: don't use time correction
2367 * - int: value of time correction in minutes
2368 * - 'format': format to use, can have the following values:
2369 * - true: use user's preference
2370 * - false: use default preference
2371 * - string: format to use
2375 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2376 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2380 * Convert an MWTimestamp into a pretty human-readable timestamp using
2381 * the given user preferences and relative base time.
2383 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2384 * on your timestamp object, which will then call this function. Calling
2385 * this function directly will cause hooks to be skipped over.
2387 * @see MWTimestamp::getHumanTimestamp
2388 * @param MWTimestamp $ts Timestamp to prettify
2389 * @param MWTimestamp $relativeTo Base timestamp
2390 * @param User $user User preferences to use
2391 * @return string Human timestamp
2394 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2395 $diff = $ts->diff( $relativeTo );
2396 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2397 (int)$relativeTo->timestamp
->format( 'w' ) );
2398 $days = $diff->days ?
: (int)$diffDay;
2399 if ( $diff->invert ||
$days > 5
2400 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2402 // Timestamps are in different years: use full timestamp
2403 // Also do full timestamp for future dates
2405 * @FIXME Add better handling of future timestamps.
2407 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2408 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2409 } elseif ( $days > 5 ) {
2410 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2411 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2412 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2413 } elseif ( $days > 1 ) {
2414 // Timestamp within the past week: show the day of the week and time
2415 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2416 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2418 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2419 $ts = wfMessage( "$weekday-at" )
2420 ->inLanguage( $this )
2421 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2423 } elseif ( $days == 1 ) {
2424 // Timestamp was yesterday: say 'yesterday' and the time.
2425 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2426 $ts = wfMessage( 'yesterday-at' )
2427 ->inLanguage( $this )
2428 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2430 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2431 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2432 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2433 $ts = wfMessage( 'today-at' )
2434 ->inLanguage( $this )
2435 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2438 // From here on in, the timestamp was soon enough ago so that we can simply say
2439 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2440 } elseif ( $diff->h
== 1 ) {
2441 // Less than 90 minutes, but more than an hour ago.
2442 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2443 } elseif ( $diff->i
>= 1 ) {
2444 // A few minutes ago.
2445 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2446 } elseif ( $diff->s
>= 30 ) {
2447 // Less than a minute, but more than 30 sec ago.
2448 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2450 // Less than 30 seconds ago.
2451 $ts = wfMessage( 'just-now' )->text();
2458 * @param string $key
2459 * @return array|null
2461 function getMessage( $key ) {
2462 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2468 function getAllMessages() {
2469 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2474 * @param string $out
2475 * @param string $string
2478 function iconv( $in, $out, $string ) {
2479 # This is a wrapper for iconv in all languages except esperanto,
2480 # which does some nasty x-conversions beforehand
2482 # Even with //IGNORE iconv can whine about illegal characters in
2483 # *input* string. We just ignore those too.
2484 # REF: http://bugs.php.net/bug.php?id=37166
2485 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2486 wfSuppressWarnings();
2487 $text = iconv( $in, $out . '//IGNORE', $string );
2488 wfRestoreWarnings();
2492 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2495 * @param array $matches
2496 * @return mixed|string
2498 function ucwordbreaksCallbackAscii( $matches ) {
2499 return $this->ucfirst( $matches[1] );
2503 * @param array $matches
2506 function ucwordbreaksCallbackMB( $matches ) {
2507 return mb_strtoupper( $matches[0] );
2511 * @param array $matches
2514 function ucCallback( $matches ) {
2515 list( $wikiUpperChars ) = self
::getCaseMaps();
2516 return strtr( $matches[1], $wikiUpperChars );
2520 * @param array $matches
2523 function lcCallback( $matches ) {
2524 list( , $wikiLowerChars ) = self
::getCaseMaps();
2525 return strtr( $matches[1], $wikiLowerChars );
2529 * @param array $matches
2532 function ucwordsCallbackMB( $matches ) {
2533 return mb_strtoupper( $matches[0] );
2537 * @param array $matches
2540 function ucwordsCallbackWiki( $matches ) {
2541 list( $wikiUpperChars ) = self
::getCaseMaps();
2542 return strtr( $matches[0], $wikiUpperChars );
2546 * Make a string's first character uppercase
2548 * @param string $str
2552 function ucfirst( $str ) {
2554 if ( $o < 96 ) { // if already uppercase...
2556 } elseif ( $o < 128 ) {
2557 return ucfirst( $str ); // use PHP's ucfirst()
2559 // fall back to more complex logic in case of multibyte strings
2560 return $this->uc( $str, true );
2565 * Convert a string to uppercase
2567 * @param string $str
2568 * @param bool $first
2572 function uc( $str, $first = false ) {
2573 if ( function_exists( 'mb_strtoupper' ) ) {
2575 if ( $this->isMultibyte( $str ) ) {
2576 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2578 return ucfirst( $str );
2581 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2584 if ( $this->isMultibyte( $str ) ) {
2585 $x = $first ?
'^' : '';
2586 return preg_replace_callback(
2587 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2588 array( $this, 'ucCallback' ),
2592 return $first ?
ucfirst( $str ) : strtoupper( $str );
2598 * @param string $str
2599 * @return mixed|string
2601 function lcfirst( $str ) {
2604 return strval( $str );
2605 } elseif ( $o >= 128 ) {
2606 return $this->lc( $str, true );
2607 } elseif ( $o > 96 ) {
2610 $str[0] = strtolower( $str[0] );
2616 * @param string $str
2617 * @param bool $first
2618 * @return mixed|string
2620 function lc( $str, $first = false ) {
2621 if ( function_exists( 'mb_strtolower' ) ) {
2623 if ( $this->isMultibyte( $str ) ) {
2624 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2626 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2629 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2632 if ( $this->isMultibyte( $str ) ) {
2633 $x = $first ?
'^' : '';
2634 return preg_replace_callback(
2635 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2636 array( $this, 'lcCallback' ),
2640 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2646 * @param string $str
2649 function isMultibyte( $str ) {
2650 return (bool)preg_match( '/[\x80-\xff]/', $str );
2654 * @param string $str
2655 * @return mixed|string
2657 function ucwords( $str ) {
2658 if ( $this->isMultibyte( $str ) ) {
2659 $str = $this->lc( $str );
2661 // regexp to find first letter in each word (i.e. after each space)
2662 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2664 // function to use to capitalize a single char
2665 if ( function_exists( 'mb_strtoupper' ) ) {
2666 return preg_replace_callback(
2668 array( $this, 'ucwordsCallbackMB' ),
2672 return preg_replace_callback(
2674 array( $this, 'ucwordsCallbackWiki' ),
2679 return ucwords( strtolower( $str ) );
2684 * capitalize words at word breaks
2686 * @param string $str
2689 function ucwordbreaks( $str ) {
2690 if ( $this->isMultibyte( $str ) ) {
2691 $str = $this->lc( $str );
2693 // since \b doesn't work for UTF-8, we explicitely define word break chars
2694 $breaks = "[ \-\(\)\}\{\.,\?!]";
2696 // find first letter after word break
2697 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2698 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2700 if ( function_exists( 'mb_strtoupper' ) ) {
2701 return preg_replace_callback(
2703 array( $this, 'ucwordbreaksCallbackMB' ),
2707 return preg_replace_callback(
2709 array( $this, 'ucwordsCallbackWiki' ),
2714 return preg_replace_callback(
2715 '/\b([\w\x80-\xff]+)\b/',
2716 array( $this, 'ucwordbreaksCallbackAscii' ),
2723 * Return a case-folded representation of $s
2725 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2726 * and $s2 are the same except for the case of their characters. It is not
2727 * necessary for the value returned to make sense when displayed.
2729 * Do *not* perform any other normalisation in this function. If a caller
2730 * uses this function when it should be using a more general normalisation
2731 * function, then fix the caller.
2737 function caseFold( $s ) {
2738 return $this->uc( $s );
2745 function checkTitleEncoding( $s ) {
2746 if ( is_array( $s ) ) {
2747 throw new MWException( 'Given array to checkTitleEncoding.' );
2749 if ( StringUtils
::isUtf8( $s ) ) {
2753 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2759 function fallback8bitEncoding() {
2760 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2764 * Most writing systems use whitespace to break up words.
2765 * Some languages such as Chinese don't conventionally do this,
2766 * which requires special handling when breaking up words for
2771 function hasWordBreaks() {
2776 * Some languages such as Chinese require word segmentation,
2777 * Specify such segmentation when overridden in derived class.
2779 * @param string $string
2782 function segmentByWord( $string ) {
2787 * Some languages have special punctuation need to be normalized.
2788 * Make such changes here.
2790 * @param string $string
2793 function normalizeForSearch( $string ) {
2794 return self
::convertDoubleWidth( $string );
2798 * convert double-width roman characters to single-width.
2799 * range: ff00-ff5f ~= 0020-007f
2801 * @param string $string
2805 protected static function convertDoubleWidth( $string ) {
2806 static $full = null;
2807 static $half = null;
2809 if ( $full === null ) {
2810 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2811 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2812 $full = str_split( $fullWidth, 3 );
2813 $half = str_split( $halfWidth );
2816 $string = str_replace( $full, $half, $string );
2821 * @param string $string
2822 * @param string $pattern
2825 protected static function insertSpace( $string, $pattern ) {
2826 $string = preg_replace( $pattern, " $1 ", $string );
2827 $string = preg_replace( '/ +/', ' ', $string );
2832 * @param array $termsArray
2835 function convertForSearchResult( $termsArray ) {
2836 # some languages, e.g. Chinese, need to do a conversion
2837 # in order for search results to be displayed correctly
2842 * Get the first character of a string.
2847 function firstChar( $s ) {
2850 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2851 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2856 if ( isset( $matches[1] ) ) {
2857 if ( strlen( $matches[1] ) != 3 ) {
2861 // Break down Hangul syllables to grab the first jamo
2862 $code = utf8ToCodepoint( $matches[1] );
2863 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2865 } elseif ( $code < 0xb098 ) {
2866 return "\xe3\x84\xb1";
2867 } elseif ( $code < 0xb2e4 ) {
2868 return "\xe3\x84\xb4";
2869 } elseif ( $code < 0xb77c ) {
2870 return "\xe3\x84\xb7";
2871 } elseif ( $code < 0xb9c8 ) {
2872 return "\xe3\x84\xb9";
2873 } elseif ( $code < 0xbc14 ) {
2874 return "\xe3\x85\x81";
2875 } elseif ( $code < 0xc0ac ) {
2876 return "\xe3\x85\x82";
2877 } elseif ( $code < 0xc544 ) {
2878 return "\xe3\x85\x85";
2879 } elseif ( $code < 0xc790 ) {
2880 return "\xe3\x85\x87";
2881 } elseif ( $code < 0xcc28 ) {
2882 return "\xe3\x85\x88";
2883 } elseif ( $code < 0xce74 ) {
2884 return "\xe3\x85\x8a";
2885 } elseif ( $code < 0xd0c0 ) {
2886 return "\xe3\x85\x8b";
2887 } elseif ( $code < 0xd30c ) {
2888 return "\xe3\x85\x8c";
2889 } elseif ( $code < 0xd558 ) {
2890 return "\xe3\x85\x8d";
2892 return "\xe3\x85\x8e";
2899 function initEncoding() {
2900 # Some languages may have an alternate char encoding option
2901 # (Esperanto X-coding, Japanese furigana conversion, etc)
2902 # If this language is used as the primary content language,
2903 # an override to the defaults can be set here on startup.
2910 function recodeForEdit( $s ) {
2911 # For some languages we'll want to explicitly specify
2912 # which characters make it into the edit box raw
2913 # or are converted in some way or another.
2914 global $wgEditEncoding;
2915 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2918 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2926 function recodeInput( $s ) {
2927 # Take the previous into account.
2928 global $wgEditEncoding;
2929 if ( $wgEditEncoding != '' ) {
2930 $enc = $wgEditEncoding;
2934 if ( $enc == 'UTF-8' ) {
2937 return $this->iconv( $enc, 'UTF-8', $s );
2942 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2943 * also cleans up certain backwards-compatible sequences, converting them
2944 * to the modern Unicode equivalent.
2946 * This is language-specific for performance reasons only.
2952 function normalize( $s ) {
2953 global $wgAllUnicodeFixes;
2954 $s = UtfNormal
::cleanUp( $s );
2955 if ( $wgAllUnicodeFixes ) {
2956 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2957 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2964 * Transform a string using serialized data stored in the given file (which
2965 * must be in the serialized subdirectory of $IP). The file contains pairs
2966 * mapping source characters to destination characters.
2968 * The data is cached in process memory. This will go faster if you have the
2969 * FastStringSearch extension.
2971 * @param string $file
2972 * @param string $string
2974 * @throws MWException
2977 function transformUsingPairFile( $file, $string ) {
2978 if ( !isset( $this->transformData
[$file] ) ) {
2979 $data = wfGetPrecompiledData( $file );
2980 if ( $data === false ) {
2981 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2983 $this->transformData
[$file] = new ReplacementArray( $data );
2985 return $this->transformData
[$file]->replace( $string );
2989 * For right-to-left language support
2994 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2998 * Return the correct HTML 'dir' attribute value for this language.
3002 return $this->isRTL() ?
'rtl' : 'ltr';
3006 * Return 'left' or 'right' as appropriate alignment for line-start
3007 * for this language's text direction.
3009 * Should be equivalent to CSS3 'start' text-align value....
3013 function alignStart() {
3014 return $this->isRTL() ?
'right' : 'left';
3018 * Return 'right' or 'left' as appropriate alignment for line-end
3019 * for this language's text direction.
3021 * Should be equivalent to CSS3 'end' text-align value....
3025 function alignEnd() {
3026 return $this->isRTL() ?
'left' : 'right';
3030 * A hidden direction mark (LRM or RLM), depending on the language direction.
3031 * Unlike getDirMark(), this function returns the character as an HTML entity.
3032 * This function should be used when the output is guaranteed to be HTML,
3033 * because it makes the output HTML source code more readable. When
3034 * the output is plain text or can be escaped, getDirMark() should be used.
3036 * @param bool $opposite Get the direction mark opposite to your language
3040 function getDirMarkEntity( $opposite = false ) {
3042 return $this->isRTL() ?
'‎' : '‏';
3044 return $this->isRTL() ?
'‏' : '‎';
3048 * A hidden direction mark (LRM or RLM), depending on the language direction.
3049 * This function produces them as invisible Unicode characters and
3050 * the output may be hard to read and debug, so it should only be used
3051 * when the output is plain text or can be escaped. When the output is
3052 * HTML, use getDirMarkEntity() instead.
3054 * @param bool $opposite Get the direction mark opposite to your language
3057 function getDirMark( $opposite = false ) {
3058 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3059 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3061 return $this->isRTL() ?
$lrm : $rlm;
3063 return $this->isRTL() ?
$rlm : $lrm;
3069 function capitalizeAllNouns() {
3070 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3074 * An arrow, depending on the language direction.
3076 * @param string $direction The direction of the arrow: forwards (default),
3077 * backwards, left, right, up, down.
3080 function getArrow( $direction = 'forwards' ) {
3081 switch ( $direction ) {
3083 return $this->isRTL() ?
'←' : '→';
3085 return $this->isRTL() ?
'→' : '←';
3098 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3102 function linkPrefixExtension() {
3103 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3107 * Get all magic words from cache.
3110 function getMagicWords() {
3111 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3115 * Run the LanguageGetMagic hook once.
3117 protected function doMagicHook() {
3118 if ( $this->mMagicHookDone
) {
3121 $this->mMagicHookDone
= true;
3122 wfProfileIn( 'LanguageGetMagic' );
3123 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3124 wfProfileOut( 'LanguageGetMagic' );
3128 * Fill a MagicWord object with data from here
3130 * @param MagicWord $mw
3132 function getMagic( $mw ) {
3133 // Saves a function call
3134 if ( ! $this->mMagicHookDone
) {
3135 $this->doMagicHook();
3138 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3139 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3141 $rawEntry = self
::$dataCache->getSubitem(
3142 $this->mCode
, 'magicWords', $mw->mId
);
3145 if ( !is_array( $rawEntry ) ) {
3146 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3148 $mw->mCaseSensitive
= $rawEntry[0];
3149 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3154 * Add magic words to the extension array
3156 * @param array $newWords
3158 function addMagicWordsByLang( $newWords ) {
3159 $fallbackChain = $this->getFallbackLanguages();
3160 $fallbackChain = array_reverse( $fallbackChain );
3161 foreach ( $fallbackChain as $code ) {
3162 if ( isset( $newWords[$code] ) ) {
3163 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3169 * Get special page names, as an associative array
3170 * case folded alias => real name
3173 function getSpecialPageAliases() {
3174 // Cache aliases because it may be slow to load them
3175 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3177 $this->mExtendedSpecialPageAliases
=
3178 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3179 wfRunHooks( 'LanguageGetSpecialPageAliases',
3180 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3183 return $this->mExtendedSpecialPageAliases
;
3187 * Italic is unsuitable for some languages
3189 * @param string $text The text to be emphasized.
3192 function emphasize( $text ) {
3193 return "<em>$text</em>";
3197 * Normally we output all numbers in plain en_US style, that is
3198 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3199 * point twohundredthirtyfive. However this is not suitable for all
3200 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3201 * Icelandic just want to use commas instead of dots, and dots instead
3202 * of commas like "293.291,235".
3204 * An example of this function being called:
3206 * wfMessage( 'message' )->numParams( $num )->text()
3209 * See $separatorTransformTable on MessageIs.php for
3210 * the , => . and . => , implementation.
3212 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3213 * @param int|float $number The string to be formatted, should be an integer
3214 * or a floating point number.
3215 * @param bool $nocommafy Set to true for special numbers like dates
3218 public function formatNum( $number, $nocommafy = false ) {
3219 global $wgTranslateNumerals;
3220 if ( !$nocommafy ) {
3221 $number = $this->commafy( $number );
3222 $s = $this->separatorTransformTable();
3224 $number = strtr( $number, $s );
3228 if ( $wgTranslateNumerals ) {
3229 $s = $this->digitTransformTable();
3231 $number = strtr( $number, $s );
3239 * Front-end for non-commafied formatNum
3241 * @param int|float $number The string to be formatted, should be an integer
3242 * or a floating point number.
3246 public function formatNumNoSeparators( $number ) {
3247 return $this->formatNum( $number, true );
3251 * @param string $number
3254 public function parseFormattedNumber( $number ) {
3255 $s = $this->digitTransformTable();
3257 // eliminate empty array values such as ''. (bug 64347)
3258 $s = array_filter( $s );
3259 $number = strtr( $number, array_flip( $s ) );
3262 $s = $this->separatorTransformTable();
3264 // eliminate empty array values such as ''. (bug 64347)
3265 $s = array_filter( $s );
3266 $number = strtr( $number, array_flip( $s ) );
3269 $number = strtr( $number, array( ',' => '' ) );
3274 * Adds commas to a given number
3276 * @param mixed $number
3279 function commafy( $number ) {
3280 $digitGroupingPattern = $this->digitGroupingPattern();
3281 if ( $number === null ) {
3285 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3286 // default grouping is at thousands, use the same for ###,###,### pattern too.
3287 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3289 // Ref: http://cldr.unicode.org/translation/number-patterns
3291 if ( intval( $number ) < 0 ) {
3292 // For negative numbers apply the algorithm like positive number and add sign.
3294 $number = substr( $number, 1 );
3296 $integerPart = array();
3297 $decimalPart = array();
3298 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3299 preg_match( "/\d+/", $number, $integerPart );
3300 preg_match( "/\.\d*/", $number, $decimalPart );
3301 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3302 if ( $groupedNumber === $number ) {
3303 // the string does not have any number part. Eg: .12345
3304 return $sign . $groupedNumber;
3306 $start = $end = strlen( $integerPart[0] );
3307 while ( $start > 0 ) {
3308 $match = $matches[0][$numMatches - 1];
3309 $matchLen = strlen( $match );
3310 $start = $end - $matchLen;
3314 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3316 if ( $numMatches > 1 ) {
3317 // use the last pattern for the rest of the number
3321 $groupedNumber = "," . $groupedNumber;
3324 return $sign . $groupedNumber;
3331 function digitGroupingPattern() {
3332 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3338 function digitTransformTable() {
3339 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3345 function separatorTransformTable() {
3346 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3350 * Take a list of strings and build a locale-friendly comma-separated
3351 * list, using the local comma-separator message.
3352 * The last two strings are chained with an "and".
3353 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3355 * @param string[] $l
3358 function listToText( array $l ) {
3359 $m = count( $l ) - 1;
3364 $and = $this->getMessageFromDB( 'and' );
3365 $space = $this->getMessageFromDB( 'word-separator' );
3367 $comma = $this->getMessageFromDB( 'comma-separator' );
3371 for ( $i = $m - 1; $i >= 0; $i-- ) {
3372 if ( $i == $m - 1 ) {
3373 $s = $l[$i] . $and . $space . $s;
3375 $s = $l[$i] . $comma . $s;
3382 * Take a list of strings and build a locale-friendly comma-separated
3383 * list, using the local comma-separator message.
3384 * @param string[] $list Array of strings to put in a comma list
3387 function commaList( array $list ) {
3389 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3395 * Take a list of strings and build a locale-friendly semicolon-separated
3396 * list, using the local semicolon-separator message.
3397 * @param string[] $list Array of strings to put in a semicolon list
3400 function semicolonList( array $list ) {
3402 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3408 * Same as commaList, but separate it with the pipe instead.
3409 * @param string[] $list Array of strings to put in a pipe list
3412 function pipeList( array $list ) {
3414 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3420 * Truncate a string to a specified length in bytes, appending an optional
3421 * string (e.g. for ellipses)
3423 * The database offers limited byte lengths for some columns in the database;
3424 * multi-byte character sets mean we need to ensure that only whole characters
3425 * are included, otherwise broken characters can be passed to the user
3427 * If $length is negative, the string will be truncated from the beginning
3429 * @param string $string String to truncate
3430 * @param int $length Maximum length (including ellipses)
3431 * @param string $ellipsis String to append to the truncated text
3432 * @param bool $adjustLength Subtract length of ellipsis from $length.
3433 * $adjustLength was introduced in 1.18, before that behaved as if false.
3436 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3437 # Use the localized ellipsis character
3438 if ( $ellipsis == '...' ) {
3439 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3441 # Check if there is no need to truncate
3442 if ( $length == 0 ) {
3443 return $ellipsis; // convention
3444 } elseif ( strlen( $string ) <= abs( $length ) ) {
3445 return $string; // no need to truncate
3447 $stringOriginal = $string;
3448 # If ellipsis length is >= $length then we can't apply $adjustLength
3449 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3450 $string = $ellipsis; // this can be slightly unexpected
3451 # Otherwise, truncate and add ellipsis...
3453 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3454 if ( $length > 0 ) {
3455 $length -= $eLength;
3456 $string = substr( $string, 0, $length ); // xyz...
3457 $string = $this->removeBadCharLast( $string );
3458 $string = rtrim( $string );
3459 $string = $string . $ellipsis;
3461 $length +
= $eLength;
3462 $string = substr( $string, $length ); // ...xyz
3463 $string = $this->removeBadCharFirst( $string );
3464 $string = ltrim( $string );
3465 $string = $ellipsis . $string;
3468 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3469 # This check is *not* redundant if $adjustLength, due to the single case where
3470 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3471 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3474 return $stringOriginal;
3479 * Remove bytes that represent an incomplete Unicode character
3480 * at the end of string (e.g. bytes of the char are missing)
3482 * @param string $string
3485 protected function removeBadCharLast( $string ) {
3486 if ( $string != '' ) {
3487 $char = ord( $string[strlen( $string ) - 1] );
3489 if ( $char >= 0xc0 ) {
3490 # We got the first byte only of a multibyte char; remove it.
3491 $string = substr( $string, 0, -1 );
3492 } elseif ( $char >= 0x80 &&
3493 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3494 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3496 # We chopped in the middle of a character; remove it
3504 * Remove bytes that represent an incomplete Unicode character
3505 * at the start of string (e.g. bytes of the char are missing)
3507 * @param string $string
3510 protected function removeBadCharFirst( $string ) {
3511 if ( $string != '' ) {
3512 $char = ord( $string[0] );
3513 if ( $char >= 0x80 && $char < 0xc0 ) {
3514 # We chopped in the middle of a character; remove the whole thing
3515 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3522 * Truncate a string of valid HTML to a specified length in bytes,
3523 * appending an optional string (e.g. for ellipses), and return valid HTML
3525 * This is only intended for styled/linked text, such as HTML with
3526 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3527 * Also, this will not detect things like "display:none" CSS.
3529 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3531 * @param string $text HTML string to truncate
3532 * @param int $length (zero/positive) Maximum length (including ellipses)
3533 * @param string $ellipsis String to append to the truncated text
3536 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3537 # Use the localized ellipsis character
3538 if ( $ellipsis == '...' ) {
3539 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3541 # Check if there is clearly no need to truncate
3542 if ( $length <= 0 ) {
3543 return $ellipsis; // no text shown, nothing to format (convention)
3544 } elseif ( strlen( $text ) <= $length ) {
3545 return $text; // string short enough even *with* HTML (short-circuit)
3548 $dispLen = 0; // innerHTML legth so far
3549 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3550 $tagType = 0; // 0-open, 1-close
3551 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3552 $entityState = 0; // 0-not entity, 1-entity
3553 $tag = $ret = ''; // accumulated tag name, accumulated result string
3554 $openTags = array(); // open tag stack
3555 $maybeState = null; // possible truncation state
3557 $textLen = strlen( $text );
3558 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3559 for ( $pos = 0; true; ++
$pos ) {
3560 # Consider truncation once the display length has reached the maximim.
3561 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3562 # Check that we're not in the middle of a bracket/entity...
3563 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3564 if ( !$testingEllipsis ) {
3565 $testingEllipsis = true;
3566 # Save where we are; we will truncate here unless there turn out to
3567 # be so few remaining characters that truncation is not necessary.
3568 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3569 $maybeState = array( $ret, $openTags ); // save state
3571 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3572 # String in fact does need truncation, the truncation point was OK.
3573 list( $ret, $openTags ) = $maybeState; // reload state
3574 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3575 $ret .= $ellipsis; // add ellipsis
3579 if ( $pos >= $textLen ) {
3580 break; // extra iteration just for above checks
3583 # Read the next char...
3585 $lastCh = $pos ?
$text[$pos - 1] : '';
3586 $ret .= $ch; // add to result string
3588 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3589 $entityState = 0; // for bad HTML
3590 $bracketState = 1; // tag started (checking for backslash)
3591 } elseif ( $ch == '>' ) {
3592 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3593 $entityState = 0; // for bad HTML
3594 $bracketState = 0; // out of brackets
3595 } elseif ( $bracketState == 1 ) {
3597 $tagType = 1; // close tag (e.g. "</span>")
3599 $tagType = 0; // open tag (e.g. "<span>")
3602 $bracketState = 2; // building tag name
3603 } elseif ( $bracketState == 2 ) {
3607 // Name found (e.g. "<a href=..."), add on tag attributes...
3608 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3610 } elseif ( $bracketState == 0 ) {
3611 if ( $entityState ) {
3614 $dispLen++
; // entity is one displayed char
3617 if ( $neLength == 0 && !$maybeState ) {
3618 // Save state without $ch. We want to *hit* the first
3619 // display char (to get tags) but not *use* it if truncating.
3620 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3623 $entityState = 1; // entity found, (e.g. " ")
3625 $dispLen++
; // this char is displayed
3626 // Add the next $max display text chars after this in one swoop...
3627 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3628 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3629 $dispLen +
= $skipped;
3635 // Close the last tag if left unclosed by bad HTML
3636 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3637 while ( count( $openTags ) > 0 ) {
3638 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3644 * truncateHtml() helper function
3645 * like strcspn() but adds the skipped chars to $ret
3647 * @param string $ret
3648 * @param string $text
3649 * @param string $search
3651 * @param null|int $len
3654 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3655 if ( $len === null ) {
3656 $len = -1; // -1 means "no limit" for strcspn
3657 } elseif ( $len < 0 ) {
3661 if ( $start < strlen( $text ) ) {
3662 $skipCount = strcspn( $text, $search, $start, $len );
3663 $ret .= substr( $text, $start, $skipCount );
3669 * truncateHtml() helper function
3670 * (a) push or pop $tag from $openTags as needed
3671 * (b) clear $tag value
3672 * @param string &$tag Current HTML tag name we are looking at
3673 * @param int $tagType (0-open tag, 1-close tag)
3674 * @param string $lastCh Character before the '>' that ended this tag
3675 * @param array &$openTags Open tag stack (not accounting for $tag)
3677 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3678 $tag = ltrim( $tag );
3680 if ( $tagType == 0 && $lastCh != '/' ) {
3681 $openTags[] = $tag; // tag opened (didn't close itself)
3682 } elseif ( $tagType == 1 ) {
3683 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3684 array_pop( $openTags ); // tag closed
3692 * Grammatical transformations, needed for inflected languages
3693 * Invoked by putting {{grammar:case|word}} in a message
3695 * @param string $word
3696 * @param string $case
3699 function convertGrammar( $word, $case ) {
3700 global $wgGrammarForms;
3701 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3702 return $wgGrammarForms[$this->getCode()][$case][$word];
3708 * Get the grammar forms for the content language
3709 * @return array Array of grammar forms
3712 function getGrammarForms() {
3713 global $wgGrammarForms;
3714 if ( isset( $wgGrammarForms[$this->getCode()] )
3715 && is_array( $wgGrammarForms[$this->getCode()] )
3717 return $wgGrammarForms[$this->getCode()];
3723 * Provides an alternative text depending on specified gender.
3724 * Usage {{gender:username|masculine|feminine|unknown}}.
3725 * username is optional, in which case the gender of current user is used,
3726 * but only in (some) interface messages; otherwise default gender is used.
3728 * If no forms are given, an empty string is returned. If only one form is
3729 * given, it will be returned unconditionally. These details are implied by
3730 * the caller and cannot be overridden in subclasses.
3732 * If three forms are given, the default is to use the third (unknown) form.
3733 * If fewer than three forms are given, the default is to use the first (masculine) form.
3734 * These details can be overridden in subclasses.
3736 * @param string $gender
3737 * @param array $forms
3741 function gender( $gender, $forms ) {
3742 if ( !count( $forms ) ) {
3745 $forms = $this->preConvertPlural( $forms, 2 );
3746 if ( $gender === 'male' ) {
3749 if ( $gender === 'female' ) {
3752 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3756 * Plural form transformations, needed for some languages.
3757 * For example, there are 3 form of plural in Russian and Polish,
3758 * depending on "count mod 10". See [[w:Plural]]
3759 * For English it is pretty simple.
3761 * Invoked by putting {{plural:count|wordform1|wordform2}}
3762 * or {{plural:count|wordform1|wordform2|wordform3}}
3764 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3766 * @param int $count Non-localized number
3767 * @param array $forms Different plural forms
3768 * @return string Correct form of plural for $count in this language
3770 function convertPlural( $count, $forms ) {
3771 // Handle explicit n=pluralform cases
3772 $forms = $this->handleExplicitPluralForms( $count, $forms );
3773 if ( is_string( $forms ) ) {
3776 if ( !count( $forms ) ) {
3780 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3781 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3782 return $forms[$pluralForm];
3786 * Handles explicit plural forms for Language::convertPlural()
3788 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3789 * If an explicitly defined plural form matches the $count, then
3790 * string value returned, otherwise array returned for further consideration
3791 * by CLDR rules or overridden convertPlural().
3795 * @param int $count non-localized number
3796 * @param array $forms different plural forms
3798 * @return array|string
3800 protected function handleExplicitPluralForms( $count, array $forms ) {
3801 foreach ( $forms as $index => $form ) {
3802 if ( preg_match( '/\d+=/i', $form ) ) {
3803 $pos = strpos( $form, '=' );
3804 if ( substr( $form, 0, $pos ) === (string) $count ) {
3805 return substr( $form, $pos +
1 );
3807 unset( $forms[$index] );
3810 return array_values( $forms );
3814 * Checks that convertPlural was given an array and pads it to requested
3815 * amount of forms by copying the last one.
3817 * @param int $count How many forms should there be at least
3818 * @param array $forms Array of forms given to convertPlural
3819 * @return array Padded array of forms or an exception if not an array
3821 protected function preConvertPlural( /* Array */ $forms, $count ) {
3822 while ( count( $forms ) < $count ) {
3823 $forms[] = $forms[count( $forms ) - 1];
3829 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3830 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3831 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3832 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3835 * @param string $str The validated block duration in English
3836 * @return string Somehow translated block duration
3837 * @see LanguageFi.php for example implementation
3839 function translateBlockExpiry( $str ) {
3840 $duration = SpecialBlock
::getSuggestedDurations( $this );
3841 foreach ( $duration as $show => $value ) {
3842 if ( strcmp( $str, $value ) == 0 ) {
3843 return htmlspecialchars( trim( $show ) );
3847 // Since usually only infinite or indefinite is only on list, so try
3848 // equivalents if still here.
3849 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3850 if ( in_array( $str, $indefs ) ) {
3851 foreach ( $indefs as $val ) {
3852 $show = array_search( $val, $duration, true );
3853 if ( $show !== false ) {
3854 return htmlspecialchars( trim( $show ) );
3859 // If all else fails, return a standard duration or timestamp description.
3860 $time = strtotime( $str, 0 );
3861 if ( $time === false ) { // Unknown format. Return it as-is in case.
3863 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3864 // $time is relative to 0 so it's a duration length.
3865 return $this->formatDuration( $time );
3866 } else { // It's an absolute timestamp.
3867 if ( $time === 0 ) {
3868 // wfTimestamp() handles 0 as current time instead of epoch.
3869 return $this->timeanddate( '19700101000000' );
3871 return $this->timeanddate( $time );
3877 * languages like Chinese need to be segmented in order for the diff
3880 * @param string $text
3883 public function segmentForDiff( $text ) {
3888 * and unsegment to show the result
3890 * @param string $text
3893 public function unsegmentForDiff( $text ) {
3898 * Return the LanguageConverter used in the Language
3901 * @return LanguageConverter
3903 public function getConverter() {
3904 return $this->mConverter
;
3908 * convert text to all supported variants
3910 * @param string $text
3913 public function autoConvertToAllVariants( $text ) {
3914 return $this->mConverter
->autoConvertToAllVariants( $text );
3918 * convert text to different variants of a language.
3920 * @param string $text
3923 public function convert( $text ) {
3924 return $this->mConverter
->convert( $text );
3928 * Convert a Title object to a string in the preferred variant
3930 * @param Title $title
3933 public function convertTitle( $title ) {
3934 return $this->mConverter
->convertTitle( $title );
3938 * Convert a namespace index to a string in the preferred variant
3943 public function convertNamespace( $ns ) {
3944 return $this->mConverter
->convertNamespace( $ns );
3948 * Check if this is a language with variants
3952 public function hasVariants() {
3953 return count( $this->getVariants() ) > 1;
3957 * Check if the language has the specific variant
3960 * @param string $variant
3963 public function hasVariant( $variant ) {
3964 return (bool)$this->mConverter
->validateVariant( $variant );
3968 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3970 * @param string $text
3972 * @deprecated since 1.22 is no longer used
3974 public function armourMath( $text ) {
3975 return $this->mConverter
->armourMath( $text );
3979 * Perform output conversion on a string, and encode for safe HTML output.
3980 * @param string $text Text to be converted
3981 * @param bool $isTitle Whether this conversion is for the article title
3983 * @todo this should get integrated somewhere sane
3985 public function convertHtml( $text, $isTitle = false ) {
3986 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3990 * @param string $key
3993 public function convertCategoryKey( $key ) {
3994 return $this->mConverter
->convertCategoryKey( $key );
3998 * Get the list of variants supported by this language
3999 * see sample implementation in LanguageZh.php
4001 * @return array an array of language codes
4003 public function getVariants() {
4004 return $this->mConverter
->getVariants();
4010 public function getPreferredVariant() {
4011 return $this->mConverter
->getPreferredVariant();
4017 public function getDefaultVariant() {
4018 return $this->mConverter
->getDefaultVariant();
4024 public function getURLVariant() {
4025 return $this->mConverter
->getURLVariant();
4029 * If a language supports multiple variants, it is
4030 * possible that non-existing link in one variant
4031 * actually exists in another variant. this function
4032 * tries to find it. See e.g. LanguageZh.php
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
4038 * @return null the input parameters may be modified upon return
4040 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4041 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4045 * returns language specific options used by User::getPageRenderHash()
4046 * for example, the preferred language variant
4050 function getExtraHashOptions() {
4051 return $this->mConverter
->getExtraHashOptions();
4055 * For languages that support multiple variants, the title of an
4056 * article may be displayed differently in different variants. this
4057 * function returns the apporiate title defined in the body of the article.
4061 public function getParsedTitle() {
4062 return $this->mConverter
->getParsedTitle();
4066 * Prepare external link text for conversion. When the text is
4067 * a URL, it shouldn't be converted, and it'll be wrapped in
4068 * the "raw" tag (-{R| }-) to prevent conversion.
4070 * This function is called "markNoConversion" for historical
4073 * @param string $text Text to be used for external link
4074 * @param bool $noParse Wrap it without confirming it's a real URL first
4075 * @return string The tagged text
4077 public function markNoConversion( $text, $noParse = false ) {
4078 // Excluding protocal-relative URLs may avoid many false positives.
4079 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4080 return $this->mConverter
->markNoConversion( $text );
4087 * A regular expression to match legal word-trailing characters
4088 * which should be merged onto a link of the form [[foo]]bar.
4092 public function linkTrail() {
4093 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4097 * A regular expression character set to match legal word-prefixing
4098 * characters which should be merged onto a link of the form foo[[bar]].
4102 public function linkPrefixCharset() {
4103 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4107 * @deprecated since 1.24, will be removed in 1.25
4110 function getLangObj() {
4111 wfDeprecated( __METHOD__
, '1.24' );
4116 * Get the "parent" language which has a converter to convert a "compatible" language
4117 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4119 * @return Language|null
4122 public function getParentLanguage() {
4123 if ( $this->mParentLanguage
!== false ) {
4124 return $this->mParentLanguage
;
4127 $pieces = explode( '-', $this->getCode() );
4129 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4130 $this->mParentLanguage
= null;
4133 $lang = Language
::factory( $code );
4134 if ( !$lang->hasVariant( $this->getCode() ) ) {
4135 $this->mParentLanguage
= null;
4139 $this->mParentLanguage
= $lang;
4144 * Get the RFC 3066 code for this language object
4146 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4147 * htmlspecialchars() or similar
4151 public function getCode() {
4152 return $this->mCode
;
4156 * Get the code in Bcp47 format which we can use
4157 * inside of html lang="" tags.
4159 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4160 * htmlspecialchars() or similar.
4165 public function getHtmlCode() {
4166 if ( is_null( $this->mHtmlCode
) ) {
4167 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4169 return $this->mHtmlCode
;
4173 * @param string $code
4175 public function setCode( $code ) {
4176 $this->mCode
= $code;
4177 // Ensure we don't leave incorrect cached data lying around
4178 $this->mHtmlCode
= null;
4179 $this->mParentLanguage
= false;
4183 * Get the name of a file for a certain language code
4184 * @param string $prefix Prepend this to the filename
4185 * @param string $code Language code
4186 * @param string $suffix Append this to the filename
4187 * @throws MWException
4188 * @return string $prefix . $mangledCode . $suffix
4190 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4191 if ( !self
::isValidBuiltInCode( $code ) ) {
4192 throw new MWException( "Invalid language code \"$code\"" );
4195 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4199 * Get the language code from a file name. Inverse of getFileName()
4200 * @param string $filename $prefix . $languageCode . $suffix
4201 * @param string $prefix Prefix before the language code
4202 * @param string $suffix Suffix after the language code
4203 * @return string Language code, or false if $prefix or $suffix isn't found
4205 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4207 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4208 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4209 if ( !count( $m ) ) {
4212 return str_replace( '_', '-', strtolower( $m[1] ) );
4216 * @param string $code
4219 public static function getMessagesFileName( $code ) {
4221 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4222 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4227 * @param string $code
4231 public static function getJsonMessagesFileName( $code ) {
4234 if ( !self
::isValidBuiltInCode( $code ) ) {
4235 throw new MWException( "Invalid language code \"$code\"" );
4238 return "$IP/languages/i18n/$code.json";
4242 * @param string $code
4245 public static function getClassFileName( $code ) {
4247 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4251 * Get the first fallback for a given language.
4253 * @param string $code
4255 * @return bool|string
4257 public static function getFallbackFor( $code ) {
4258 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4261 $fallbacks = self
::getFallbacksFor( $code );
4262 $first = array_shift( $fallbacks );
4268 * Get the ordered list of fallback languages.
4271 * @param string $code Language code
4274 public static function getFallbacksFor( $code ) {
4275 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4278 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4279 $v = array_map( 'trim', explode( ',', $v ) );
4280 if ( $v[count( $v ) - 1] !== 'en' ) {
4288 * Get the ordered list of fallback languages, ending with the fallback
4289 * language chain for the site language.
4292 * @param string $code Language code
4293 * @return array array( fallbacks, site fallbacks )
4295 public static function getFallbacksIncludingSiteLanguage( $code ) {
4296 global $wgLanguageCode;
4298 // Usually, we will only store a tiny number of fallback chains, so we
4299 // keep them in static memory.
4300 $cacheKey = "{$code}-{$wgLanguageCode}";
4302 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4303 $fallbacks = self
::getFallbacksFor( $code );
4305 // Append the site's fallback chain, including the site language itself
4306 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4307 array_unshift( $siteFallbacks, $wgLanguageCode );
4309 // Eliminate any languages already included in the chain
4310 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4312 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4314 return self
::$fallbackLanguageCache[$cacheKey];
4318 * Get all messages for a given language
4319 * WARNING: this may take a long time. If you just need all message *keys*
4320 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4322 * @param string $code
4326 public static function getMessagesFor( $code ) {
4327 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4331 * Get a message for a given language
4333 * @param string $key
4334 * @param string $code
4338 public static function getMessageFor( $key, $code ) {
4339 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4343 * Get all message keys for a given language. This is a faster alternative to
4344 * array_keys( Language::getMessagesFor( $code ) )
4347 * @param string $code Language code
4348 * @return array of message keys (strings)
4350 public static function getMessageKeysFor( $code ) {
4351 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4355 * @param string $talk
4358 function fixVariableInNamespace( $talk ) {
4359 if ( strpos( $talk, '$1' ) === false ) {
4363 global $wgMetaNamespace;
4364 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4366 # Allow grammar transformations
4367 # Allowing full message-style parsing would make simple requests
4368 # such as action=raw much more expensive than they need to be.
4369 # This will hopefully cover most cases.
4370 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4371 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4372 return str_replace( ' ', '_', $talk );
4379 function replaceGrammarInNamespace( $m ) {
4380 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4384 * @throws MWException
4387 static function getCaseMaps() {
4388 static $wikiUpperChars, $wikiLowerChars;
4389 if ( isset( $wikiUpperChars ) ) {
4390 return array( $wikiUpperChars, $wikiLowerChars );
4393 wfProfileIn( __METHOD__
);
4394 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4395 if ( $arr === false ) {
4396 throw new MWException(
4397 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4399 $wikiUpperChars = $arr['wikiUpperChars'];
4400 $wikiLowerChars = $arr['wikiLowerChars'];
4401 wfProfileOut( __METHOD__
);
4402 return array( $wikiUpperChars, $wikiLowerChars );
4406 * Decode an expiry (block, protection, etc) which has come from the DB
4408 * @todo FIXME: why are we returnings DBMS-dependent strings???
4410 * @param string $expiry Database expiry String
4411 * @param bool|int $format True to process using language functions, or TS_ constant
4412 * to return the expiry in a given timestamp
4416 public function formatExpiry( $expiry, $format = true ) {
4418 if ( $infinity === null ) {
4419 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4422 if ( $expiry == '' ||
$expiry == $infinity ) {
4423 return $format === true
4424 ?
$this->getMessageFromDB( 'infiniteblock' )
4427 return $format === true
4428 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4429 : wfTimestamp( $format, $expiry );
4435 * @param int|float $seconds
4436 * @param array $format Optional
4437 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4438 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4439 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4441 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4442 * or 'avoidminutes'.
4445 function formatTimePeriod( $seconds, $format = array() ) {
4446 if ( !is_array( $format ) ) {
4447 $format = array( 'avoid' => $format ); // For backwards compatibility
4449 if ( !isset( $format['avoid'] ) ) {
4450 $format['avoid'] = false;
4452 if ( !isset( $format['noabbrevs' ] ) ) {
4453 $format['noabbrevs'] = false;
4455 $secondsMsg = wfMessage(
4456 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4457 $minutesMsg = wfMessage(
4458 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4459 $hoursMsg = wfMessage(
4460 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4461 $daysMsg = wfMessage(
4462 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4464 if ( round( $seconds * 10 ) < 100 ) {
4465 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4466 $s = $secondsMsg->params( $s )->text();
4467 } elseif ( round( $seconds ) < 60 ) {
4468 $s = $this->formatNum( round( $seconds ) );
4469 $s = $secondsMsg->params( $s )->text();
4470 } elseif ( round( $seconds ) < 3600 ) {
4471 $minutes = floor( $seconds / 60 );
4472 $secondsPart = round( fmod( $seconds, 60 ) );
4473 if ( $secondsPart == 60 ) {
4477 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4479 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4480 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4481 $hours = floor( $seconds / 3600 );
4482 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4483 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4484 if ( $secondsPart == 60 ) {
4488 if ( $minutes == 60 ) {
4492 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4494 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4495 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4496 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4499 $days = floor( $seconds / 86400 );
4500 if ( $format['avoid'] === 'avoidminutes' ) {
4501 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4502 if ( $hours == 24 ) {
4506 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4508 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4509 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4510 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4511 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4512 if ( $minutes == 60 ) {
4516 if ( $hours == 24 ) {
4520 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4522 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4524 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4526 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4528 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4535 * Format a bitrate for output, using an appropriate
4536 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4537 * the magnitude in question.
4539 * This use base 1000. For base 1024 use formatSize(), for another base
4540 * see formatComputingNumbers().
4545 function formatBitrate( $bps ) {
4546 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4550 * @param int $size Size of the unit
4551 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4552 * @param string $messageKey Message key to be uesd
4555 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4557 return str_replace( '$1', $this->formatNum( $size ),
4558 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4561 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4564 $maxIndex = count( $sizes ) - 1;
4565 while ( $size >= $boundary && $index < $maxIndex ) {
4570 // For small sizes no decimal places necessary
4573 // For MB and bigger two decimal places are smarter
4576 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4578 $size = round( $size, $round );
4579 $text = $this->getMessageFromDB( $msg );
4580 return str_replace( '$1', $this->formatNum( $size ), $text );
4584 * Format a size in bytes for output, using an appropriate
4585 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4587 * This method use base 1024. For base 1000 use formatBitrate(), for
4588 * another base see formatComputingNumbers()
4590 * @param int $size Size to format
4591 * @return string Plain text (not HTML)
4593 function formatSize( $size ) {
4594 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4598 * Make a list item, used by various special pages
4600 * @param string $page Page link
4601 * @param string $details Text between brackets
4602 * @param bool $oppositedm Add the direction mark opposite to your
4603 * language, to display text properly
4606 function specialList( $page, $details, $oppositedm = true ) {
4607 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4608 $this->getDirMark();
4609 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4610 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4611 return $page . $details;
4615 * Generate (prev x| next x) (20|50|100...) type links for paging
4617 * @param Title $title Title object to link
4618 * @param int $offset
4620 * @param array|string $query Optional URL query parameter string
4621 * @param bool $atend Optional param for specified if this is the last page
4624 public function viewPrevNext( Title
$title, $offset, $limit,
4625 array $query = array(), $atend = false
4627 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4629 # Make 'previous' link
4630 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4631 if ( $offset > 0 ) {
4632 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4633 $query, $prev, 'prevn-title', 'mw-prevlink' );
4635 $plink = htmlspecialchars( $prev );
4639 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4641 $nlink = htmlspecialchars( $next );
4643 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4644 $query, $next, 'nextn-title', 'mw-nextlink' );
4647 # Make links to set number of items per page
4648 $numLinks = array();
4649 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4650 $numLinks[] = $this->numLink( $title, $offset, $num,
4651 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4654 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4655 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4659 * Helper function for viewPrevNext() that generates links
4661 * @param Title $title Title object to link
4662 * @param int $offset
4664 * @param array $query Extra query parameters
4665 * @param string $link Text to use for the link; will be escaped
4666 * @param string $tooltipMsg Name of the message to use as tooltip
4667 * @param string $class Value of the "class" attribute of the link
4668 * @return string HTML fragment
4670 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4673 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4674 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4675 ->numParams( $limit )->text();
4677 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4678 'title' => $tooltip, 'class' => $class ), $link );
4682 * Get the conversion rule title, if any.
4686 public function getConvRuleTitle() {
4687 return $this->mConverter
->getConvRuleTitle();
4691 * Get the compiled plural rules for the language
4693 * @return array Associative array with plural form, and plural rule as key-value pairs
4695 public function getCompiledPluralRules() {
4696 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4697 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4698 if ( !$pluralRules ) {
4699 foreach ( $fallbacks as $fallbackCode ) {
4700 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4701 if ( $pluralRules ) {
4706 return $pluralRules;
4710 * Get the plural rules for the language
4712 * @return array Associative array with plural form number and plural rule as key-value pairs
4714 public function getPluralRules() {
4715 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4716 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4717 if ( !$pluralRules ) {
4718 foreach ( $fallbacks as $fallbackCode ) {
4719 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4720 if ( $pluralRules ) {
4725 return $pluralRules;
4729 * Get the plural rule types for the language
4731 * @return array Associative array with plural form number and plural rule type as key-value pairs
4733 public function getPluralRuleTypes() {
4734 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4735 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4736 if ( !$pluralRuleTypes ) {
4737 foreach ( $fallbacks as $fallbackCode ) {
4738 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4739 if ( $pluralRuleTypes ) {
4744 return $pluralRuleTypes;
4748 * Find the index number of the plural rule appropriate for the given 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 * @return string The name of the plural rule type, e.g. one, two, few, many
4764 public function getPluralRuleType( $number ) {
4765 $index = $this->getPluralRuleIndexNumber( $number );
4766 $pluralRuleTypes = $this->getPluralRuleTypes();
4767 if ( isset( $pluralRuleTypes[$index] ) ) {
4768 return $pluralRuleTypes[$index];