3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
38 * Internationalisation code
43 * @var LanguageConverter
47 public $mVariants, $mCode, $mLoaded = false;
48 public $mMagicExtensions = array(), $mMagicHookDone = false;
49 private $mHtmlCode = null, $mParentLanguage = false;
51 public $dateFormatStrings = array();
52 public $mExtendedSpecialPageAliases;
54 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
57 * ReplacementArray object caches
59 public $transformData = array();
62 * @var LocalisationCache
64 static public $dataCache;
66 static public $mLangObjCache = array();
68 static public $mWeekdayMsgs = array(
69 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
73 static public $mWeekdayAbbrevMsgs = array(
74 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
77 static public $mMonthMsgs = array(
78 'january', 'february', 'march', 'april', 'may_long', 'june',
79 'july', 'august', 'september', 'october', 'november',
82 static public $mMonthGenMsgs = array(
83 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
84 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
87 static public $mMonthAbbrevMsgs = array(
88 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
89 'sep', 'oct', 'nov', 'dec'
92 static public $mIranianCalendarMonthMsgs = array(
93 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
94 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
95 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
96 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
99 static public $mHebrewCalendarMonthMsgs = array(
100 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
101 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
102 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
103 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
104 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
107 static public $mHebrewCalendarMonthGenMsgs = array(
108 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
109 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
110 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
111 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
112 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
115 static public $mHijriCalendarMonthMsgs = array(
116 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
117 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
118 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
119 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
126 static public $durationIntervals = array(
127 'millennia' => 31556952000,
128 'centuries' => 3155695200,
129 'decades' => 315569520,
130 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
139 * Cache for language fallbacks.
140 * @see Language::getFallbacksIncludingSiteLanguage
144 static private $fallbackLanguageCache = array();
147 * Cache for language names
148 * @var MapCacheLRU|null
150 static private $languageNameCache;
153 * Get a cached or new language object for a given language code
154 * @param string $code
157 static function factory( $code ) {
158 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
160 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
161 $code = $wgDummyLanguageCodes[$code];
164 // get the language object to process
165 $langObj = isset( self
::$mLangObjCache[$code] )
166 ? self
::$mLangObjCache[$code]
167 : self
::newFromCode( $code );
169 // merge the language object in to get it up front in the cache
170 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
171 // get rid of the oldest ones in case we have an overflow
172 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
178 * Create a language object for a given language code
179 * @param string $code
180 * @throws MWException
183 protected static function newFromCode( $code ) {
184 // Protect against path traversal below
185 if ( !Language
::isValidCode( $code )
186 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code )
188 throw new MWException( "Invalid language code \"$code\"" );
191 if ( !Language
::isValidBuiltInCode( $code ) ) {
192 // It's not possible to customise this code with class files, so
193 // just return a Language object. This is to support uselang= hacks.
194 $lang = new Language
;
195 $lang->setCode( $code );
199 // Check if there is a language class for the code
200 $class = self
::classFromCode( $code );
201 self
::preloadLanguageClass( $class );
202 if ( class_exists( $class ) ) {
207 // Keep trying the fallback list until we find an existing class
208 $fallbacks = Language
::getFallbacksFor( $code );
209 foreach ( $fallbacks as $fallbackCode ) {
210 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
211 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
214 $class = self
::classFromCode( $fallbackCode );
215 self
::preloadLanguageClass( $class );
216 if ( class_exists( $class ) ) {
217 $lang = Language
::newFromCode( $fallbackCode );
218 $lang->setCode( $code );
223 throw new MWException( "Invalid fallback sequence for language '$code'" );
227 * Checks whether any localisation is available for that language tag
228 * in MediaWiki (MessagesXx.php exists).
230 * @param string $code Language tag (in lower case)
231 * @return bool Whether language is supported
234 public static function isSupportedLanguage( $code ) {
235 return self
::isValidBuiltInCode( $code )
236 && ( is_readable( self
::getMessagesFileName( $code ) )
237 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
242 * Returns true if a language code string is a well-formed language tag
243 * according to RFC 5646.
244 * This function only checks well-formedness; it doesn't check that
245 * language, script or variant codes actually exist in the repositories.
247 * Based on regexes by Mark Davis of the Unicode Consortium:
248 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
250 * @param string $code
251 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
256 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
259 $alphanum = '[a-z0-9]';
260 $x = 'x'; # private use singleton
261 $singleton = '[a-wy-z]'; # other singleton
262 $s = $lenient ?
'[-_]' : '-';
264 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
265 $script = "$alpha{4}"; # ISO 15924
266 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
267 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
268 $extension = "$singleton(?:$s$alphanum{2,8})+";
269 $privateUse = "$x(?:$s$alphanum{1,8})+";
271 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
272 # Since these are limited, this is safe even later changes to the registry --
273 # the only oddity is that it might change the type of the tag, and thus
274 # the results from the capturing groups.
275 # http://www.iana.org/assignments/language-subtag-registry
277 $grandfathered = "en{$s}GB{$s}oed"
278 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
279 . "|no{$s}(?:bok|nyn)"
280 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
281 . "|zh{$s}min{$s}nan";
283 $variantList = "$variant(?:$s$variant)*";
284 $extensionList = "$extension(?:$s$extension)*";
286 $langtag = "(?:($language)"
289 . "(?:$s$variantList)?"
290 . "(?:$s$extensionList)?"
291 . "(?:$s$privateUse)?)";
293 # The final breakdown, with capturing groups for each of these components
294 # The variants, extensions, grandfathered, and private-use may have interior '-'
296 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
298 return (bool)preg_match( "/$root/", strtolower( $code ) );
302 * Returns true if a language code string is of a valid form, whether or
303 * not it exists. This includes codes which are used solely for
304 * customisation via the MediaWiki namespace.
306 * @param string $code
310 public static function isValidCode( $code ) {
311 static $cache = array();
312 if ( isset( $cache[$code] ) ) {
313 return $cache[$code];
315 // People think language codes are html safe, so enforce it.
316 // Ideally we should only allow a-zA-Z0-9-
317 // but, .+ and other chars are often used for {{int:}} hacks
318 // see bugs 37564, 37587, 36938
320 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
321 && !preg_match( Title
::getTitleInvalidRegex(), $code );
323 return $cache[$code];
327 * Returns true if a language code is of a valid form for the purposes of
328 * internal customisation of MediaWiki, via Messages*.php or *.json.
330 * @param string $code
332 * @throws MWException
336 public static function isValidBuiltInCode( $code ) {
338 if ( !is_string( $code ) ) {
339 if ( is_object( $code ) ) {
340 $addmsg = " of class " . get_class( $code );
344 $type = gettype( $code );
345 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
348 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
352 * Returns true if a language code is an IETF tag known to MediaWiki.
359 public static function isKnownLanguageTag( $tag ) {
360 static $coreLanguageNames;
362 // Quick escape for invalid input to avoid exceptions down the line
363 // when code tries to process tags which are not valid at all.
364 if ( !self
::isValidBuiltInCode( $tag ) ) {
368 if ( $coreLanguageNames === null ) {
370 include "$IP/languages/Names.php";
373 if ( isset( $coreLanguageNames[$tag] )
374 || self
::fetchLanguageName( $tag, $tag ) !== ''
383 * @param string $code
384 * @return string Name of the language class
386 public static function classFromCode( $code ) {
387 if ( $code == 'en' ) {
390 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
395 * Includes language class files
397 * @param string $class Name of the language class
399 public static function preloadLanguageClass( $class ) {
402 if ( $class === 'Language' ) {
406 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
407 include_once "$IP/languages/classes/$class.php";
412 * Get the LocalisationCache instance
414 * @return LocalisationCache
416 public static function getLocalisationCache() {
417 if ( is_null( self
::$dataCache ) ) {
418 global $wgLocalisationCacheConf;
419 $class = $wgLocalisationCacheConf['class'];
420 self
::$dataCache = new $class( $wgLocalisationCacheConf );
422 return self
::$dataCache;
425 function __construct() {
426 $this->mConverter
= new FakeConverter( $this );
427 // Set the code to the name of the descendant
428 if ( get_class( $this ) == 'Language' ) {
431 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
433 self
::getLocalisationCache();
437 * Reduce memory usage
439 function __destruct() {
440 foreach ( $this as $name => $value ) {
441 unset( $this->$name );
446 * Hook which will be called if this is the content language.
447 * Descendants can use this to register hook functions or modify globals
449 function initContLang() {
456 function getFallbackLanguages() {
457 return self
::getFallbacksFor( $this->mCode
);
461 * Exports $wgBookstoreListEn
464 function getBookstoreList() {
465 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
469 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
470 * available in localised form, it will be included in English.
474 public function getNamespaces() {
475 if ( is_null( $this->namespaceNames
) ) {
476 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
478 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
479 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
481 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
483 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
484 if ( $wgMetaNamespaceTalk ) {
485 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
487 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
488 $this->namespaceNames
[NS_PROJECT_TALK
] =
489 $this->fixVariableInNamespace( $talk );
492 # Sometimes a language will be localised but not actually exist on this wiki.
493 foreach ( $this->namespaceNames
as $key => $text ) {
494 if ( !isset( $validNamespaces[$key] ) ) {
495 unset( $this->namespaceNames
[$key] );
499 # The above mixing may leave namespaces out of canonical order.
500 # Re-order by namespace ID number...
501 ksort( $this->namespaceNames
);
503 Hooks
::run( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
506 return $this->namespaceNames
;
510 * Arbitrarily set all of the namespace names at once. Mainly used for testing
511 * @param array $namespaces Array of namespaces (id => name)
513 public function setNamespaces( array $namespaces ) {
514 $this->namespaceNames
= $namespaces;
515 $this->mNamespaceIds
= null;
519 * Resets all of the namespace caches. Mainly used for testing
521 public function resetNamespaces() {
522 $this->namespaceNames
= null;
523 $this->mNamespaceIds
= null;
524 $this->namespaceAliases
= null;
528 * A convenience function that returns the same thing as
529 * getNamespaces() except with the array values changed to ' '
530 * where it found '_', useful for producing output to be displayed
531 * e.g. in <select> forms.
535 function getFormattedNamespaces() {
536 $ns = $this->getNamespaces();
537 foreach ( $ns as $k => $v ) {
538 $ns[$k] = strtr( $v, '_', ' ' );
544 * Get a namespace value by key
546 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
547 * echo $mw_ns; // prints 'MediaWiki'
550 * @param int $index The array key of the namespace to return
551 * @return string|bool String if the namespace value exists, otherwise false
553 function getNsText( $index ) {
554 $ns = $this->getNamespaces();
556 return isset( $ns[$index] ) ?
$ns[$index] : false;
560 * A convenience function that returns the same thing as
561 * getNsText() except with '_' changed to ' ', useful for
565 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
566 * echo $mw_ns; // prints 'MediaWiki talk'
569 * @param int $index The array key of the namespace to return
570 * @return string Namespace name without underscores (empty string if namespace does not exist)
572 function getFormattedNsText( $index ) {
573 $ns = $this->getNsText( $index );
575 return strtr( $ns, '_', ' ' );
579 * Returns gender-dependent namespace alias if available.
580 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
581 * @param int $index Namespace index
582 * @param string $gender Gender key (male, female... )
586 function getGenderNsText( $index, $gender ) {
587 global $wgExtraGenderNamespaces;
589 $ns = $wgExtraGenderNamespaces +
590 self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
592 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
596 * Whether this language uses gender-dependent namespace aliases.
597 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
601 function needsGenderDistinction() {
602 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
603 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
604 // $wgExtraGenderNamespaces overrides everything
606 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
607 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
608 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
611 // Check what is in i18n files
612 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
613 return count( $aliases ) > 0;
618 * Get a namespace key by value, case insensitive.
619 * Only matches namespace names for the current language, not the
620 * canonical ones defined in Namespace.php.
622 * @param string $text
623 * @return int|bool An integer if $text is a valid value otherwise false
625 function getLocalNsIndex( $text ) {
626 $lctext = $this->lc( $text );
627 $ids = $this->getNamespaceIds();
628 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
634 function getNamespaceAliases() {
635 if ( is_null( $this->namespaceAliases
) ) {
636 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
640 foreach ( $aliases as $name => $index ) {
641 if ( $index === NS_PROJECT_TALK
) {
642 unset( $aliases[$name] );
643 $name = $this->fixVariableInNamespace( $name );
644 $aliases[$name] = $index;
649 global $wgExtraGenderNamespaces;
650 $genders = $wgExtraGenderNamespaces +
651 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
652 foreach ( $genders as $index => $forms ) {
653 foreach ( $forms as $alias ) {
654 $aliases[$alias] = $index;
658 # Also add converted namespace names as aliases, to avoid confusion.
659 $convertedNames = array();
660 foreach ( $this->getVariants() as $variant ) {
661 if ( $variant === $this->mCode
) {
664 foreach ( $this->getNamespaces() as $ns => $_ ) {
665 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
669 $this->namespaceAliases
= $aliases +
$convertedNames;
672 return $this->namespaceAliases
;
678 function getNamespaceIds() {
679 if ( is_null( $this->mNamespaceIds
) ) {
680 global $wgNamespaceAliases;
681 # Put namespace names and aliases into a hashtable.
682 # If this is too slow, then we should arrange it so that it is done
683 # before caching. The catch is that at pre-cache time, the above
684 # class-specific fixup hasn't been done.
685 $this->mNamespaceIds
= array();
686 foreach ( $this->getNamespaces() as $index => $name ) {
687 $this->mNamespaceIds
[$this->lc( $name )] = $index;
689 foreach ( $this->getNamespaceAliases() as $name => $index ) {
690 $this->mNamespaceIds
[$this->lc( $name )] = $index;
692 if ( $wgNamespaceAliases ) {
693 foreach ( $wgNamespaceAliases as $name => $index ) {
694 $this->mNamespaceIds
[$this->lc( $name )] = $index;
698 return $this->mNamespaceIds
;
702 * Get a namespace key by value, case insensitive. Canonical namespace
703 * names override custom ones defined for the current language.
705 * @param string $text
706 * @return int|bool An integer if $text is a valid value otherwise false
708 function getNsIndex( $text ) {
709 $lctext = $this->lc( $text );
710 $ns = MWNamespace
::getCanonicalIndex( $lctext );
711 if ( $ns !== null ) {
714 $ids = $this->getNamespaceIds();
715 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
719 * short names for language variants used for language conversion links.
721 * @param string $code
722 * @param bool $usemsg Use the "variantname-xyz" message if it exists
725 function getVariantname( $code, $usemsg = true ) {
726 $msg = "variantname-$code";
727 if ( $usemsg && wfMessage( $msg )->exists() ) {
728 return $this->getMessageFromDB( $msg );
730 $name = self
::fetchLanguageName( $code );
732 return $name; # if it's defined as a language name, show that
734 # otherwise, output the language code
740 * @deprecated since 1.24, doesn't handle conflicting aliases. Use
741 * SpecialPageFactory::getLocalNameFor instead.
742 * @param string $name
745 function specialPage( $name ) {
746 $aliases = $this->getSpecialPageAliases();
747 if ( isset( $aliases[$name][0] ) ) {
748 $name = $aliases[$name][0];
750 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
756 function getDatePreferences() {
757 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
763 function getDateFormats() {
764 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
768 * @return array|string
770 function getDefaultDateFormat() {
771 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
772 if ( $df === 'dmy or mdy' ) {
773 global $wgAmericanDates;
774 return $wgAmericanDates ?
'mdy' : 'dmy';
783 function getDatePreferenceMigrationMap() {
784 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
788 * @param string $image
791 function getImageFile( $image ) {
792 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
799 function getImageFiles() {
800 return self
::$dataCache->getItem( $this->mCode
, 'imageFiles' );
806 function getExtraUserToggles() {
807 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
814 function getUserToggle( $tog ) {
815 return $this->getMessageFromDB( "tog-$tog" );
819 * Get native language names, indexed by code.
820 * Only those defined in MediaWiki, no other data like CLDR.
821 * If $customisedOnly is true, only returns codes with a messages file
823 * @param bool $customisedOnly
826 * @deprecated since 1.20, use fetchLanguageNames()
828 public static function getLanguageNames( $customisedOnly = false ) {
829 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
833 * Get translated language names. This is done on best effort and
834 * by default this is exactly the same as Language::getLanguageNames.
835 * The CLDR extension provides translated names.
836 * @param string $code Language code.
837 * @return array Language code => language name
839 * @deprecated since 1.20, use fetchLanguageNames()
841 public static function getTranslatedLanguageNames( $code ) {
842 return self
::fetchLanguageNames( $code, 'all' );
846 * Get an array of language names, indexed by code.
847 * @param null|string $inLanguage Code of language in which to return the names
848 * Use null for autonyms (native names)
849 * @param string $include One of:
850 * 'all' all available languages
851 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
852 * 'mwfile' only if the language is in 'mw' *and* has a message file
853 * @return array Language code => language name
856 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
857 wfProfileIn( __METHOD__
);
858 $cacheKey = $inLanguage === null ?
'null' : $inLanguage;
859 $cacheKey .= ":$include";
860 if ( self
::$languageNameCache === null ) {
861 self
::$languageNameCache = new MapCacheLRU( 20 );
863 if ( self
::$languageNameCache->has( $cacheKey ) ) {
864 $ret = self
::$languageNameCache->get( $cacheKey );
866 $ret = self
::fetchLanguageNamesUncached( $inLanguage, $include );
867 self
::$languageNameCache->set( $cacheKey, $ret );
869 wfProfileOut( __METHOD__
);
874 * Uncached helper for fetchLanguageNames
875 * @param null|string $inLanguage Code of language in which to return the names
876 * Use null for autonyms (native names)
877 * @param string $include One of:
878 * 'all' all available languages
879 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
880 * 'mwfile' only if the language is in 'mw' *and* has a message file
881 * @return array Language code => language name
883 private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
884 global $wgExtraLanguageNames;
885 static $coreLanguageNames;
887 if ( $coreLanguageNames === null ) {
889 include "$IP/languages/Names.php";
892 // If passed an invalid language code to use, fallback to en
893 if ( $inLanguage !== null && !Language
::isValidCode( $inLanguage ) ) {
900 # TODO: also include when $inLanguage is null, when this code is more efficient
901 Hooks
::run( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
904 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
905 foreach ( $mwNames as $mwCode => $mwName ) {
906 # - Prefer own MediaWiki native name when not using the hook
907 # - For other names just add if not added through the hook
908 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
909 $names[$mwCode] = $mwName;
913 if ( $include === 'all' ) {
919 $coreCodes = array_keys( $mwNames );
920 foreach ( $coreCodes as $coreCode ) {
921 $returnMw[$coreCode] = $names[$coreCode];
924 if ( $include === 'mwfile' ) {
925 $namesMwFile = array();
926 # We do this using a foreach over the codes instead of a directory
927 # loop so that messages files in extensions will work correctly.
928 foreach ( $returnMw as $code => $value ) {
929 if ( is_readable( self
::getMessagesFileName( $code ) )
930 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
932 $namesMwFile[$code] = $names[$code];
936 ksort( $namesMwFile );
941 # 'mw' option; default if it's not one of the other two options (all/mwfile)
946 * @param string $code The code of the language for which to get the name
947 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
948 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
949 * @return string Language name or empty
952 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
953 $code = strtolower( $code );
954 $array = self
::fetchLanguageNames( $inLanguage, $include );
955 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
959 * Get a message from the MediaWiki namespace.
961 * @param string $msg Message name
964 function getMessageFromDB( $msg ) {
965 return wfMessage( $msg )->inLanguage( $this )->text();
969 * Get the native language name of $code.
970 * Only if defined in MediaWiki, no other data like CLDR.
971 * @param string $code
973 * @deprecated since 1.20, use fetchLanguageName()
975 function getLanguageName( $code ) {
976 return self
::fetchLanguageName( $code );
983 function getMonthName( $key ) {
984 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
990 function getMonthNamesArray() {
991 $monthNames = array( '' );
992 for ( $i = 1; $i < 13; $i++
) {
993 $monthNames[] = $this->getMonthName( $i );
1002 function getMonthNameGen( $key ) {
1003 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
1007 * @param string $key
1010 function getMonthAbbreviation( $key ) {
1011 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
1017 function getMonthAbbreviationsArray() {
1018 $monthNames = array( '' );
1019 for ( $i = 1; $i < 13; $i++
) {
1020 $monthNames[] = $this->getMonthAbbreviation( $i );
1026 * @param string $key
1029 function getWeekdayName( $key ) {
1030 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1034 * @param string $key
1037 function getWeekdayAbbreviation( $key ) {
1038 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1042 * @param string $key
1045 function getIranianCalendarMonthName( $key ) {
1046 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1050 * @param string $key
1053 function getHebrewCalendarMonthName( $key ) {
1054 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1058 * @param string $key
1061 function getHebrewCalendarMonthNameGen( $key ) {
1062 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1066 * @param string $key
1069 function getHijriCalendarMonthName( $key ) {
1070 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1074 * Pass through result from $dateTimeObj->format()
1075 * @param DateTime|bool|null &$dateTimeObj
1077 * @param DateTimeZone|bool|null $zone
1078 * @param string $code
1081 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1082 if ( !$dateTimeObj ) {
1083 $dateTimeObj = DateTime
::createFromFormat(
1084 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1087 return $dateTimeObj->format( $code );
1091 * This is a workalike of PHP's date() function, but with better
1092 * internationalisation, a reduced set of format characters, and a better
1095 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1096 * the PHP manual for definitions. There are a number of extensions, which
1099 * xn Do not translate digits of the next numeric format character
1100 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1101 * xr Use roman numerals for the next numeric format character
1102 * xh Use hebrew numerals for the next numeric format character
1104 * xg Genitive month name
1106 * xij j (day number) in Iranian calendar
1107 * xiF F (month name) in Iranian calendar
1108 * xin n (month number) in Iranian calendar
1109 * xiy y (two digit year) in Iranian calendar
1110 * xiY Y (full year) in Iranian calendar
1112 * xjj j (day number) in Hebrew calendar
1113 * xjF F (month name) in Hebrew calendar
1114 * xjt t (days in month) in Hebrew calendar
1115 * xjx xg (genitive month name) in Hebrew calendar
1116 * xjn n (month number) in Hebrew calendar
1117 * xjY Y (full year) in Hebrew calendar
1119 * xmj j (day number) in Hijri calendar
1120 * xmF F (month name) in Hijri calendar
1121 * xmn n (month number) in Hijri calendar
1122 * xmY Y (full year) in Hijri calendar
1124 * xkY Y (full year) in Thai solar calendar. Months and days are
1125 * identical to the Gregorian calendar
1126 * xoY Y (full year) in Minguo calendar or Juche year.
1127 * Months and days are identical to the
1128 * Gregorian calendar
1129 * xtY Y (full year) in Japanese nengo. Months and days are
1130 * identical to the Gregorian calendar
1132 * Characters enclosed in double quotes will be considered literal (with
1133 * the quotes themselves removed). Unmatched quotes will be considered
1134 * literal quotes. Example:
1136 * "The month is" F => The month is January
1139 * Backslash escaping is also supported.
1141 * Input timestamp is assumed to be pre-normalized to the desired local
1142 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1143 * $ts is UTC if $zone is not given.
1145 * @param string $format
1146 * @param string $ts 14-character timestamp
1149 * @param DateTimeZone $zone Timezone of $ts
1150 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1151 * Only makes sense if $ts is the current time.
1152 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1154 * @throws MWException
1157 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1162 $dateTimeObj = false;
1171 $usedSecond = false;
1172 $usedMinute = false;
1179 $usedISOYear = false;
1180 $usedIsLeapYear = false;
1182 $usedHebrewMonth = false;
1183 $usedIranianMonth = false;
1184 $usedHijriMonth = false;
1185 $usedHebrewYear = false;
1186 $usedIranianYear = false;
1187 $usedHijriYear = false;
1188 $usedTennoYear = false;
1190 if ( strlen( $ts ) !== 14 ) {
1191 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1194 if ( !ctype_digit( $ts ) ) {
1195 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1198 $formatLength = strlen( $format );
1199 for ( $p = 0; $p < $formatLength; $p++
) {
1201 $code = $format[$p];
1202 if ( $code == 'x' && $p < $formatLength - 1 ) {
1203 $code .= $format[++
$p];
1206 if ( ( $code === 'xi'
1212 && $p < $formatLength - 1 ) {
1213 $code .= $format[++
$p];
1224 $rawToggle = !$rawToggle;
1234 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1237 $usedHebrewMonth = true;
1239 $hebrew = self
::tsToHebrew( $ts );
1241 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1245 $num = substr( $ts, 6, 2 );
1249 $s .= $this->getWeekdayAbbreviation( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1253 $num = intval( substr( $ts, 6, 2 ) );
1258 $iranian = self
::tsToIranian( $ts );
1265 $hijri = self
::tsToHijri( $ts );
1272 $hebrew = self
::tsToHebrew( $ts );
1278 $s .= $this->getWeekdayName( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1282 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1285 $usedIranianMonth = true;
1287 $iranian = self
::tsToIranian( $ts );
1289 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1292 $usedHijriMonth = true;
1294 $hijri = self
::tsToHijri( $ts );
1296 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1299 $usedHebrewMonth = true;
1301 $hebrew = self
::tsToHebrew( $ts );
1303 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1307 $num = substr( $ts, 4, 2 );
1311 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1315 $num = intval( substr( $ts, 4, 2 ) );
1318 $usedIranianMonth = true;
1320 $iranian = self
::tsToIranian( $ts );
1325 $usedHijriMonth = true;
1327 $hijri = self
::tsToHijri ( $ts );
1332 $usedHebrewMonth = true;
1334 $hebrew = self
::tsToHebrew( $ts );
1339 $usedHebrewMonth = true;
1341 $hebrew = self
::tsToHebrew( $ts );
1347 $num = substr( $ts, 0, 4 );
1350 $usedIranianYear = true;
1352 $iranian = self
::tsToIranian( $ts );
1357 $usedHijriYear = true;
1359 $hijri = self
::tsToHijri( $ts );
1364 $usedHebrewYear = true;
1366 $hebrew = self
::tsToHebrew( $ts );
1373 $thai = self
::tsToYear( $ts, 'thai' );
1380 $minguo = self
::tsToYear( $ts, 'minguo' );
1385 $usedTennoYear = true;
1387 $tenno = self
::tsToYear( $ts, 'tenno' );
1393 $num = substr( $ts, 2, 2 );
1396 $usedIranianYear = true;
1398 $iranian = self
::tsToIranian( $ts );
1400 $num = substr( $iranian[0], -2 );
1404 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1408 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1412 $h = substr( $ts, 8, 2 );
1413 $num = $h %
12 ?
$h %
12 : 12;
1417 $num = intval( substr( $ts, 8, 2 ) );
1421 $h = substr( $ts, 8, 2 );
1422 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1426 $num = substr( $ts, 8, 2 );
1430 $num = substr( $ts, 10, 2 );
1434 $num = substr( $ts, 12, 2 );
1444 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1450 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1454 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1458 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1461 $usedIsLeapYear = true;
1462 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1465 $usedISOYear = true;
1466 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1473 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1476 # Backslash escaping
1477 if ( $p < $formatLength - 1 ) {
1478 $s .= $format[++
$p];
1485 if ( $p < $formatLength - 1 ) {
1486 $endQuote = strpos( $format, '"', $p +
1 );
1487 if ( $endQuote === false ) {
1488 # No terminating quote, assume literal "
1491 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1495 # Quote at end of string, assume literal "
1502 if ( $num !== false ) {
1503 if ( $rawToggle ||
$raw ) {
1506 } elseif ( $roman ) {
1507 $s .= Language
::romanNumeral( $num );
1509 } elseif ( $hebrewNum ) {
1510 $s .= self
::hebrewNumeral( $num );
1513 $s .= $this->formatNum( $num, true );
1518 if ( $usedSecond ) {
1520 } elseif ( $usedMinute ) {
1521 $ttl = 60 - substr( $ts, 12, 2 );
1522 } elseif ( $usedHour ) {
1523 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1524 } elseif ( $usedAMPM ) {
1525 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1526 } elseif ( $usedDay ||
$usedHebrewMonth ||
$usedIranianMonth ||
$usedHijriMonth ||
$usedHebrewYear ||
$usedIranianYear ||
$usedHijriYear ||
$usedTennoYear ) {
1527 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1528 // so that they don't need purged every day.
1529 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1531 $possibleTtls = array();
1532 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1534 $possibleTtls[] = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1535 } elseif ( $usedISOYear ) {
1536 // December 28th falls on the last ISO week of the year, every year.
1537 // The last ISO week of a year can be 52 or 53.
1538 $lastWeekOfISOYear = DateTime
::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?
: new DateTimeZone( 'UTC' ) )->format( 'W' );
1539 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1540 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1541 $timeRemainingInWeek = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1542 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1546 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 +
$timeRemainingInDay;
1547 } elseif ( $usedYear ) {
1548 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1549 +
$timeRemainingInDay;
1550 } elseif ( $usedIsLeapYear ) {
1551 $year = substr( $ts, 0, 4 );
1552 $timeRemainingInYear = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1553 +
$timeRemainingInDay;
1555 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1556 // this isn't a leap year. see when the next one starts
1557 $nextCandidate = $year - $mod +
4;
1558 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1559 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
$timeRemainingInYear;
1561 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
$timeRemainingInYear;
1564 // this is a leap year, so the next year isn't
1565 $possibleTtls[] = $timeRemainingInYear;
1569 if ( $possibleTtls ) {
1570 $ttl = min( $possibleTtls );
1577 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1578 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1581 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1582 * Gregorian dates to Iranian dates. Originally written in C, it
1583 * is released under the terms of GNU Lesser General Public
1584 * License. Conversion to PHP was performed by Niklas Laxström.
1586 * Link: http://www.farsiweb.info/jalali/jalali.c
1592 private static function tsToIranian( $ts ) {
1593 $gy = substr( $ts, 0, 4 ) -1600;
1594 $gm = substr( $ts, 4, 2 ) -1;
1595 $gd = substr( $ts, 6, 2 ) -1;
1597 # Days passed from the beginning (including leap years)
1599 +
floor( ( $gy +
3 ) / 4 )
1600 - floor( ( $gy +
99 ) / 100 )
1601 +
floor( ( $gy +
399 ) / 400 );
1603 // Add days of the past months of this year
1604 for ( $i = 0; $i < $gm; $i++
) {
1605 $gDayNo +
= self
::$GREG_DAYS[$i];
1609 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1613 // Days passed in current month
1614 $gDayNo +
= (int)$gd;
1616 $jDayNo = $gDayNo - 79;
1618 $jNp = floor( $jDayNo / 12053 );
1621 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1624 if ( $jDayNo >= 366 ) {
1625 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1626 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1629 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1630 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1636 return array( $jy, $jm, $jd );
1640 * Converting Gregorian dates to Hijri dates.
1642 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1644 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1650 private static function tsToHijri( $ts ) {
1651 $year = substr( $ts, 0, 4 );
1652 $month = substr( $ts, 4, 2 );
1653 $day = substr( $ts, 6, 2 );
1661 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1662 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1664 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1665 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1666 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1669 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1670 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1673 $zl = $zjd -1948440 +
10632;
1674 $zn = (int)( ( $zl - 1 ) / 10631 );
1675 $zl = $zl - 10631 * $zn +
354;
1676 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1677 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1678 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1679 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1680 $zm = (int)( ( 24 * $zl ) / 709 );
1681 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1682 $zy = 30 * $zn +
$zj - 30;
1684 return array( $zy, $zm, $zd );
1688 * Converting Gregorian dates to Hebrew dates.
1690 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1691 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1692 * to translate the relevant functions into PHP and release them under
1695 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1696 * and Adar II is 14. In a non-leap year, Adar is 6.
1702 private static function tsToHebrew( $ts ) {
1704 $year = substr( $ts, 0, 4 );
1705 $month = substr( $ts, 4, 2 );
1706 $day = substr( $ts, 6, 2 );
1708 # Calculate Hebrew year
1709 $hebrewYear = $year +
3760;
1711 # Month number when September = 1, August = 12
1713 if ( $month > 12 ) {
1720 # Calculate day of year from 1 September
1722 for ( $i = 1; $i < $month; $i++
) {
1726 # Check if the year is leap
1727 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1730 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1737 # Calculate the start of the Hebrew year
1738 $start = self
::hebrewYearStart( $hebrewYear );
1740 # Calculate next year's start
1741 if ( $dayOfYear <= $start ) {
1742 # Day is before the start of the year - it is the previous year
1744 $nextStart = $start;
1748 # Add days since previous year's 1 September
1750 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1754 # Start of the new (previous) year
1755 $start = self
::hebrewYearStart( $hebrewYear );
1758 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1761 # Calculate Hebrew day of year
1762 $hebrewDayOfYear = $dayOfYear - $start;
1764 # Difference between year's days
1765 $diff = $nextStart - $start;
1766 # Add 12 (or 13 for leap years) days to ignore the difference between
1767 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1768 # difference is only about the year type
1769 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1775 # Check the year pattern, and is leap year
1776 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1777 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1778 # and non-leap years
1779 $yearPattern = $diff %
30;
1780 # Check if leap year
1781 $isLeap = $diff >= 30;
1783 # Calculate day in the month from number of day in the Hebrew year
1784 # Don't check Adar - if the day is not in Adar, we will stop before;
1785 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1786 $hebrewDay = $hebrewDayOfYear;
1789 while ( $hebrewMonth <= 12 ) {
1790 # Calculate days in this month
1791 if ( $isLeap && $hebrewMonth == 6 ) {
1792 # Adar in a leap year
1794 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1796 if ( $hebrewDay <= $days ) {
1800 # Subtract the days of Adar I
1801 $hebrewDay -= $days;
1804 if ( $hebrewDay <= $days ) {
1810 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1811 # Cheshvan in a complete year (otherwise as the rule below)
1813 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1814 # Kislev in an incomplete year (otherwise as the rule below)
1817 # Odd months have 30 days, even have 29
1818 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1820 if ( $hebrewDay <= $days ) {
1821 # In the current month
1824 # Subtract the days of the current month
1825 $hebrewDay -= $days;
1826 # Try in the next month
1831 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1835 * This calculates the Hebrew year start, as days since 1 September.
1836 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1837 * Used for Hebrew date.
1843 private static function hebrewYearStart( $year ) {
1844 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1845 $b = intval( ( $year - 1 ) %
4 );
1846 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1850 $Mar = intval( $m );
1856 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1857 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1859 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1861 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1865 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1870 * Algorithm to convert Gregorian dates to Thai solar dates,
1871 * Minguo dates or Minguo dates.
1873 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1874 * http://en.wikipedia.org/wiki/Minguo_calendar
1875 * http://en.wikipedia.org/wiki/Japanese_era_name
1877 * @param string $ts 14-character timestamp
1878 * @param string $cName Calender name
1879 * @return array Converted year, month, day
1881 private static function tsToYear( $ts, $cName ) {
1882 $gy = substr( $ts, 0, 4 );
1883 $gm = substr( $ts, 4, 2 );
1884 $gd = substr( $ts, 6, 2 );
1886 if ( !strcmp( $cName, 'thai' ) ) {
1888 # Add 543 years to the Gregorian calendar
1889 # Months and days are identical
1890 $gy_offset = $gy +
543;
1891 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1893 # Deduct 1911 years from the Gregorian calendar
1894 # Months and days are identical
1895 $gy_offset = $gy - 1911;
1896 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1897 # Nengō dates up to Meiji period
1898 # Deduct years from the Gregorian calendar
1899 # depending on the nengo periods
1900 # Months and days are identical
1902 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1903 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1906 $gy_gannen = $gy - 1868 +
1;
1907 $gy_offset = $gy_gannen;
1908 if ( $gy_gannen == 1 ) {
1911 $gy_offset = '明治' . $gy_offset;
1913 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1914 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1915 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1916 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1917 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1920 $gy_gannen = $gy - 1912 +
1;
1921 $gy_offset = $gy_gannen;
1922 if ( $gy_gannen == 1 ) {
1925 $gy_offset = '大正' . $gy_offset;
1927 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1928 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1929 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1932 $gy_gannen = $gy - 1926 +
1;
1933 $gy_offset = $gy_gannen;
1934 if ( $gy_gannen == 1 ) {
1937 $gy_offset = '昭和' . $gy_offset;
1940 $gy_gannen = $gy - 1989 +
1;
1941 $gy_offset = $gy_gannen;
1942 if ( $gy_gannen == 1 ) {
1945 $gy_offset = '平成' . $gy_offset;
1951 return array( $gy_offset, $gm, $gd );
1955 * Roman number formatting up to 10000
1961 static function romanNumeral( $num ) {
1962 static $table = array(
1963 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1964 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1965 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1966 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1967 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1970 $num = intval( $num );
1971 if ( $num > 10000 ||
$num <= 0 ) {
1976 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1977 if ( $num >= $pow10 ) {
1978 $s .= $table[$i][(int)floor( $num / $pow10 )];
1980 $num = $num %
$pow10;
1986 * Hebrew Gematria number formatting up to 9999
1992 static function hebrewNumeral( $num ) {
1993 static $table = array(
1994 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1995 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1996 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1997 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
2000 $num = intval( $num );
2001 if ( $num > 9999 ||
$num <= 0 ) {
2006 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2007 if ( $num >= $pow10 ) {
2008 if ( $num == 15 ||
$num == 16 ) {
2009 $s .= $table[0][9] . $table[0][$num - 9];
2012 $s .= $table[$i][intval( ( $num / $pow10 ) )];
2013 if ( $pow10 == 1000 ) {
2018 $num = $num %
$pow10;
2020 if ( strlen( $s ) == 2 ) {
2023 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
2024 $str .= substr( $s, strlen( $s ) - 2, 2 );
2026 $start = substr( $str, 0, strlen( $str ) - 2 );
2027 $end = substr( $str, strlen( $str ) - 2 );
2030 $str = $start . 'ך';
2033 $str = $start . 'ם';
2036 $str = $start . 'ן';
2039 $str = $start . 'ף';
2042 $str = $start . 'ץ';
2049 * Used by date() and time() to adjust the time output.
2051 * @param string $ts The time in date('YmdHis') format
2052 * @param mixed $tz Adjust the time by this amount (default false, mean we
2053 * get user timecorrection setting)
2056 function userAdjust( $ts, $tz = false ) {
2057 global $wgUser, $wgLocalTZoffset;
2059 if ( $tz === false ) {
2060 $tz = $wgUser->getOption( 'timecorrection' );
2063 $data = explode( '|', $tz, 3 );
2065 if ( $data[0] == 'ZoneInfo' ) {
2066 wfSuppressWarnings();
2067 $userTZ = timezone_open( $data[2] );
2068 wfRestoreWarnings();
2069 if ( $userTZ !== false ) {
2070 $date = date_create( $ts, timezone_open( 'UTC' ) );
2071 date_timezone_set( $date, $userTZ );
2072 $date = date_format( $date, 'YmdHis' );
2075 # Unrecognized timezone, default to 'Offset' with the stored offset.
2076 $data[0] = 'Offset';
2079 if ( $data[0] == 'System' ||
$tz == '' ) {
2080 # Global offset in minutes.
2081 $minDiff = $wgLocalTZoffset;
2082 } elseif ( $data[0] == 'Offset' ) {
2083 $minDiff = intval( $data[1] );
2085 $data = explode( ':', $tz );
2086 if ( count( $data ) == 2 ) {
2087 $data[0] = intval( $data[0] );
2088 $data[1] = intval( $data[1] );
2089 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2090 if ( $data[0] < 0 ) {
2091 $minDiff = -$minDiff;
2094 $minDiff = intval( $data[0] ) * 60;
2098 # No difference ? Return time unchanged
2099 if ( 0 == $minDiff ) {
2103 wfSuppressWarnings(); // E_STRICT system time bitching
2104 # Generate an adjusted date; take advantage of the fact that mktime
2105 # will normalize out-of-range values so we don't have to split $minDiff
2106 # into hours and minutes.
2108 (int)substr( $ts, 8, 2 ) ), # Hours
2109 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2110 (int)substr( $ts, 12, 2 ), # Seconds
2111 (int)substr( $ts, 4, 2 ), # Month
2112 (int)substr( $ts, 6, 2 ), # Day
2113 (int)substr( $ts, 0, 4 ) ); # Year
2115 $date = date( 'YmdHis', $t );
2116 wfRestoreWarnings();
2122 * This is meant to be used by time(), date(), and timeanddate() to get
2123 * the date preference they're supposed to use, it should be used in
2127 * function timeanddate([...], $format = true) {
2128 * $datePreference = $this->dateFormat($format);
2133 * @param int|string|bool $usePrefs If true, the user's preference is used
2134 * if false, the site/language default is used
2135 * if int/string, assumed to be a format.
2138 function dateFormat( $usePrefs = true ) {
2141 if ( is_bool( $usePrefs ) ) {
2143 $datePreference = $wgUser->getDatePreference();
2145 $datePreference = (string)User
::getDefaultOption( 'date' );
2148 $datePreference = (string)$usePrefs;
2152 if ( $datePreference == '' ) {
2156 return $datePreference;
2160 * Get a format string for a given type and preference
2161 * @param string $type May be date, time or both
2162 * @param string $pref The format name as it appears in Messages*.php
2164 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2168 function getDateFormatString( $type, $pref ) {
2169 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2170 if ( $pref == 'default' ) {
2171 $pref = $this->getDefaultDateFormat();
2172 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2174 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2176 if ( $type === 'pretty' && $df === null ) {
2177 $df = $this->getDateFormatString( 'date', $pref );
2180 if ( $df === null ) {
2181 $pref = $this->getDefaultDateFormat();
2182 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2185 $this->dateFormatStrings
[$type][$pref] = $df;
2187 return $this->dateFormatStrings
[$type][$pref];
2191 * @param string $ts The time format which needs to be turned into a
2192 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2193 * @param bool $adj Whether to adjust the time output according to the
2194 * user configured offset ($timecorrection)
2195 * @param mixed $format True to use user's date format preference
2196 * @param string|bool $timecorrection The time offset as returned by
2197 * validateTimeZone() in Special:Preferences
2200 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2201 $ts = wfTimestamp( TS_MW
, $ts );
2203 $ts = $this->userAdjust( $ts, $timecorrection );
2205 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2206 return $this->sprintfDate( $df, $ts );
2210 * @param string $ts The time format which needs to be turned into a
2211 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2212 * @param bool $adj Whether to adjust the time output according to the
2213 * user configured offset ($timecorrection)
2214 * @param mixed $format True to use user's date format preference
2215 * @param string|bool $timecorrection The time offset as returned by
2216 * validateTimeZone() in Special:Preferences
2219 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2220 $ts = wfTimestamp( TS_MW
, $ts );
2222 $ts = $this->userAdjust( $ts, $timecorrection );
2224 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2225 return $this->sprintfDate( $df, $ts );
2229 * @param string $ts The time format which needs to be turned into a
2230 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2231 * @param bool $adj Whether to adjust the time output according to the
2232 * user configured offset ($timecorrection)
2233 * @param mixed $format What format to return, if it's false output the
2234 * default one (default true)
2235 * @param string|bool $timecorrection The time offset as returned by
2236 * validateTimeZone() in Special:Preferences
2239 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2240 $ts = wfTimestamp( TS_MW
, $ts );
2242 $ts = $this->userAdjust( $ts, $timecorrection );
2244 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2245 return $this->sprintfDate( $df, $ts );
2249 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2253 * @param int $seconds The amount of seconds.
2254 * @param array $chosenIntervals The intervals to enable.
2258 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2259 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2261 $segments = array();
2263 foreach ( $intervals as $intervalName => $intervalValue ) {
2264 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2265 // duration-years, duration-decades, duration-centuries, duration-millennia
2266 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2267 $segments[] = $message->inLanguage( $this )->escaped();
2270 return $this->listToText( $segments );
2274 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2275 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2279 * @param int $seconds The amount of seconds.
2280 * @param array $chosenIntervals The intervals to enable.
2284 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2285 if ( empty( $chosenIntervals ) ) {
2286 $chosenIntervals = array(
2298 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2299 $sortedNames = array_keys( $intervals );
2300 $smallestInterval = array_pop( $sortedNames );
2302 $segments = array();
2304 foreach ( $intervals as $name => $length ) {
2305 $value = floor( $seconds / $length );
2307 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2308 $seconds -= $value * $length;
2309 $segments[$name] = $value;
2317 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2319 * @param string $type Can be 'date', 'time' or 'both'
2320 * @param string $ts The time format which needs to be turned into a
2321 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2322 * @param User $user User object used to get preferences for timezone and format
2323 * @param array $options Array, can contain the following keys:
2324 * - 'timecorrection': time correction, can have the following values:
2325 * - true: use user's preference
2326 * - false: don't use time correction
2327 * - int: value of time correction in minutes
2328 * - 'format': format to use, can have the following values:
2329 * - true: use user's preference
2330 * - false: use default preference
2331 * - string: format to use
2335 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2336 $ts = wfTimestamp( TS_MW
, $ts );
2337 $options +
= array( 'timecorrection' => true, 'format' => true );
2338 if ( $options['timecorrection'] !== false ) {
2339 if ( $options['timecorrection'] === true ) {
2340 $offset = $user->getOption( 'timecorrection' );
2342 $offset = $options['timecorrection'];
2344 $ts = $this->userAdjust( $ts, $offset );
2346 if ( $options['format'] === true ) {
2347 $format = $user->getDatePreference();
2349 $format = $options['format'];
2351 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2352 return $this->sprintfDate( $df, $ts );
2356 * Get the formatted date for the given timestamp and formatted for
2359 * @param mixed $ts Mixed: the time format which needs to be turned into a
2360 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2361 * @param User $user User object used to get preferences for timezone and format
2362 * @param array $options Array, can contain the following keys:
2363 * - 'timecorrection': time correction, can have the following values:
2364 * - true: use user's preference
2365 * - false: don't use time correction
2366 * - int: value of time correction in minutes
2367 * - 'format': format to use, can have the following values:
2368 * - true: use user's preference
2369 * - false: use default preference
2370 * - string: format to use
2374 public function userDate( $ts, User
$user, array $options = array() ) {
2375 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2379 * Get the formatted time for the given timestamp and formatted for
2382 * @param mixed $ts The time format which needs to be turned into a
2383 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2384 * @param User $user User object used to get preferences for timezone and format
2385 * @param array $options Array, can contain the following keys:
2386 * - 'timecorrection': time correction, can have the following values:
2387 * - true: use user's preference
2388 * - false: don't use time correction
2389 * - int: value of time correction in minutes
2390 * - 'format': format to use, can have the following values:
2391 * - true: use user's preference
2392 * - false: use default preference
2393 * - string: format to use
2397 public function userTime( $ts, User
$user, array $options = array() ) {
2398 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2402 * Get the formatted date and time for the given timestamp and formatted for
2405 * @param mixed $ts The time format which needs to be turned into a
2406 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2407 * @param User $user User object used to get preferences for timezone and format
2408 * @param array $options Array, can contain the following keys:
2409 * - 'timecorrection': time correction, can have the following values:
2410 * - true: use user's preference
2411 * - false: don't use time correction
2412 * - int: value of time correction in minutes
2413 * - 'format': format to use, can have the following values:
2414 * - true: use user's preference
2415 * - false: use default preference
2416 * - string: format to use
2420 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2421 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2425 * Convert an MWTimestamp into a pretty human-readable timestamp using
2426 * the given user preferences and relative base time.
2428 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2429 * on your timestamp object, which will then call this function. Calling
2430 * this function directly will cause hooks to be skipped over.
2432 * @see MWTimestamp::getHumanTimestamp
2433 * @param MWTimestamp $ts Timestamp to prettify
2434 * @param MWTimestamp $relativeTo Base timestamp
2435 * @param User $user User preferences to use
2436 * @return string Human timestamp
2439 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2440 $diff = $ts->diff( $relativeTo );
2441 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2442 (int)$relativeTo->timestamp
->format( 'w' ) );
2443 $days = $diff->days ?
: (int)$diffDay;
2444 if ( $diff->invert ||
$days > 5
2445 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2447 // Timestamps are in different years: use full timestamp
2448 // Also do full timestamp for future dates
2450 * @todo FIXME: Add better handling of future timestamps.
2452 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2453 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2454 } elseif ( $days > 5 ) {
2455 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2456 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2457 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2458 } elseif ( $days > 1 ) {
2459 // Timestamp within the past week: show the day of the week and time
2460 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2461 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2463 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2464 $ts = wfMessage( "$weekday-at" )
2465 ->inLanguage( $this )
2466 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2468 } elseif ( $days == 1 ) {
2469 // Timestamp was yesterday: say 'yesterday' and the time.
2470 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2471 $ts = wfMessage( 'yesterday-at' )
2472 ->inLanguage( $this )
2473 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2475 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2476 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2477 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2478 $ts = wfMessage( 'today-at' )
2479 ->inLanguage( $this )
2480 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2483 // From here on in, the timestamp was soon enough ago so that we can simply say
2484 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2485 } elseif ( $diff->h
== 1 ) {
2486 // Less than 90 minutes, but more than an hour ago.
2487 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2488 } elseif ( $diff->i
>= 1 ) {
2489 // A few minutes ago.
2490 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2491 } elseif ( $diff->s
>= 30 ) {
2492 // Less than a minute, but more than 30 sec ago.
2493 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2495 // Less than 30 seconds ago.
2496 $ts = wfMessage( 'just-now' )->text();
2503 * @param string $key
2504 * @return array|null
2506 function getMessage( $key ) {
2507 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2513 function getAllMessages() {
2514 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2519 * @param string $out
2520 * @param string $string
2523 function iconv( $in, $out, $string ) {
2524 # This is a wrapper for iconv in all languages except esperanto,
2525 # which does some nasty x-conversions beforehand
2527 # Even with //IGNORE iconv can whine about illegal characters in
2528 # *input* string. We just ignore those too.
2529 # REF: http://bugs.php.net/bug.php?id=37166
2530 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2531 wfSuppressWarnings();
2532 $text = iconv( $in, $out . '//IGNORE', $string );
2533 wfRestoreWarnings();
2537 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2540 * @param array $matches
2541 * @return mixed|string
2543 function ucwordbreaksCallbackAscii( $matches ) {
2544 return $this->ucfirst( $matches[1] );
2548 * @param array $matches
2551 function ucwordbreaksCallbackMB( $matches ) {
2552 return mb_strtoupper( $matches[0] );
2556 * @param array $matches
2559 function ucCallback( $matches ) {
2560 list( $wikiUpperChars ) = self
::getCaseMaps();
2561 return strtr( $matches[1], $wikiUpperChars );
2565 * @param array $matches
2568 function lcCallback( $matches ) {
2569 list( , $wikiLowerChars ) = self
::getCaseMaps();
2570 return strtr( $matches[1], $wikiLowerChars );
2574 * @param array $matches
2577 function ucwordsCallbackMB( $matches ) {
2578 return mb_strtoupper( $matches[0] );
2582 * @param array $matches
2585 function ucwordsCallbackWiki( $matches ) {
2586 list( $wikiUpperChars ) = self
::getCaseMaps();
2587 return strtr( $matches[0], $wikiUpperChars );
2591 * Make a string's first character uppercase
2593 * @param string $str
2597 function ucfirst( $str ) {
2599 if ( $o < 96 ) { // if already uppercase...
2601 } elseif ( $o < 128 ) {
2602 return ucfirst( $str ); // use PHP's ucfirst()
2604 // fall back to more complex logic in case of multibyte strings
2605 return $this->uc( $str, true );
2610 * Convert a string to uppercase
2612 * @param string $str
2613 * @param bool $first
2617 function uc( $str, $first = false ) {
2618 if ( function_exists( 'mb_strtoupper' ) ) {
2620 if ( $this->isMultibyte( $str ) ) {
2621 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2623 return ucfirst( $str );
2626 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2629 if ( $this->isMultibyte( $str ) ) {
2630 $x = $first ?
'^' : '';
2631 return preg_replace_callback(
2632 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2633 array( $this, 'ucCallback' ),
2637 return $first ?
ucfirst( $str ) : strtoupper( $str );
2643 * @param string $str
2644 * @return mixed|string
2646 function lcfirst( $str ) {
2649 return strval( $str );
2650 } elseif ( $o >= 128 ) {
2651 return $this->lc( $str, true );
2652 } elseif ( $o > 96 ) {
2655 $str[0] = strtolower( $str[0] );
2661 * @param string $str
2662 * @param bool $first
2663 * @return mixed|string
2665 function lc( $str, $first = false ) {
2666 if ( function_exists( 'mb_strtolower' ) ) {
2668 if ( $this->isMultibyte( $str ) ) {
2669 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2671 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2674 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2677 if ( $this->isMultibyte( $str ) ) {
2678 $x = $first ?
'^' : '';
2679 return preg_replace_callback(
2680 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2681 array( $this, 'lcCallback' ),
2685 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2691 * @param string $str
2694 function isMultibyte( $str ) {
2695 return (bool)preg_match( '/[\x80-\xff]/', $str );
2699 * @param string $str
2700 * @return mixed|string
2702 function ucwords( $str ) {
2703 if ( $this->isMultibyte( $str ) ) {
2704 $str = $this->lc( $str );
2706 // regexp to find first letter in each word (i.e. after each space)
2707 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2709 // function to use to capitalize a single char
2710 if ( function_exists( 'mb_strtoupper' ) ) {
2711 return preg_replace_callback(
2713 array( $this, 'ucwordsCallbackMB' ),
2717 return preg_replace_callback(
2719 array( $this, 'ucwordsCallbackWiki' ),
2724 return ucwords( strtolower( $str ) );
2729 * capitalize words at word breaks
2731 * @param string $str
2734 function ucwordbreaks( $str ) {
2735 if ( $this->isMultibyte( $str ) ) {
2736 $str = $this->lc( $str );
2738 // since \b doesn't work for UTF-8, we explicitely define word break chars
2739 $breaks = "[ \-\(\)\}\{\.,\?!]";
2741 // find first letter after word break
2742 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2743 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2745 if ( function_exists( 'mb_strtoupper' ) ) {
2746 return preg_replace_callback(
2748 array( $this, 'ucwordbreaksCallbackMB' ),
2752 return preg_replace_callback(
2754 array( $this, 'ucwordsCallbackWiki' ),
2759 return preg_replace_callback(
2760 '/\b([\w\x80-\xff]+)\b/',
2761 array( $this, 'ucwordbreaksCallbackAscii' ),
2768 * Return a case-folded representation of $s
2770 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2771 * and $s2 are the same except for the case of their characters. It is not
2772 * necessary for the value returned to make sense when displayed.
2774 * Do *not* perform any other normalisation in this function. If a caller
2775 * uses this function when it should be using a more general normalisation
2776 * function, then fix the caller.
2782 function caseFold( $s ) {
2783 return $this->uc( $s );
2790 function checkTitleEncoding( $s ) {
2791 if ( is_array( $s ) ) {
2792 throw new MWException( 'Given array to checkTitleEncoding.' );
2794 if ( StringUtils
::isUtf8( $s ) ) {
2798 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2804 function fallback8bitEncoding() {
2805 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2809 * Most writing systems use whitespace to break up words.
2810 * Some languages such as Chinese don't conventionally do this,
2811 * which requires special handling when breaking up words for
2816 function hasWordBreaks() {
2821 * Some languages such as Chinese require word segmentation,
2822 * Specify such segmentation when overridden in derived class.
2824 * @param string $string
2827 function segmentByWord( $string ) {
2832 * Some languages have special punctuation need to be normalized.
2833 * Make such changes here.
2835 * @param string $string
2838 function normalizeForSearch( $string ) {
2839 return self
::convertDoubleWidth( $string );
2843 * convert double-width roman characters to single-width.
2844 * range: ff00-ff5f ~= 0020-007f
2846 * @param string $string
2850 protected static function convertDoubleWidth( $string ) {
2851 static $full = null;
2852 static $half = null;
2854 if ( $full === null ) {
2855 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2856 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2857 $full = str_split( $fullWidth, 3 );
2858 $half = str_split( $halfWidth );
2861 $string = str_replace( $full, $half, $string );
2866 * @param string $string
2867 * @param string $pattern
2870 protected static function insertSpace( $string, $pattern ) {
2871 $string = preg_replace( $pattern, " $1 ", $string );
2872 $string = preg_replace( '/ +/', ' ', $string );
2877 * @param array $termsArray
2880 function convertForSearchResult( $termsArray ) {
2881 # some languages, e.g. Chinese, need to do a conversion
2882 # in order for search results to be displayed correctly
2887 * Get the first character of a string.
2892 function firstChar( $s ) {
2895 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2896 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2901 if ( isset( $matches[1] ) ) {
2902 if ( strlen( $matches[1] ) != 3 ) {
2906 // Break down Hangul syllables to grab the first jamo
2907 $code = utf8ToCodepoint( $matches[1] );
2908 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2910 } elseif ( $code < 0xb098 ) {
2911 return "\xe3\x84\xb1";
2912 } elseif ( $code < 0xb2e4 ) {
2913 return "\xe3\x84\xb4";
2914 } elseif ( $code < 0xb77c ) {
2915 return "\xe3\x84\xb7";
2916 } elseif ( $code < 0xb9c8 ) {
2917 return "\xe3\x84\xb9";
2918 } elseif ( $code < 0xbc14 ) {
2919 return "\xe3\x85\x81";
2920 } elseif ( $code < 0xc0ac ) {
2921 return "\xe3\x85\x82";
2922 } elseif ( $code < 0xc544 ) {
2923 return "\xe3\x85\x85";
2924 } elseif ( $code < 0xc790 ) {
2925 return "\xe3\x85\x87";
2926 } elseif ( $code < 0xcc28 ) {
2927 return "\xe3\x85\x88";
2928 } elseif ( $code < 0xce74 ) {
2929 return "\xe3\x85\x8a";
2930 } elseif ( $code < 0xd0c0 ) {
2931 return "\xe3\x85\x8b";
2932 } elseif ( $code < 0xd30c ) {
2933 return "\xe3\x85\x8c";
2934 } elseif ( $code < 0xd558 ) {
2935 return "\xe3\x85\x8d";
2937 return "\xe3\x85\x8e";
2944 function initEncoding() {
2945 # Some languages may have an alternate char encoding option
2946 # (Esperanto X-coding, Japanese furigana conversion, etc)
2947 # If this language is used as the primary content language,
2948 # an override to the defaults can be set here on startup.
2955 function recodeForEdit( $s ) {
2956 # For some languages we'll want to explicitly specify
2957 # which characters make it into the edit box raw
2958 # or are converted in some way or another.
2959 global $wgEditEncoding;
2960 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2963 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2971 function recodeInput( $s ) {
2972 # Take the previous into account.
2973 global $wgEditEncoding;
2974 if ( $wgEditEncoding != '' ) {
2975 $enc = $wgEditEncoding;
2979 if ( $enc == 'UTF-8' ) {
2982 return $this->iconv( $enc, 'UTF-8', $s );
2987 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2988 * also cleans up certain backwards-compatible sequences, converting them
2989 * to the modern Unicode equivalent.
2991 * This is language-specific for performance reasons only.
2997 function normalize( $s ) {
2998 global $wgAllUnicodeFixes;
2999 $s = UtfNormal
::cleanUp( $s );
3000 if ( $wgAllUnicodeFixes ) {
3001 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
3002 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
3009 * Transform a string using serialized data stored in the given file (which
3010 * must be in the serialized subdirectory of $IP). The file contains pairs
3011 * mapping source characters to destination characters.
3013 * The data is cached in process memory. This will go faster if you have the
3014 * FastStringSearch extension.
3016 * @param string $file
3017 * @param string $string
3019 * @throws MWException
3022 function transformUsingPairFile( $file, $string ) {
3023 if ( !isset( $this->transformData
[$file] ) ) {
3024 $data = wfGetPrecompiledData( $file );
3025 if ( $data === false ) {
3026 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
3028 $this->transformData
[$file] = new ReplacementArray( $data );
3030 return $this->transformData
[$file]->replace( $string );
3034 * For right-to-left language support
3039 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
3043 * Return the correct HTML 'dir' attribute value for this language.
3047 return $this->isRTL() ?
'rtl' : 'ltr';
3051 * Return 'left' or 'right' as appropriate alignment for line-start
3052 * for this language's text direction.
3054 * Should be equivalent to CSS3 'start' text-align value....
3058 function alignStart() {
3059 return $this->isRTL() ?
'right' : 'left';
3063 * Return 'right' or 'left' as appropriate alignment for line-end
3064 * for this language's text direction.
3066 * Should be equivalent to CSS3 'end' text-align value....
3070 function alignEnd() {
3071 return $this->isRTL() ?
'left' : 'right';
3075 * A hidden direction mark (LRM or RLM), depending on the language direction.
3076 * Unlike getDirMark(), this function returns the character as an HTML entity.
3077 * This function should be used when the output is guaranteed to be HTML,
3078 * because it makes the output HTML source code more readable. When
3079 * the output is plain text or can be escaped, getDirMark() should be used.
3081 * @param bool $opposite Get the direction mark opposite to your language
3085 function getDirMarkEntity( $opposite = false ) {
3087 return $this->isRTL() ?
'‎' : '‏';
3089 return $this->isRTL() ?
'‏' : '‎';
3093 * A hidden direction mark (LRM or RLM), depending on the language direction.
3094 * This function produces them as invisible Unicode characters and
3095 * the output may be hard to read and debug, so it should only be used
3096 * when the output is plain text or can be escaped. When the output is
3097 * HTML, use getDirMarkEntity() instead.
3099 * @param bool $opposite Get the direction mark opposite to your language
3102 function getDirMark( $opposite = false ) {
3103 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3104 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3106 return $this->isRTL() ?
$lrm : $rlm;
3108 return $this->isRTL() ?
$rlm : $lrm;
3114 function capitalizeAllNouns() {
3115 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3119 * An arrow, depending on the language direction.
3121 * @param string $direction The direction of the arrow: forwards (default),
3122 * backwards, left, right, up, down.
3125 function getArrow( $direction = 'forwards' ) {
3126 switch ( $direction ) {
3128 return $this->isRTL() ?
'←' : '→';
3130 return $this->isRTL() ?
'→' : '←';
3143 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3147 function linkPrefixExtension() {
3148 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3152 * Get all magic words from cache.
3155 function getMagicWords() {
3156 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3160 * Run the LanguageGetMagic hook once.
3162 protected function doMagicHook() {
3163 if ( $this->mMagicHookDone
) {
3166 $this->mMagicHookDone
= true;
3167 wfProfileIn( 'LanguageGetMagic' );
3168 Hooks
::run( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3169 wfProfileOut( 'LanguageGetMagic' );
3173 * Fill a MagicWord object with data from here
3175 * @param MagicWord $mw
3177 function getMagic( $mw ) {
3178 // Saves a function call
3179 if ( !$this->mMagicHookDone
) {
3180 $this->doMagicHook();
3183 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3184 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3186 $rawEntry = self
::$dataCache->getSubitem(
3187 $this->mCode
, 'magicWords', $mw->mId
);
3190 if ( !is_array( $rawEntry ) ) {
3191 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3193 $mw->mCaseSensitive
= $rawEntry[0];
3194 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3199 * Add magic words to the extension array
3201 * @param array $newWords
3203 function addMagicWordsByLang( $newWords ) {
3204 $fallbackChain = $this->getFallbackLanguages();
3205 $fallbackChain = array_reverse( $fallbackChain );
3206 foreach ( $fallbackChain as $code ) {
3207 if ( isset( $newWords[$code] ) ) {
3208 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3214 * Get special page names, as an associative array
3215 * canonical name => array of valid names, including aliases
3218 function getSpecialPageAliases() {
3219 // Cache aliases because it may be slow to load them
3220 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3222 $this->mExtendedSpecialPageAliases
=
3223 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3224 Hooks
::run( 'LanguageGetSpecialPageAliases',
3225 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3228 return $this->mExtendedSpecialPageAliases
;
3232 * Italic is unsuitable for some languages
3234 * @param string $text The text to be emphasized.
3237 function emphasize( $text ) {
3238 return "<em>$text</em>";
3242 * Normally we output all numbers in plain en_US style, that is
3243 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3244 * point twohundredthirtyfive. However this is not suitable for all
3245 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3246 * Icelandic just want to use commas instead of dots, and dots instead
3247 * of commas like "293.291,235".
3249 * An example of this function being called:
3251 * wfMessage( 'message' )->numParams( $num )->text()
3254 * See $separatorTransformTable on MessageIs.php for
3255 * the , => . and . => , implementation.
3257 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3258 * @param int|float $number The string to be formatted, should be an integer
3259 * or a floating point number.
3260 * @param bool $nocommafy Set to true for special numbers like dates
3263 public function formatNum( $number, $nocommafy = false ) {
3264 global $wgTranslateNumerals;
3265 if ( !$nocommafy ) {
3266 $number = $this->commafy( $number );
3267 $s = $this->separatorTransformTable();
3269 $number = strtr( $number, $s );
3273 if ( $wgTranslateNumerals ) {
3274 $s = $this->digitTransformTable();
3276 $number = strtr( $number, $s );
3284 * Front-end for non-commafied formatNum
3286 * @param int|float $number The string to be formatted, should be an integer
3287 * or a floating point number.
3291 public function formatNumNoSeparators( $number ) {
3292 return $this->formatNum( $number, true );
3296 * @param string $number
3299 public function parseFormattedNumber( $number ) {
3300 $s = $this->digitTransformTable();
3302 // eliminate empty array values such as ''. (bug 64347)
3303 $s = array_filter( $s );
3304 $number = strtr( $number, array_flip( $s ) );
3307 $s = $this->separatorTransformTable();
3309 // eliminate empty array values such as ''. (bug 64347)
3310 $s = array_filter( $s );
3311 $number = strtr( $number, array_flip( $s ) );
3314 $number = strtr( $number, array( ',' => '' ) );
3319 * Adds commas to a given number
3321 * @param mixed $number
3324 function commafy( $number ) {
3325 $digitGroupingPattern = $this->digitGroupingPattern();
3326 if ( $number === null ) {
3330 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3331 // default grouping is at thousands, use the same for ###,###,### pattern too.
3332 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3334 // Ref: http://cldr.unicode.org/translation/number-patterns
3336 if ( intval( $number ) < 0 ) {
3337 // For negative numbers apply the algorithm like positive number and add sign.
3339 $number = substr( $number, 1 );
3341 $integerPart = array();
3342 $decimalPart = array();
3343 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3344 preg_match( "/\d+/", $number, $integerPart );
3345 preg_match( "/\.\d*/", $number, $decimalPart );
3346 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3347 if ( $groupedNumber === $number ) {
3348 // the string does not have any number part. Eg: .12345
3349 return $sign . $groupedNumber;
3351 $start = $end = ($integerPart) ?
strlen( $integerPart[0] ) : 0;
3352 while ( $start > 0 ) {
3353 $match = $matches[0][$numMatches - 1];
3354 $matchLen = strlen( $match );
3355 $start = $end - $matchLen;
3359 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3361 if ( $numMatches > 1 ) {
3362 // use the last pattern for the rest of the number
3366 $groupedNumber = "," . $groupedNumber;
3369 return $sign . $groupedNumber;
3376 function digitGroupingPattern() {
3377 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3383 function digitTransformTable() {
3384 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3390 function separatorTransformTable() {
3391 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3395 * Take a list of strings and build a locale-friendly comma-separated
3396 * list, using the local comma-separator message.
3397 * The last two strings are chained with an "and".
3398 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3400 * @param string[] $l
3403 function listToText( array $l ) {
3404 $m = count( $l ) - 1;
3409 $and = $this->getMessageFromDB( 'and' );
3410 $space = $this->getMessageFromDB( 'word-separator' );
3412 $comma = $this->getMessageFromDB( 'comma-separator' );
3416 for ( $i = $m - 1; $i >= 0; $i-- ) {
3417 if ( $i == $m - 1 ) {
3418 $s = $l[$i] . $and . $space . $s;
3420 $s = $l[$i] . $comma . $s;
3427 * Take a list of strings and build a locale-friendly comma-separated
3428 * list, using the local comma-separator message.
3429 * @param string[] $list Array of strings to put in a comma list
3432 function commaList( array $list ) {
3434 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3440 * Take a list of strings and build a locale-friendly semicolon-separated
3441 * list, using the local semicolon-separator message.
3442 * @param string[] $list Array of strings to put in a semicolon list
3445 function semicolonList( array $list ) {
3447 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3453 * Same as commaList, but separate it with the pipe instead.
3454 * @param string[] $list Array of strings to put in a pipe list
3457 function pipeList( array $list ) {
3459 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3465 * Truncate a string to a specified length in bytes, appending an optional
3466 * string (e.g. for ellipses)
3468 * The database offers limited byte lengths for some columns in the database;
3469 * multi-byte character sets mean we need to ensure that only whole characters
3470 * are included, otherwise broken characters can be passed to the user
3472 * If $length is negative, the string will be truncated from the beginning
3474 * @param string $string String to truncate
3475 * @param int $length Maximum length (including ellipses)
3476 * @param string $ellipsis String to append to the truncated text
3477 * @param bool $adjustLength Subtract length of ellipsis from $length.
3478 * $adjustLength was introduced in 1.18, before that behaved as if false.
3481 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3482 # Use the localized ellipsis character
3483 if ( $ellipsis == '...' ) {
3484 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3486 # Check if there is no need to truncate
3487 if ( $length == 0 ) {
3488 return $ellipsis; // convention
3489 } elseif ( strlen( $string ) <= abs( $length ) ) {
3490 return $string; // no need to truncate
3492 $stringOriginal = $string;
3493 # If ellipsis length is >= $length then we can't apply $adjustLength
3494 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3495 $string = $ellipsis; // this can be slightly unexpected
3496 # Otherwise, truncate and add ellipsis...
3498 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3499 if ( $length > 0 ) {
3500 $length -= $eLength;
3501 $string = substr( $string, 0, $length ); // xyz...
3502 $string = $this->removeBadCharLast( $string );
3503 $string = rtrim( $string );
3504 $string = $string . $ellipsis;
3506 $length +
= $eLength;
3507 $string = substr( $string, $length ); // ...xyz
3508 $string = $this->removeBadCharFirst( $string );
3509 $string = ltrim( $string );
3510 $string = $ellipsis . $string;
3513 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3514 # This check is *not* redundant if $adjustLength, due to the single case where
3515 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3516 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3519 return $stringOriginal;
3524 * Remove bytes that represent an incomplete Unicode character
3525 * at the end of string (e.g. bytes of the char are missing)
3527 * @param string $string
3530 protected function removeBadCharLast( $string ) {
3531 if ( $string != '' ) {
3532 $char = ord( $string[strlen( $string ) - 1] );
3534 if ( $char >= 0xc0 ) {
3535 # We got the first byte only of a multibyte char; remove it.
3536 $string = substr( $string, 0, -1 );
3537 } elseif ( $char >= 0x80 &&
3538 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3539 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3541 # We chopped in the middle of a character; remove it
3549 * Remove bytes that represent an incomplete Unicode character
3550 * at the start of string (e.g. bytes of the char are missing)
3552 * @param string $string
3555 protected function removeBadCharFirst( $string ) {
3556 if ( $string != '' ) {
3557 $char = ord( $string[0] );
3558 if ( $char >= 0x80 && $char < 0xc0 ) {
3559 # We chopped in the middle of a character; remove the whole thing
3560 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3567 * Truncate a string of valid HTML to a specified length in bytes,
3568 * appending an optional string (e.g. for ellipses), and return valid HTML
3570 * This is only intended for styled/linked text, such as HTML with
3571 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3572 * Also, this will not detect things like "display:none" CSS.
3574 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3576 * @param string $text HTML string to truncate
3577 * @param int $length (zero/positive) Maximum length (including ellipses)
3578 * @param string $ellipsis String to append to the truncated text
3581 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3582 # Use the localized ellipsis character
3583 if ( $ellipsis == '...' ) {
3584 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3586 # Check if there is clearly no need to truncate
3587 if ( $length <= 0 ) {
3588 return $ellipsis; // no text shown, nothing to format (convention)
3589 } elseif ( strlen( $text ) <= $length ) {
3590 return $text; // string short enough even *with* HTML (short-circuit)
3593 $dispLen = 0; // innerHTML legth so far
3594 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3595 $tagType = 0; // 0-open, 1-close
3596 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3597 $entityState = 0; // 0-not entity, 1-entity
3598 $tag = $ret = ''; // accumulated tag name, accumulated result string
3599 $openTags = array(); // open tag stack
3600 $maybeState = null; // possible truncation state
3602 $textLen = strlen( $text );
3603 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3604 for ( $pos = 0; true; ++
$pos ) {
3605 # Consider truncation once the display length has reached the maximim.
3606 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3607 # Check that we're not in the middle of a bracket/entity...
3608 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3609 if ( !$testingEllipsis ) {
3610 $testingEllipsis = true;
3611 # Save where we are; we will truncate here unless there turn out to
3612 # be so few remaining characters that truncation is not necessary.
3613 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3614 $maybeState = array( $ret, $openTags ); // save state
3616 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3617 # String in fact does need truncation, the truncation point was OK.
3618 list( $ret, $openTags ) = $maybeState; // reload state
3619 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3620 $ret .= $ellipsis; // add ellipsis
3624 if ( $pos >= $textLen ) {
3625 break; // extra iteration just for above checks
3628 # Read the next char...
3630 $lastCh = $pos ?
$text[$pos - 1] : '';
3631 $ret .= $ch; // add to result string
3633 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3634 $entityState = 0; // for bad HTML
3635 $bracketState = 1; // tag started (checking for backslash)
3636 } elseif ( $ch == '>' ) {
3637 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3638 $entityState = 0; // for bad HTML
3639 $bracketState = 0; // out of brackets
3640 } elseif ( $bracketState == 1 ) {
3642 $tagType = 1; // close tag (e.g. "</span>")
3644 $tagType = 0; // open tag (e.g. "<span>")
3647 $bracketState = 2; // building tag name
3648 } elseif ( $bracketState == 2 ) {
3652 // Name found (e.g. "<a href=..."), add on tag attributes...
3653 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3655 } elseif ( $bracketState == 0 ) {
3656 if ( $entityState ) {
3659 $dispLen++
; // entity is one displayed char
3662 if ( $neLength == 0 && !$maybeState ) {
3663 // Save state without $ch. We want to *hit* the first
3664 // display char (to get tags) but not *use* it if truncating.
3665 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3668 $entityState = 1; // entity found, (e.g. " ")
3670 $dispLen++
; // this char is displayed
3671 // Add the next $max display text chars after this in one swoop...
3672 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3673 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3674 $dispLen +
= $skipped;
3680 // Close the last tag if left unclosed by bad HTML
3681 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3682 while ( count( $openTags ) > 0 ) {
3683 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3689 * truncateHtml() helper function
3690 * like strcspn() but adds the skipped chars to $ret
3692 * @param string $ret
3693 * @param string $text
3694 * @param string $search
3696 * @param null|int $len
3699 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3700 if ( $len === null ) {
3701 $len = -1; // -1 means "no limit" for strcspn
3702 } elseif ( $len < 0 ) {
3706 if ( $start < strlen( $text ) ) {
3707 $skipCount = strcspn( $text, $search, $start, $len );
3708 $ret .= substr( $text, $start, $skipCount );
3714 * truncateHtml() helper function
3715 * (a) push or pop $tag from $openTags as needed
3716 * (b) clear $tag value
3717 * @param string &$tag Current HTML tag name we are looking at
3718 * @param int $tagType (0-open tag, 1-close tag)
3719 * @param string $lastCh Character before the '>' that ended this tag
3720 * @param array &$openTags Open tag stack (not accounting for $tag)
3722 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3723 $tag = ltrim( $tag );
3725 if ( $tagType == 0 && $lastCh != '/' ) {
3726 $openTags[] = $tag; // tag opened (didn't close itself)
3727 } elseif ( $tagType == 1 ) {
3728 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3729 array_pop( $openTags ); // tag closed
3737 * Grammatical transformations, needed for inflected languages
3738 * Invoked by putting {{grammar:case|word}} in a message
3740 * @param string $word
3741 * @param string $case
3744 function convertGrammar( $word, $case ) {
3745 global $wgGrammarForms;
3746 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3747 return $wgGrammarForms[$this->getCode()][$case][$word];
3753 * Get the grammar forms for the content language
3754 * @return array Array of grammar forms
3757 function getGrammarForms() {
3758 global $wgGrammarForms;
3759 if ( isset( $wgGrammarForms[$this->getCode()] )
3760 && is_array( $wgGrammarForms[$this->getCode()] )
3762 return $wgGrammarForms[$this->getCode()];
3768 * Provides an alternative text depending on specified gender.
3769 * Usage {{gender:username|masculine|feminine|unknown}}.
3770 * username is optional, in which case the gender of current user is used,
3771 * but only in (some) interface messages; otherwise default gender is used.
3773 * If no forms are given, an empty string is returned. If only one form is
3774 * given, it will be returned unconditionally. These details are implied by
3775 * the caller and cannot be overridden in subclasses.
3777 * If three forms are given, the default is to use the third (unknown) form.
3778 * If fewer than three forms are given, the default is to use the first (masculine) form.
3779 * These details can be overridden in subclasses.
3781 * @param string $gender
3782 * @param array $forms
3786 function gender( $gender, $forms ) {
3787 if ( !count( $forms ) ) {
3790 $forms = $this->preConvertPlural( $forms, 2 );
3791 if ( $gender === 'male' ) {
3794 if ( $gender === 'female' ) {
3797 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3801 * Plural form transformations, needed for some languages.
3802 * For example, there are 3 form of plural in Russian and Polish,
3803 * depending on "count mod 10". See [[w:Plural]]
3804 * For English it is pretty simple.
3806 * Invoked by putting {{plural:count|wordform1|wordform2}}
3807 * or {{plural:count|wordform1|wordform2|wordform3}}
3809 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3811 * @param int $count Non-localized number
3812 * @param array $forms Different plural forms
3813 * @return string Correct form of plural for $count in this language
3815 function convertPlural( $count, $forms ) {
3816 // Handle explicit n=pluralform cases
3817 $forms = $this->handleExplicitPluralForms( $count, $forms );
3818 if ( is_string( $forms ) ) {
3821 if ( !count( $forms ) ) {
3825 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3826 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3827 return $forms[$pluralForm];
3831 * Handles explicit plural forms for Language::convertPlural()
3833 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3834 * If an explicitly defined plural form matches the $count, then
3835 * string value returned, otherwise array returned for further consideration
3836 * by CLDR rules or overridden convertPlural().
3840 * @param int $count Non-localized number
3841 * @param array $forms Different plural forms
3843 * @return array|string
3845 protected function handleExplicitPluralForms( $count, array $forms ) {
3846 foreach ( $forms as $index => $form ) {
3847 if ( preg_match( '/\d+=/i', $form ) ) {
3848 $pos = strpos( $form, '=' );
3849 if ( substr( $form, 0, $pos ) === (string)$count ) {
3850 return substr( $form, $pos +
1 );
3852 unset( $forms[$index] );
3855 return array_values( $forms );
3859 * Checks that convertPlural was given an array and pads it to requested
3860 * amount of forms by copying the last one.
3862 * @param array $forms Array of forms given to convertPlural
3863 * @param int $count How many forms should there be at least
3864 * @return array Padded array of forms or an exception if not an array
3866 protected function preConvertPlural( /* Array */ $forms, $count ) {
3867 while ( count( $forms ) < $count ) {
3868 $forms[] = $forms[count( $forms ) - 1];
3874 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3875 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3876 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3877 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3880 * @param string $str The validated block duration in English
3881 * @return string Somehow translated block duration
3882 * @see LanguageFi.php for example implementation
3884 function translateBlockExpiry( $str ) {
3885 $duration = SpecialBlock
::getSuggestedDurations( $this );
3886 foreach ( $duration as $show => $value ) {
3887 if ( strcmp( $str, $value ) == 0 ) {
3888 return htmlspecialchars( trim( $show ) );
3892 // Since usually only infinite or indefinite is only on list, so try
3893 // equivalents if still here.
3894 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3895 if ( in_array( $str, $indefs ) ) {
3896 foreach ( $indefs as $val ) {
3897 $show = array_search( $val, $duration, true );
3898 if ( $show !== false ) {
3899 return htmlspecialchars( trim( $show ) );
3904 // If all else fails, return a standard duration or timestamp description.
3905 $time = strtotime( $str, 0 );
3906 if ( $time === false ) { // Unknown format. Return it as-is in case.
3908 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3909 // $time is relative to 0 so it's a duration length.
3910 return $this->formatDuration( $time );
3911 } else { // It's an absolute timestamp.
3912 if ( $time === 0 ) {
3913 // wfTimestamp() handles 0 as current time instead of epoch.
3914 return $this->timeanddate( '19700101000000' );
3916 return $this->timeanddate( $time );
3922 * languages like Chinese need to be segmented in order for the diff
3925 * @param string $text
3928 public function segmentForDiff( $text ) {
3933 * and unsegment to show the result
3935 * @param string $text
3938 public function unsegmentForDiff( $text ) {
3943 * Return the LanguageConverter used in the Language
3946 * @return LanguageConverter
3948 public function getConverter() {
3949 return $this->mConverter
;
3953 * convert text to all supported variants
3955 * @param string $text
3958 public function autoConvertToAllVariants( $text ) {
3959 return $this->mConverter
->autoConvertToAllVariants( $text );
3963 * convert text to different variants of a language.
3965 * @param string $text
3968 public function convert( $text ) {
3969 return $this->mConverter
->convert( $text );
3973 * Convert a Title object to a string in the preferred variant
3975 * @param Title $title
3978 public function convertTitle( $title ) {
3979 return $this->mConverter
->convertTitle( $title );
3983 * Convert a namespace index to a string in the preferred variant
3988 public function convertNamespace( $ns ) {
3989 return $this->mConverter
->convertNamespace( $ns );
3993 * Check if this is a language with variants
3997 public function hasVariants() {
3998 return count( $this->getVariants() ) > 1;
4002 * Check if the language has the specific variant
4005 * @param string $variant
4008 public function hasVariant( $variant ) {
4009 return (bool)$this->mConverter
->validateVariant( $variant );
4013 * Put custom tags (e.g. -{ }-) around math to prevent conversion
4015 * @param string $text
4017 * @deprecated since 1.22 is no longer used
4019 public function armourMath( $text ) {
4020 return $this->mConverter
->armourMath( $text );
4024 * Perform output conversion on a string, and encode for safe HTML output.
4025 * @param string $text Text to be converted
4026 * @param bool $isTitle Whether this conversion is for the article title
4028 * @todo this should get integrated somewhere sane
4030 public function convertHtml( $text, $isTitle = false ) {
4031 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4035 * @param string $key
4038 public function convertCategoryKey( $key ) {
4039 return $this->mConverter
->convertCategoryKey( $key );
4043 * Get the list of variants supported by this language
4044 * see sample implementation in LanguageZh.php
4046 * @return array An array of language codes
4048 public function getVariants() {
4049 return $this->mConverter
->getVariants();
4055 public function getPreferredVariant() {
4056 return $this->mConverter
->getPreferredVariant();
4062 public function getDefaultVariant() {
4063 return $this->mConverter
->getDefaultVariant();
4069 public function getURLVariant() {
4070 return $this->mConverter
->getURLVariant();
4074 * If a language supports multiple variants, it is
4075 * possible that non-existing link in one variant
4076 * actually exists in another variant. this function
4077 * tries to find it. See e.g. LanguageZh.php
4078 * The input parameters may be modified upon return
4080 * @param string &$link The name of the link
4081 * @param Title &$nt The title object of the link
4082 * @param bool $ignoreOtherCond To disable other conditions when
4083 * we need to transclude a template or update a category's link
4085 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4086 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4090 * returns language specific options used by User::getPageRenderHash()
4091 * for example, the preferred language variant
4095 function getExtraHashOptions() {
4096 return $this->mConverter
->getExtraHashOptions();
4100 * For languages that support multiple variants, the title of an
4101 * article may be displayed differently in different variants. this
4102 * function returns the apporiate title defined in the body of the article.
4106 public function getParsedTitle() {
4107 return $this->mConverter
->getParsedTitle();
4111 * Prepare external link text for conversion. When the text is
4112 * a URL, it shouldn't be converted, and it'll be wrapped in
4113 * the "raw" tag (-{R| }-) to prevent conversion.
4115 * This function is called "markNoConversion" for historical
4118 * @param string $text Text to be used for external link
4119 * @param bool $noParse Wrap it without confirming it's a real URL first
4120 * @return string The tagged text
4122 public function markNoConversion( $text, $noParse = false ) {
4123 // Excluding protocal-relative URLs may avoid many false positives.
4124 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4125 return $this->mConverter
->markNoConversion( $text );
4132 * A regular expression to match legal word-trailing characters
4133 * which should be merged onto a link of the form [[foo]]bar.
4137 public function linkTrail() {
4138 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4142 * A regular expression character set to match legal word-prefixing
4143 * characters which should be merged onto a link of the form foo[[bar]].
4147 public function linkPrefixCharset() {
4148 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4152 * @deprecated since 1.24, will be removed in 1.25
4155 function getLangObj() {
4156 wfDeprecated( __METHOD__
, '1.24' );
4161 * Get the "parent" language which has a converter to convert a "compatible" language
4162 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4164 * @return Language|null
4167 public function getParentLanguage() {
4168 if ( $this->mParentLanguage
!== false ) {
4169 return $this->mParentLanguage
;
4172 $pieces = explode( '-', $this->getCode() );
4174 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4175 $this->mParentLanguage
= null;
4178 $lang = Language
::factory( $code );
4179 if ( !$lang->hasVariant( $this->getCode() ) ) {
4180 $this->mParentLanguage
= null;
4184 $this->mParentLanguage
= $lang;
4189 * Get the RFC 3066 code for this language object
4191 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4192 * htmlspecialchars() or similar
4196 public function getCode() {
4197 return $this->mCode
;
4201 * Get the code in Bcp47 format which we can use
4202 * inside of html lang="" tags.
4204 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4205 * htmlspecialchars() or similar.
4210 public function getHtmlCode() {
4211 if ( is_null( $this->mHtmlCode
) ) {
4212 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4214 return $this->mHtmlCode
;
4218 * @param string $code
4220 public function setCode( $code ) {
4221 $this->mCode
= $code;
4222 // Ensure we don't leave incorrect cached data lying around
4223 $this->mHtmlCode
= null;
4224 $this->mParentLanguage
= false;
4228 * Get the name of a file for a certain language code
4229 * @param string $prefix Prepend this to the filename
4230 * @param string $code Language code
4231 * @param string $suffix Append this to the filename
4232 * @throws MWException
4233 * @return string $prefix . $mangledCode . $suffix
4235 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4236 if ( !self
::isValidBuiltInCode( $code ) ) {
4237 throw new MWException( "Invalid language code \"$code\"" );
4240 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4244 * Get the language code from a file name. Inverse of getFileName()
4245 * @param string $filename $prefix . $languageCode . $suffix
4246 * @param string $prefix Prefix before the language code
4247 * @param string $suffix Suffix after the language code
4248 * @return string Language code, or false if $prefix or $suffix isn't found
4250 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4252 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4253 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4254 if ( !count( $m ) ) {
4257 return str_replace( '_', '-', strtolower( $m[1] ) );
4261 * @param string $code
4264 public static function getMessagesFileName( $code ) {
4266 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4267 Hooks
::run( 'Language::getMessagesFileName', array( $code, &$file ) );
4272 * @param string $code
4276 public static function getJsonMessagesFileName( $code ) {
4279 if ( !self
::isValidBuiltInCode( $code ) ) {
4280 throw new MWException( "Invalid language code \"$code\"" );
4283 return "$IP/languages/i18n/$code.json";
4287 * @param string $code
4290 public static function getClassFileName( $code ) {
4292 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4296 * Get the first fallback for a given language.
4298 * @param string $code
4300 * @return bool|string
4302 public static function getFallbackFor( $code ) {
4303 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4306 $fallbacks = self
::getFallbacksFor( $code );
4307 $first = array_shift( $fallbacks );
4313 * Get the ordered list of fallback languages.
4316 * @param string $code Language code
4319 public static function getFallbacksFor( $code ) {
4320 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4323 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4324 $v = array_map( 'trim', explode( ',', $v ) );
4325 if ( $v[count( $v ) - 1] !== 'en' ) {
4333 * Get the ordered list of fallback languages, ending with the fallback
4334 * language chain for the site language.
4337 * @param string $code Language code
4338 * @return array Array( fallbacks, site fallbacks )
4340 public static function getFallbacksIncludingSiteLanguage( $code ) {
4341 global $wgLanguageCode;
4343 // Usually, we will only store a tiny number of fallback chains, so we
4344 // keep them in static memory.
4345 $cacheKey = "{$code}-{$wgLanguageCode}";
4347 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4348 $fallbacks = self
::getFallbacksFor( $code );
4350 // Append the site's fallback chain, including the site language itself
4351 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4352 array_unshift( $siteFallbacks, $wgLanguageCode );
4354 // Eliminate any languages already included in the chain
4355 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4357 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4359 return self
::$fallbackLanguageCache[$cacheKey];
4363 * Get all messages for a given language
4364 * WARNING: this may take a long time. If you just need all message *keys*
4365 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4367 * @param string $code
4371 public static function getMessagesFor( $code ) {
4372 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4376 * Get a message for a given language
4378 * @param string $key
4379 * @param string $code
4383 public static function getMessageFor( $key, $code ) {
4384 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4388 * Get all message keys for a given language. This is a faster alternative to
4389 * array_keys( Language::getMessagesFor( $code ) )
4392 * @param string $code Language code
4393 * @return array Array of message keys (strings)
4395 public static function getMessageKeysFor( $code ) {
4396 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4400 * @param string $talk
4403 function fixVariableInNamespace( $talk ) {
4404 if ( strpos( $talk, '$1' ) === false ) {
4408 global $wgMetaNamespace;
4409 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4411 # Allow grammar transformations
4412 # Allowing full message-style parsing would make simple requests
4413 # such as action=raw much more expensive than they need to be.
4414 # This will hopefully cover most cases.
4415 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4416 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4417 return str_replace( ' ', '_', $talk );
4424 function replaceGrammarInNamespace( $m ) {
4425 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4429 * @throws MWException
4432 static function getCaseMaps() {
4433 static $wikiUpperChars, $wikiLowerChars;
4434 if ( isset( $wikiUpperChars ) ) {
4435 return array( $wikiUpperChars, $wikiLowerChars );
4438 wfProfileIn( __METHOD__
);
4439 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4440 if ( $arr === false ) {
4441 throw new MWException(
4442 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4444 $wikiUpperChars = $arr['wikiUpperChars'];
4445 $wikiLowerChars = $arr['wikiLowerChars'];
4446 wfProfileOut( __METHOD__
);
4447 return array( $wikiUpperChars, $wikiLowerChars );
4451 * Decode an expiry (block, protection, etc) which has come from the DB
4453 * @todo FIXME: why are we returnings DBMS-dependent strings???
4455 * @param string $expiry Database expiry String
4456 * @param bool|int $format True to process using language functions, or TS_ constant
4457 * to return the expiry in a given timestamp
4461 public function formatExpiry( $expiry, $format = true ) {
4463 if ( $infinity === null ) {
4464 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4467 if ( $expiry == '' ||
$expiry == $infinity ) {
4468 return $format === true
4469 ?
$this->getMessageFromDB( 'infiniteblock' )
4472 return $format === true
4473 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4474 : wfTimestamp( $format, $expiry );
4480 * @param int|float $seconds
4481 * @param array $format Optional
4482 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4483 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4484 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4486 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4487 * or 'avoidminutes'.
4490 function formatTimePeriod( $seconds, $format = array() ) {
4491 if ( !is_array( $format ) ) {
4492 $format = array( 'avoid' => $format ); // For backwards compatibility
4494 if ( !isset( $format['avoid'] ) ) {
4495 $format['avoid'] = false;
4497 if ( !isset( $format['noabbrevs'] ) ) {
4498 $format['noabbrevs'] = false;
4500 $secondsMsg = wfMessage(
4501 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4502 $minutesMsg = wfMessage(
4503 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4504 $hoursMsg = wfMessage(
4505 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4506 $daysMsg = wfMessage(
4507 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4509 if ( round( $seconds * 10 ) < 100 ) {
4510 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4511 $s = $secondsMsg->params( $s )->text();
4512 } elseif ( round( $seconds ) < 60 ) {
4513 $s = $this->formatNum( round( $seconds ) );
4514 $s = $secondsMsg->params( $s )->text();
4515 } elseif ( round( $seconds ) < 3600 ) {
4516 $minutes = floor( $seconds / 60 );
4517 $secondsPart = round( fmod( $seconds, 60 ) );
4518 if ( $secondsPart == 60 ) {
4522 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4524 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4525 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4526 $hours = floor( $seconds / 3600 );
4527 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4528 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4529 if ( $secondsPart == 60 ) {
4533 if ( $minutes == 60 ) {
4537 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4539 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4540 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4541 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4544 $days = floor( $seconds / 86400 );
4545 if ( $format['avoid'] === 'avoidminutes' ) {
4546 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4547 if ( $hours == 24 ) {
4551 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4553 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4554 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4555 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4556 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4557 if ( $minutes == 60 ) {
4561 if ( $hours == 24 ) {
4565 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4567 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4569 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4571 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4573 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4580 * Format a bitrate for output, using an appropriate
4581 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4582 * the magnitude in question.
4584 * This use base 1000. For base 1024 use formatSize(), for another base
4585 * see formatComputingNumbers().
4590 function formatBitrate( $bps ) {
4591 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4595 * @param int $size Size of the unit
4596 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4597 * @param string $messageKey Message key to be uesd
4600 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4602 return str_replace( '$1', $this->formatNum( $size ),
4603 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4606 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4609 $maxIndex = count( $sizes ) - 1;
4610 while ( $size >= $boundary && $index < $maxIndex ) {
4615 // For small sizes no decimal places necessary
4618 // For MB and bigger two decimal places are smarter
4621 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4623 $size = round( $size, $round );
4624 $text = $this->getMessageFromDB( $msg );
4625 return str_replace( '$1', $this->formatNum( $size ), $text );
4629 * Format a size in bytes for output, using an appropriate
4630 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4632 * This method use base 1024. For base 1000 use formatBitrate(), for
4633 * another base see formatComputingNumbers()
4635 * @param int $size Size to format
4636 * @return string Plain text (not HTML)
4638 function formatSize( $size ) {
4639 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4643 * Make a list item, used by various special pages
4645 * @param string $page Page link
4646 * @param string $details Text between brackets
4647 * @param bool $oppositedm Add the direction mark opposite to your
4648 * language, to display text properly
4651 function specialList( $page, $details, $oppositedm = true ) {
4652 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4653 $this->getDirMark();
4654 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4655 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4656 return $page . $details;
4660 * Generate (prev x| next x) (20|50|100...) type links for paging
4662 * @param Title $title Title object to link
4663 * @param int $offset
4665 * @param array $query Optional URL query parameter string
4666 * @param bool $atend Optional param for specified if this is the last page
4669 public function viewPrevNext( Title
$title, $offset, $limit,
4670 array $query = array(), $atend = false
4672 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4674 # Make 'previous' link
4675 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4676 if ( $offset > 0 ) {
4677 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4678 $query, $prev, 'prevn-title', 'mw-prevlink' );
4680 $plink = htmlspecialchars( $prev );
4684 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4686 $nlink = htmlspecialchars( $next );
4688 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4689 $query, $next, 'nextn-title', 'mw-nextlink' );
4692 # Make links to set number of items per page
4693 $numLinks = array();
4694 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4695 $numLinks[] = $this->numLink( $title, $offset, $num,
4696 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4699 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4700 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4704 * Helper function for viewPrevNext() that generates links
4706 * @param Title $title Title object to link
4707 * @param int $offset
4709 * @param array $query Extra query parameters
4710 * @param string $link Text to use for the link; will be escaped
4711 * @param string $tooltipMsg Name of the message to use as tooltip
4712 * @param string $class Value of the "class" attribute of the link
4713 * @return string HTML fragment
4715 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4718 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4719 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4720 ->numParams( $limit )->text();
4722 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4723 'title' => $tooltip, 'class' => $class ), $link );
4727 * Get the conversion rule title, if any.
4731 public function getConvRuleTitle() {
4732 return $this->mConverter
->getConvRuleTitle();
4736 * Get the compiled plural rules for the language
4738 * @return array Associative array with plural form, and plural rule as key-value pairs
4740 public function getCompiledPluralRules() {
4741 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4742 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4743 if ( !$pluralRules ) {
4744 foreach ( $fallbacks as $fallbackCode ) {
4745 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4746 if ( $pluralRules ) {
4751 return $pluralRules;
4755 * Get the plural rules for the language
4757 * @return array Associative array with plural form number and plural rule as key-value pairs
4759 public function getPluralRules() {
4760 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4761 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4762 if ( !$pluralRules ) {
4763 foreach ( $fallbacks as $fallbackCode ) {
4764 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4765 if ( $pluralRules ) {
4770 return $pluralRules;
4774 * Get the plural rule types for the language
4776 * @return array Associative array with plural form number and plural rule type as key-value pairs
4778 public function getPluralRuleTypes() {
4779 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4780 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4781 if ( !$pluralRuleTypes ) {
4782 foreach ( $fallbacks as $fallbackCode ) {
4783 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4784 if ( $pluralRuleTypes ) {
4789 return $pluralRuleTypes;
4793 * Find the index number of the plural rule appropriate for the given number
4794 * @param int $number
4795 * @return int The index number of the plural rule
4797 public function getPluralRuleIndexNumber( $number ) {
4798 $pluralRules = $this->getCompiledPluralRules();
4799 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4804 * Find the plural rule type appropriate for the given number
4805 * For example, if the language is set to Arabic, getPluralType(5) should
4808 * @param int $number
4809 * @return string The name of the plural rule type, e.g. one, two, few, many
4811 public function getPluralRuleType( $number ) {
4812 $index = $this->getPluralRuleIndexNumber( $number );
4813 $pluralRuleTypes = $this->getPluralRuleTypes();
4814 if ( isset( $pluralRuleTypes[$index] ) ) {
4815 return $pluralRuleTypes[$index];