3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
38 * Internationalisation code
43 * @var LanguageConverter
47 public $mVariants, $mCode, $mLoaded = false;
48 public $mMagicExtensions = array(), $mMagicHookDone = false;
49 private $mHtmlCode = null, $mParentLanguage = false;
51 public $dateFormatStrings = array();
52 public $mExtendedSpecialPageAliases;
54 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
57 * ReplacementArray object caches
59 public $transformData = array();
62 * @var LocalisationCache
64 static public $dataCache;
66 static public $mLangObjCache = array();
68 static public $mWeekdayMsgs = array(
69 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
73 static public $mWeekdayAbbrevMsgs = array(
74 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
77 static public $mMonthMsgs = array(
78 'january', 'february', 'march', 'april', 'may_long', 'june',
79 'july', 'august', 'september', 'october', 'november',
82 static public $mMonthGenMsgs = array(
83 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
84 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
87 static public $mMonthAbbrevMsgs = array(
88 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
89 'sep', 'oct', 'nov', 'dec'
92 static public $mIranianCalendarMonthMsgs = array(
93 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
94 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
95 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
96 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
99 static public $mHebrewCalendarMonthMsgs = array(
100 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
101 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
102 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
103 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
104 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
107 static public $mHebrewCalendarMonthGenMsgs = array(
108 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
109 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
110 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
111 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
112 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
115 static public $mHijriCalendarMonthMsgs = array(
116 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
117 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
118 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
119 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
126 static public $durationIntervals = array(
127 'millennia' => 31556952000,
128 'centuries' => 3155695200,
129 'decades' => 315569520,
130 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
139 * Cache for language fallbacks.
140 * @see Language::getFallbacksIncludingSiteLanguage
144 static private $fallbackLanguageCache = array();
147 * Get a cached or new language object for a given language code
148 * @param string $code
151 static function factory( $code ) {
152 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
154 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
155 $code = $wgDummyLanguageCodes[$code];
158 // get the language object to process
159 $langObj = isset( self
::$mLangObjCache[$code] )
160 ? self
::$mLangObjCache[$code]
161 : self
::newFromCode( $code );
163 // merge the language object in to get it up front in the cache
164 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
165 // get rid of the oldest ones in case we have an overflow
166 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
172 * Create a language object for a given language code
173 * @param string $code
174 * @throws MWException
177 protected static function newFromCode( $code ) {
178 // Protect against path traversal below
179 if ( !Language
::isValidCode( $code )
180 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code )
182 throw new MWException( "Invalid language code \"$code\"" );
185 if ( !Language
::isValidBuiltInCode( $code ) ) {
186 // It's not possible to customise this code with class files, so
187 // just return a Language object. This is to support uselang= hacks.
188 $lang = new Language
;
189 $lang->setCode( $code );
193 // Check if there is a language class for the code
194 $class = self
::classFromCode( $code );
195 self
::preloadLanguageClass( $class );
196 if ( class_exists( $class ) ) {
201 // Keep trying the fallback list until we find an existing class
202 $fallbacks = Language
::getFallbacksFor( $code );
203 foreach ( $fallbacks as $fallbackCode ) {
204 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
205 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
208 $class = self
::classFromCode( $fallbackCode );
209 self
::preloadLanguageClass( $class );
210 if ( class_exists( $class ) ) {
211 $lang = Language
::newFromCode( $fallbackCode );
212 $lang->setCode( $code );
217 throw new MWException( "Invalid fallback sequence for language '$code'" );
221 * Checks whether any localisation is available for that language tag
222 * in MediaWiki (MessagesXx.php exists).
224 * @param string $code Language tag (in lower case)
225 * @return bool Whether language is supported
228 public static function isSupportedLanguage( $code ) {
229 return self
::isValidBuiltInCode( $code )
230 && ( is_readable( self
::getMessagesFileName( $code ) )
231 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
236 * Returns true if a language code string is a well-formed language tag
237 * according to RFC 5646.
238 * This function only checks well-formedness; it doesn't check that
239 * language, script or variant codes actually exist in the repositories.
241 * Based on regexes by Mark Davis of the Unicode Consortium:
242 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
244 * @param string $code
245 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
250 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
253 $alphanum = '[a-z0-9]';
254 $x = 'x'; # private use singleton
255 $singleton = '[a-wy-z]'; # other singleton
256 $s = $lenient ?
'[-_]' : '-';
258 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
259 $script = "$alpha{4}"; # ISO 15924
260 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
261 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
262 $extension = "$singleton(?:$s$alphanum{2,8})+";
263 $privateUse = "$x(?:$s$alphanum{1,8})+";
265 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
266 # Since these are limited, this is safe even later changes to the registry --
267 # the only oddity is that it might change the type of the tag, and thus
268 # the results from the capturing groups.
269 # http://www.iana.org/assignments/language-subtag-registry
271 $grandfathered = "en{$s}GB{$s}oed"
272 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
273 . "|no{$s}(?:bok|nyn)"
274 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
275 . "|zh{$s}min{$s}nan";
277 $variantList = "$variant(?:$s$variant)*";
278 $extensionList = "$extension(?:$s$extension)*";
280 $langtag = "(?:($language)"
283 . "(?:$s$variantList)?"
284 . "(?:$s$extensionList)?"
285 . "(?:$s$privateUse)?)";
287 # The final breakdown, with capturing groups for each of these components
288 # The variants, extensions, grandfathered, and private-use may have interior '-'
290 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
292 return (bool)preg_match( "/$root/", strtolower( $code ) );
296 * Returns true if a language code string is of a valid form, whether or
297 * not it exists. This includes codes which are used solely for
298 * customisation via the MediaWiki namespace.
300 * @param string $code
304 public static function isValidCode( $code ) {
305 static $cache = array();
306 if ( isset( $cache[$code] ) ) {
307 return $cache[$code];
309 // People think language codes are html safe, so enforce it.
310 // Ideally we should only allow a-zA-Z0-9-
311 // but, .+ and other chars are often used for {{int:}} hacks
312 // see bugs 37564, 37587, 36938
314 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
315 && !preg_match( Title
::getTitleInvalidRegex(), $code );
317 return $cache[$code];
321 * Returns true if a language code is of a valid form for the purposes of
322 * internal customisation of MediaWiki, via Messages*.php or *.json.
324 * @param string $code
326 * @throws MWException
330 public static function isValidBuiltInCode( $code ) {
332 if ( !is_string( $code ) ) {
333 if ( is_object( $code ) ) {
334 $addmsg = " of class " . get_class( $code );
338 $type = gettype( $code );
339 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
342 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
346 * Returns true if a language code is an IETF tag known to MediaWiki.
348 * @param string $code
353 public static function isKnownLanguageTag( $tag ) {
354 static $coreLanguageNames;
356 // Quick escape for invalid input to avoid exceptions down the line
357 // when code tries to process tags which are not valid at all.
358 if ( !self
::isValidBuiltInCode( $tag ) ) {
362 if ( $coreLanguageNames === null ) {
364 include "$IP/languages/Names.php";
367 if ( isset( $coreLanguageNames[$tag] )
368 || self
::fetchLanguageName( $tag, $tag ) !== ''
377 * @param string $code
378 * @return string Name of the language class
380 public static function classFromCode( $code ) {
381 if ( $code == 'en' ) {
384 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
389 * Includes language class files
391 * @param string $class Name of the language class
393 public static function preloadLanguageClass( $class ) {
396 if ( $class === 'Language' ) {
400 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
401 include_once "$IP/languages/classes/$class.php";
406 * Get the LocalisationCache instance
408 * @return LocalisationCache
410 public static function getLocalisationCache() {
411 if ( is_null( self
::$dataCache ) ) {
412 global $wgLocalisationCacheConf;
413 $class = $wgLocalisationCacheConf['class'];
414 self
::$dataCache = new $class( $wgLocalisationCacheConf );
416 return self
::$dataCache;
419 function __construct() {
420 $this->mConverter
= new FakeConverter( $this );
421 // Set the code to the name of the descendant
422 if ( get_class( $this ) == 'Language' ) {
425 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
427 self
::getLocalisationCache();
431 * Reduce memory usage
433 function __destruct() {
434 foreach ( $this as $name => $value ) {
435 unset( $this->$name );
440 * Hook which will be called if this is the content language.
441 * Descendants can use this to register hook functions or modify globals
443 function initContLang() {
450 function getFallbackLanguages() {
451 return self
::getFallbacksFor( $this->mCode
);
455 * Exports $wgBookstoreListEn
458 function getBookstoreList() {
459 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
463 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
464 * available in localised form, it will be included in English.
468 public function getNamespaces() {
469 if ( is_null( $this->namespaceNames
) ) {
470 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
472 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
473 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
475 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
477 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
478 if ( $wgMetaNamespaceTalk ) {
479 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
481 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
482 $this->namespaceNames
[NS_PROJECT_TALK
] =
483 $this->fixVariableInNamespace( $talk );
486 # Sometimes a language will be localised but not actually exist on this wiki.
487 foreach ( $this->namespaceNames
as $key => $text ) {
488 if ( !isset( $validNamespaces[$key] ) ) {
489 unset( $this->namespaceNames
[$key] );
493 # The above mixing may leave namespaces out of canonical order.
494 # Re-order by namespace ID number...
495 ksort( $this->namespaceNames
);
497 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
500 return $this->namespaceNames
;
504 * Arbitrarily set all of the namespace names at once. Mainly used for testing
505 * @param array $namespaces Array of namespaces (id => name)
507 public function setNamespaces( array $namespaces ) {
508 $this->namespaceNames
= $namespaces;
509 $this->mNamespaceIds
= null;
513 * Resets all of the namespace caches. Mainly used for testing
515 public function resetNamespaces() {
516 $this->namespaceNames
= null;
517 $this->mNamespaceIds
= null;
518 $this->namespaceAliases
= null;
522 * A convenience function that returns the same thing as
523 * getNamespaces() except with the array values changed to ' '
524 * where it found '_', useful for producing output to be displayed
525 * e.g. in <select> forms.
529 function getFormattedNamespaces() {
530 $ns = $this->getNamespaces();
531 foreach ( $ns as $k => $v ) {
532 $ns[$k] = strtr( $v, '_', ' ' );
538 * Get a namespace value by key
540 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
541 * echo $mw_ns; // prints 'MediaWiki'
544 * @param int $index The array key of the namespace to return
545 * @return string|bool String if the namespace value exists, otherwise false
547 function getNsText( $index ) {
548 $ns = $this->getNamespaces();
550 return isset( $ns[$index] ) ?
$ns[$index] : false;
554 * A convenience function that returns the same thing as
555 * getNsText() except with '_' changed to ' ', useful for
559 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
560 * echo $mw_ns; // prints 'MediaWiki talk'
563 * @param int $index The array key of the namespace to return
564 * @return string Namespace name without underscores (empty string if namespace does not exist)
566 function getFormattedNsText( $index ) {
567 $ns = $this->getNsText( $index );
569 return strtr( $ns, '_', ' ' );
573 * Returns gender-dependent namespace alias if available.
574 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
575 * @param int $index Namespace index
576 * @param string $gender Gender key (male, female... )
580 function getGenderNsText( $index, $gender ) {
581 global $wgExtraGenderNamespaces;
583 $ns = $wgExtraGenderNamespaces +
584 self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
586 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
590 * Whether this language uses gender-dependent namespace aliases.
591 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
595 function needsGenderDistinction() {
596 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
597 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
598 // $wgExtraGenderNamespaces overrides everything
600 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
601 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
602 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
605 // Check what is in i18n files
606 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
607 return count( $aliases ) > 0;
612 * Get a namespace key by value, case insensitive.
613 * Only matches namespace names for the current language, not the
614 * canonical ones defined in Namespace.php.
616 * @param string $text
617 * @return int|bool An integer if $text is a valid value otherwise false
619 function getLocalNsIndex( $text ) {
620 $lctext = $this->lc( $text );
621 $ids = $this->getNamespaceIds();
622 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
628 function getNamespaceAliases() {
629 if ( is_null( $this->namespaceAliases
) ) {
630 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
634 foreach ( $aliases as $name => $index ) {
635 if ( $index === NS_PROJECT_TALK
) {
636 unset( $aliases[$name] );
637 $name = $this->fixVariableInNamespace( $name );
638 $aliases[$name] = $index;
643 global $wgExtraGenderNamespaces;
644 $genders = $wgExtraGenderNamespaces +
645 (array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
646 foreach ( $genders as $index => $forms ) {
647 foreach ( $forms as $alias ) {
648 $aliases[$alias] = $index;
652 # Also add converted namespace names as aliases, to avoid confusion.
653 $convertedNames = array();
654 foreach ( $this->getVariants() as $variant ) {
655 if ( $variant === $this->mCode
) {
658 foreach ( $this->getNamespaces() as $ns => $_ ) {
659 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
663 $this->namespaceAliases
= $aliases +
$convertedNames;
666 return $this->namespaceAliases
;
672 function getNamespaceIds() {
673 if ( is_null( $this->mNamespaceIds
) ) {
674 global $wgNamespaceAliases;
675 # Put namespace names and aliases into a hashtable.
676 # If this is too slow, then we should arrange it so that it is done
677 # before caching. The catch is that at pre-cache time, the above
678 # class-specific fixup hasn't been done.
679 $this->mNamespaceIds
= array();
680 foreach ( $this->getNamespaces() as $index => $name ) {
681 $this->mNamespaceIds
[$this->lc( $name )] = $index;
683 foreach ( $this->getNamespaceAliases() as $name => $index ) {
684 $this->mNamespaceIds
[$this->lc( $name )] = $index;
686 if ( $wgNamespaceAliases ) {
687 foreach ( $wgNamespaceAliases as $name => $index ) {
688 $this->mNamespaceIds
[$this->lc( $name )] = $index;
692 return $this->mNamespaceIds
;
696 * Get a namespace key by value, case insensitive. Canonical namespace
697 * names override custom ones defined for the current language.
699 * @param string $text
700 * @return int|bool An integer if $text is a valid value otherwise false
702 function getNsIndex( $text ) {
703 $lctext = $this->lc( $text );
704 $ns = MWNamespace
::getCanonicalIndex( $lctext );
705 if ( $ns !== null ) {
708 $ids = $this->getNamespaceIds();
709 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
713 * short names for language variants used for language conversion links.
715 * @param string $code
716 * @param bool $usemsg Use the "variantname-xyz" message if it exists
719 function getVariantname( $code, $usemsg = true ) {
720 $msg = "variantname-$code";
721 if ( $usemsg && wfMessage( $msg )->exists() ) {
722 return $this->getMessageFromDB( $msg );
724 $name = self
::fetchLanguageName( $code );
726 return $name; # if it's defined as a language name, show that
728 # otherwise, output the language code
734 * @param string $name
737 function specialPage( $name ) {
738 $aliases = $this->getSpecialPageAliases();
739 if ( isset( $aliases[$name][0] ) ) {
740 $name = $aliases[$name][0];
742 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
748 function getDatePreferences() {
749 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
755 function getDateFormats() {
756 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
760 * @return array|string
762 function getDefaultDateFormat() {
763 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
764 if ( $df === 'dmy or mdy' ) {
765 global $wgAmericanDates;
766 return $wgAmericanDates ?
'mdy' : 'dmy';
775 function getDatePreferenceMigrationMap() {
776 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
780 * @param string $image
783 function getImageFile( $image ) {
784 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
790 function getExtraUserToggles() {
791 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
798 function getUserToggle( $tog ) {
799 return $this->getMessageFromDB( "tog-$tog" );
803 * Get native language names, indexed by code.
804 * Only those defined in MediaWiki, no other data like CLDR.
805 * If $customisedOnly is true, only returns codes with a messages file
807 * @param bool $customisedOnly
810 * @deprecated since 1.20, use fetchLanguageNames()
812 public static function getLanguageNames( $customisedOnly = false ) {
813 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
817 * Get translated language names. This is done on best effort and
818 * by default this is exactly the same as Language::getLanguageNames.
819 * The CLDR extension provides translated names.
820 * @param string $code Language code.
821 * @return array Language code => language name
823 * @deprecated since 1.20, use fetchLanguageNames()
825 public static function getTranslatedLanguageNames( $code ) {
826 return self
::fetchLanguageNames( $code, 'all' );
830 * Get an array of language names, indexed by code.
831 * @param null|string $inLanguage Code of language in which to return the names
832 * Use null for autonyms (native names)
833 * @param string $include One of:
834 * 'all' all available languages
835 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
836 * 'mwfile' only if the language is in 'mw' *and* has a message file
837 * @return array Language code => language name
840 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
841 global $wgExtraLanguageNames;
842 static $coreLanguageNames;
844 if ( $coreLanguageNames === null ) {
846 include "$IP/languages/Names.php";
852 # TODO: also include when $inLanguage is null, when this code is more efficient
853 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
856 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
857 foreach ( $mwNames as $mwCode => $mwName ) {
858 # - Prefer own MediaWiki native name when not using the hook
859 # - For other names just add if not added through the hook
860 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
861 $names[$mwCode] = $mwName;
865 if ( $include === 'all' ) {
870 $coreCodes = array_keys( $mwNames );
871 foreach ( $coreCodes as $coreCode ) {
872 $returnMw[$coreCode] = $names[$coreCode];
875 if ( $include === 'mwfile' ) {
876 $namesMwFile = array();
877 # We do this using a foreach over the codes instead of a directory
878 # loop so that messages files in extensions will work correctly.
879 foreach ( $returnMw as $code => $value ) {
880 if ( is_readable( self
::getMessagesFileName( $code ) )
881 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
883 $namesMwFile[$code] = $names[$code];
890 # 'mw' option; default if it's not one of the other two options (all/mwfile)
895 * @param string $code The code of the language for which to get the name
896 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
897 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
898 * @return string Language name or empty
901 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
902 $code = strtolower( $code );
903 $array = self
::fetchLanguageNames( $inLanguage, $include );
904 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
908 * Get a message from the MediaWiki namespace.
910 * @param string $msg Message name
913 function getMessageFromDB( $msg ) {
914 return wfMessage( $msg )->inLanguage( $this )->text();
918 * Get the native language name of $code.
919 * Only if defined in MediaWiki, no other data like CLDR.
920 * @param string $code
922 * @deprecated since 1.20, use fetchLanguageName()
924 function getLanguageName( $code ) {
925 return self
::fetchLanguageName( $code );
932 function getMonthName( $key ) {
933 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
939 function getMonthNamesArray() {
940 $monthNames = array( '' );
941 for ( $i = 1; $i < 13; $i++
) {
942 $monthNames[] = $this->getMonthName( $i );
951 function getMonthNameGen( $key ) {
952 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
959 function getMonthAbbreviation( $key ) {
960 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
966 function getMonthAbbreviationsArray() {
967 $monthNames = array( '' );
968 for ( $i = 1; $i < 13; $i++
) {
969 $monthNames[] = $this->getMonthAbbreviation( $i );
978 function getWeekdayName( $key ) {
979 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
986 function getWeekdayAbbreviation( $key ) {
987 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
994 function getIranianCalendarMonthName( $key ) {
995 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1002 function getHebrewCalendarMonthName( $key ) {
1003 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1007 * @param string $key
1010 function getHebrewCalendarMonthNameGen( $key ) {
1011 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1015 * @param string $key
1018 function getHijriCalendarMonthName( $key ) {
1019 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1023 * Pass through result from $dateTimeObj->format()
1025 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1026 if ( !$dateTimeObj ) {
1027 $dateTimeObj = DateTime
::createFromFormat(
1028 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1031 return $dateTimeObj->format( $code );
1035 * This is a workalike of PHP's date() function, but with better
1036 * internationalisation, a reduced set of format characters, and a better
1039 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1040 * the PHP manual for definitions. There are a number of extensions, which
1043 * xn Do not translate digits of the next numeric format character
1044 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1045 * xr Use roman numerals for the next numeric format character
1046 * xh Use hebrew numerals for the next numeric format character
1048 * xg Genitive month name
1050 * xij j (day number) in Iranian calendar
1051 * xiF F (month name) in Iranian calendar
1052 * xin n (month number) in Iranian calendar
1053 * xiy y (two digit year) in Iranian calendar
1054 * xiY Y (full year) in Iranian calendar
1056 * xjj j (day number) in Hebrew calendar
1057 * xjF F (month name) in Hebrew calendar
1058 * xjt t (days in month) in Hebrew calendar
1059 * xjx xg (genitive month name) in Hebrew calendar
1060 * xjn n (month number) in Hebrew calendar
1061 * xjY Y (full year) in Hebrew calendar
1063 * xmj j (day number) in Hijri calendar
1064 * xmF F (month name) in Hijri calendar
1065 * xmn n (month number) in Hijri calendar
1066 * xmY Y (full year) in Hijri calendar
1068 * xkY Y (full year) in Thai solar calendar. Months and days are
1069 * identical to the Gregorian calendar
1070 * xoY Y (full year) in Minguo calendar or Juche year.
1071 * Months and days are identical to the
1072 * Gregorian calendar
1073 * xtY Y (full year) in Japanese nengo. Months and days are
1074 * identical to the Gregorian calendar
1076 * Characters enclosed in double quotes will be considered literal (with
1077 * the quotes themselves removed). Unmatched quotes will be considered
1078 * literal quotes. Example:
1080 * "The month is" F => The month is January
1083 * Backslash escaping is also supported.
1085 * Input timestamp is assumed to be pre-normalized to the desired local
1086 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1087 * $ts is UTC if $zone is not given.
1089 * @param string $format
1090 * @param string $ts 14-character timestamp
1093 * @param DateTimeZone $zone Timezone of $ts
1094 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1095 * Only makes sense if $ts is the current time.
1096 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1098 * @throws MWException
1101 function sprintfDate( $format, $ts, DateTimeZone
$zone = null, &$ttl = null ) {
1106 $dateTimeObj = false;
1115 $usedSecond = false;
1116 $usedMinute = false;
1123 $usedISOYear = false;
1124 $usedIsLeapYear = false;
1126 $usedHebrewMonth = false;
1127 $usedIranianMonth = false;
1128 $usedHijriMonth = false;
1129 $usedHebrewYear = false;
1130 $usedIranianYear = false;
1131 $usedHijriYear = false;
1132 $usedTennoYear = false;
1134 if ( strlen( $ts ) !== 14 ) {
1135 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1138 if ( !ctype_digit( $ts ) ) {
1139 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1142 $formatLength = strlen( $format );
1143 for ( $p = 0; $p < $formatLength; $p++
) {
1145 $code = $format[$p];
1146 if ( $code == 'x' && $p < $formatLength - 1 ) {
1147 $code .= $format[++
$p];
1150 if ( ( $code === 'xi'
1156 && $p < $formatLength - 1 ) {
1157 $code .= $format[++
$p];
1168 $rawToggle = !$rawToggle;
1178 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1181 $usedHebrewMonth = true;
1183 $hebrew = self
::tsToHebrew( $ts );
1185 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1189 $num = substr( $ts, 6, 2 );
1193 $s .= $this->getWeekdayAbbreviation( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1197 $num = intval( substr( $ts, 6, 2 ) );
1202 $iranian = self
::tsToIranian( $ts );
1209 $hijri = self
::tsToHijri( $ts );
1216 $hebrew = self
::tsToHebrew( $ts );
1222 $s .= $this->getWeekdayName( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) +
1 );
1226 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1229 $usedIranianMonth = true;
1231 $iranian = self
::tsToIranian( $ts );
1233 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1236 $usedHijriMonth = true;
1238 $hijri = self
::tsToHijri( $ts );
1240 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1243 $usedHebrewMonth = true;
1245 $hebrew = self
::tsToHebrew( $ts );
1247 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1251 $num = substr( $ts, 4, 2 );
1255 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1259 $num = intval( substr( $ts, 4, 2 ) );
1262 $usedIranianMonth = true;
1264 $iranian = self
::tsToIranian( $ts );
1269 $usedHijriMonth = true;
1271 $hijri = self
::tsToHijri ( $ts );
1276 $usedHebrewMonth = true;
1278 $hebrew = self
::tsToHebrew( $ts );
1283 $usedHebrewMonth = true;
1285 $hebrew = self
::tsToHebrew( $ts );
1291 $num = substr( $ts, 0, 4 );
1294 $usedIranianYear = true;
1296 $iranian = self
::tsToIranian( $ts );
1301 $usedHijriYear = true;
1303 $hijri = self
::tsToHijri( $ts );
1308 $usedHebrewYear = true;
1310 $hebrew = self
::tsToHebrew( $ts );
1317 $thai = self
::tsToYear( $ts, 'thai' );
1324 $minguo = self
::tsToYear( $ts, 'minguo' );
1329 $usedTennoYear = true;
1331 $tenno = self
::tsToYear( $ts, 'tenno' );
1337 $num = substr( $ts, 2, 2 );
1340 $usedIranianYear = true;
1342 $iranian = self
::tsToIranian( $ts );
1344 $num = substr( $iranian[0], -2 );
1348 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1352 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1356 $h = substr( $ts, 8, 2 );
1357 $num = $h %
12 ?
$h %
12 : 12;
1361 $num = intval( substr( $ts, 8, 2 ) );
1365 $h = substr( $ts, 8, 2 );
1366 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1370 $num = substr( $ts, 8, 2 );
1374 $num = substr( $ts, 10, 2 );
1378 $num = substr( $ts, 12, 2 );
1388 $s .= Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1394 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1398 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1402 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1405 $usedIsLeapYear = true;
1406 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1409 $usedISOYear = true;
1410 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1417 $num = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1420 # Backslash escaping
1421 if ( $p < $formatLength - 1 ) {
1422 $s .= $format[++
$p];
1429 if ( $p < $formatLength - 1 ) {
1430 $endQuote = strpos( $format, '"', $p +
1 );
1431 if ( $endQuote === false ) {
1432 # No terminating quote, assume literal "
1435 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1439 # Quote at end of string, assume literal "
1446 if ( $num !== false ) {
1447 if ( $rawToggle ||
$raw ) {
1450 } elseif ( $roman ) {
1451 $s .= Language
::romanNumeral( $num );
1453 } elseif ( $hebrewNum ) {
1454 $s .= self
::hebrewNumeral( $num );
1457 $s .= $this->formatNum( $num, true );
1462 if ( $usedSecond ) {
1464 } elseif ( $usedMinute ) {
1465 $ttl = 60 - substr( $ts, 12, 2 );
1466 } elseif ( $usedHour ) {
1467 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1468 } elseif ( $usedAMPM ) {
1469 $ttl = 43200 - ( substr( $ts, 8, 2 ) %
12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1470 } elseif ( $usedDay ||
$usedHebrewMonth ||
$usedIranianMonth ||
$usedHijriMonth ||
$usedHebrewYear ||
$usedIranianYear ||
$usedHijriYear ||
$usedTennoYear ) {
1471 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1472 // so that they don't need purged every day.
1473 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1475 $possibleTtls = array();
1476 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1478 $possibleTtls[] = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1479 } elseif ( $usedISOYear ) {
1480 // December 28th falls on the last ISO week of the year, every year.
1481 // The last ISO week of a year can be 52 or 53.
1482 $lastWeekOfISOYear = DateTime
::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?
: new DateTimeZone( 'UTC' ) )->format( 'W' );
1483 $currentISOWeek = Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1484 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1485 $timeRemainingInWeek = ( 7 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
$timeRemainingInDay;
1486 $possibleTtls[] = $weeksRemaining * 604800 +
$timeRemainingInWeek;
1490 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 +
$timeRemainingInDay;
1491 } elseif ( $usedYear ) {
1492 $possibleTtls[] = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1493 +
$timeRemainingInDay;
1494 } elseif ( $usedIsLeapYear ) {
1495 $year = substr( $ts, 0, 4 );
1496 $timeRemainingInYear = ( Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) +
364 - Language
::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1497 +
$timeRemainingInDay;
1499 if ( $mod ||
( !( $year %
100 ) && $year %
400 ) ) {
1500 // this isn't a leap year. see when the next one starts
1501 $nextCandidate = $year - $mod +
4;
1502 if ( $nextCandidate %
100 ||
!( $nextCandidate %
400 ) ) {
1503 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
$timeRemainingInYear;
1505 $possibleTtls[] = ( $nextCandidate - $year +
3 ) * 365 * 86400 +
$timeRemainingInYear;
1508 // this is a leap year, so the next year isn't
1509 $possibleTtls[] = $timeRemainingInYear;
1513 if ( $possibleTtls ) {
1514 $ttl = min( $possibleTtls );
1521 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1522 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1525 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1526 * Gregorian dates to Iranian dates. Originally written in C, it
1527 * is released under the terms of GNU Lesser General Public
1528 * License. Conversion to PHP was performed by Niklas Laxström.
1530 * Link: http://www.farsiweb.info/jalali/jalali.c
1536 private static function tsToIranian( $ts ) {
1537 $gy = substr( $ts, 0, 4 ) -1600;
1538 $gm = substr( $ts, 4, 2 ) -1;
1539 $gd = substr( $ts, 6, 2 ) -1;
1541 # Days passed from the beginning (including leap years)
1543 +
floor( ( $gy +
3 ) / 4 )
1544 - floor( ( $gy +
99 ) / 100 )
1545 +
floor( ( $gy +
399 ) / 400 );
1547 // Add days of the past months of this year
1548 for ( $i = 0; $i < $gm; $i++
) {
1549 $gDayNo +
= self
::$GREG_DAYS[$i];
1553 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1557 // Days passed in current month
1558 $gDayNo +
= (int)$gd;
1560 $jDayNo = $gDayNo - 79;
1562 $jNp = floor( $jDayNo / 12053 );
1565 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1568 if ( $jDayNo >= 366 ) {
1569 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1570 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1573 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1574 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1580 return array( $jy, $jm, $jd );
1584 * Converting Gregorian dates to Hijri dates.
1586 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1588 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1594 private static function tsToHijri( $ts ) {
1595 $year = substr( $ts, 0, 4 );
1596 $month = substr( $ts, 4, 2 );
1597 $day = substr( $ts, 6, 2 );
1605 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1606 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1608 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1609 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1610 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1613 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1614 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1617 $zl = $zjd -1948440 +
10632;
1618 $zn = (int)( ( $zl - 1 ) / 10631 );
1619 $zl = $zl - 10631 * $zn +
354;
1620 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1621 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1622 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1623 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1624 $zm = (int)( ( 24 * $zl ) / 709 );
1625 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1626 $zy = 30 * $zn +
$zj - 30;
1628 return array( $zy, $zm, $zd );
1632 * Converting Gregorian dates to Hebrew dates.
1634 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1635 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1636 * to translate the relevant functions into PHP and release them under
1639 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1640 * and Adar II is 14. In a non-leap year, Adar is 6.
1646 private static function tsToHebrew( $ts ) {
1648 $year = substr( $ts, 0, 4 );
1649 $month = substr( $ts, 4, 2 );
1650 $day = substr( $ts, 6, 2 );
1652 # Calculate Hebrew year
1653 $hebrewYear = $year +
3760;
1655 # Month number when September = 1, August = 12
1657 if ( $month > 12 ) {
1664 # Calculate day of year from 1 September
1666 for ( $i = 1; $i < $month; $i++
) {
1670 # Check if the year is leap
1671 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1674 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1681 # Calculate the start of the Hebrew year
1682 $start = self
::hebrewYearStart( $hebrewYear );
1684 # Calculate next year's start
1685 if ( $dayOfYear <= $start ) {
1686 # Day is before the start of the year - it is the previous year
1688 $nextStart = $start;
1692 # Add days since previous year's 1 September
1694 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1698 # Start of the new (previous) year
1699 $start = self
::hebrewYearStart( $hebrewYear );
1702 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1705 # Calculate Hebrew day of year
1706 $hebrewDayOfYear = $dayOfYear - $start;
1708 # Difference between year's days
1709 $diff = $nextStart - $start;
1710 # Add 12 (or 13 for leap years) days to ignore the difference between
1711 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1712 # difference is only about the year type
1713 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1719 # Check the year pattern, and is leap year
1720 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1721 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1722 # and non-leap years
1723 $yearPattern = $diff %
30;
1724 # Check if leap year
1725 $isLeap = $diff >= 30;
1727 # Calculate day in the month from number of day in the Hebrew year
1728 # Don't check Adar - if the day is not in Adar, we will stop before;
1729 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1730 $hebrewDay = $hebrewDayOfYear;
1733 while ( $hebrewMonth <= 12 ) {
1734 # Calculate days in this month
1735 if ( $isLeap && $hebrewMonth == 6 ) {
1736 # Adar in a leap year
1738 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1740 if ( $hebrewDay <= $days ) {
1744 # Subtract the days of Adar I
1745 $hebrewDay -= $days;
1748 if ( $hebrewDay <= $days ) {
1754 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1755 # Cheshvan in a complete year (otherwise as the rule below)
1757 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1758 # Kislev in an incomplete year (otherwise as the rule below)
1761 # Odd months have 30 days, even have 29
1762 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1764 if ( $hebrewDay <= $days ) {
1765 # In the current month
1768 # Subtract the days of the current month
1769 $hebrewDay -= $days;
1770 # Try in the next month
1775 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1779 * This calculates the Hebrew year start, as days since 1 September.
1780 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1781 * Used for Hebrew date.
1787 private static function hebrewYearStart( $year ) {
1788 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1789 $b = intval( ( $year - 1 ) %
4 );
1790 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1794 $Mar = intval( $m );
1800 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1801 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1803 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1805 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1809 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1814 * Algorithm to convert Gregorian dates to Thai solar dates,
1815 * Minguo dates or Minguo dates.
1817 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1818 * http://en.wikipedia.org/wiki/Minguo_calendar
1819 * http://en.wikipedia.org/wiki/Japanese_era_name
1821 * @param string $ts 14-character timestamp
1822 * @param string $cName Calender name
1823 * @return array Converted year, month, day
1825 private static function tsToYear( $ts, $cName ) {
1826 $gy = substr( $ts, 0, 4 );
1827 $gm = substr( $ts, 4, 2 );
1828 $gd = substr( $ts, 6, 2 );
1830 if ( !strcmp( $cName, 'thai' ) ) {
1832 # Add 543 years to the Gregorian calendar
1833 # Months and days are identical
1834 $gy_offset = $gy +
543;
1835 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1837 # Deduct 1911 years from the Gregorian calendar
1838 # Months and days are identical
1839 $gy_offset = $gy - 1911;
1840 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1841 # Nengō dates up to Meiji period
1842 # Deduct years from the Gregorian calendar
1843 # depending on the nengo periods
1844 # Months and days are identical
1846 ||
( ( $gy == 1912 ) && ( $gm < 7 ) )
1847 ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1850 $gy_gannen = $gy - 1868 +
1;
1851 $gy_offset = $gy_gannen;
1852 if ( $gy_gannen == 1 ) {
1855 $gy_offset = '明治' . $gy_offset;
1857 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1858 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1859 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1860 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1861 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1864 $gy_gannen = $gy - 1912 +
1;
1865 $gy_offset = $gy_gannen;
1866 if ( $gy_gannen == 1 ) {
1869 $gy_offset = '大正' . $gy_offset;
1871 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1872 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1873 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1876 $gy_gannen = $gy - 1926 +
1;
1877 $gy_offset = $gy_gannen;
1878 if ( $gy_gannen == 1 ) {
1881 $gy_offset = '昭和' . $gy_offset;
1884 $gy_gannen = $gy - 1989 +
1;
1885 $gy_offset = $gy_gannen;
1886 if ( $gy_gannen == 1 ) {
1889 $gy_offset = '平成' . $gy_offset;
1895 return array( $gy_offset, $gm, $gd );
1899 * Roman number formatting up to 10000
1905 static function romanNumeral( $num ) {
1906 static $table = array(
1907 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1908 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1909 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1910 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1911 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1914 $num = intval( $num );
1915 if ( $num > 10000 ||
$num <= 0 ) {
1920 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1921 if ( $num >= $pow10 ) {
1922 $s .= $table[$i][(int)floor( $num / $pow10 )];
1924 $num = $num %
$pow10;
1930 * Hebrew Gematria number formatting up to 9999
1936 static function hebrewNumeral( $num ) {
1937 static $table = array(
1938 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1939 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1940 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1941 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1944 $num = intval( $num );
1945 if ( $num > 9999 ||
$num <= 0 ) {
1950 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1951 if ( $num >= $pow10 ) {
1952 if ( $num == 15 ||
$num == 16 ) {
1953 $s .= $table[0][9] . $table[0][$num - 9];
1956 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1957 if ( $pow10 == 1000 ) {
1962 $num = $num %
$pow10;
1964 if ( strlen( $s ) == 2 ) {
1967 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1968 $str .= substr( $s, strlen( $s ) - 2, 2 );
1970 $start = substr( $str, 0, strlen( $str ) - 2 );
1971 $end = substr( $str, strlen( $str ) - 2 );
1974 $str = $start . 'ך';
1977 $str = $start . 'ם';
1980 $str = $start . 'ן';
1983 $str = $start . 'ף';
1986 $str = $start . 'ץ';
1993 * Used by date() and time() to adjust the time output.
1995 * @param string $ts The time in date('YmdHis') format
1996 * @param mixed $tz Adjust the time by this amount (default false, mean we
1997 * get user timecorrection setting)
2000 function userAdjust( $ts, $tz = false ) {
2001 global $wgUser, $wgLocalTZoffset;
2003 if ( $tz === false ) {
2004 $tz = $wgUser->getOption( 'timecorrection' );
2007 $data = explode( '|', $tz, 3 );
2009 if ( $data[0] == 'ZoneInfo' ) {
2010 wfSuppressWarnings();
2011 $userTZ = timezone_open( $data[2] );
2012 wfRestoreWarnings();
2013 if ( $userTZ !== false ) {
2014 $date = date_create( $ts, timezone_open( 'UTC' ) );
2015 date_timezone_set( $date, $userTZ );
2016 $date = date_format( $date, 'YmdHis' );
2019 # Unrecognized timezone, default to 'Offset' with the stored offset.
2020 $data[0] = 'Offset';
2023 if ( $data[0] == 'System' ||
$tz == '' ) {
2024 # Global offset in minutes.
2025 $minDiff = $wgLocalTZoffset;
2026 } elseif ( $data[0] == 'Offset' ) {
2027 $minDiff = intval( $data[1] );
2029 $data = explode( ':', $tz );
2030 if ( count( $data ) == 2 ) {
2031 $data[0] = intval( $data[0] );
2032 $data[1] = intval( $data[1] );
2033 $minDiff = abs( $data[0] ) * 60 +
$data[1];
2034 if ( $data[0] < 0 ) {
2035 $minDiff = -$minDiff;
2038 $minDiff = intval( $data[0] ) * 60;
2042 # No difference ? Return time unchanged
2043 if ( 0 == $minDiff ) {
2047 wfSuppressWarnings(); // E_STRICT system time bitching
2048 # Generate an adjusted date; take advantage of the fact that mktime
2049 # will normalize out-of-range values so we don't have to split $minDiff
2050 # into hours and minutes.
2052 (int)substr( $ts, 8, 2 ) ), # Hours
2053 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
2054 (int)substr( $ts, 12, 2 ), # Seconds
2055 (int)substr( $ts, 4, 2 ), # Month
2056 (int)substr( $ts, 6, 2 ), # Day
2057 (int)substr( $ts, 0, 4 ) ); # Year
2059 $date = date( 'YmdHis', $t );
2060 wfRestoreWarnings();
2066 * This is meant to be used by time(), date(), and timeanddate() to get
2067 * the date preference they're supposed to use, it should be used in
2071 * function timeanddate([...], $format = true) {
2072 * $datePreference = $this->dateFormat($format);
2077 * @param int|string|bool $usePrefs If true, the user's preference is used
2078 * if false, the site/language default is used
2079 * if int/string, assumed to be a format.
2082 function dateFormat( $usePrefs = true ) {
2085 if ( is_bool( $usePrefs ) ) {
2087 $datePreference = $wgUser->getDatePreference();
2089 $datePreference = (string)User
::getDefaultOption( 'date' );
2092 $datePreference = (string)$usePrefs;
2096 if ( $datePreference == '' ) {
2100 return $datePreference;
2104 * Get a format string for a given type and preference
2105 * @param string $type May be date, time or both
2106 * @param string $pref The format name as it appears in Messages*.php
2108 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2112 function getDateFormatString( $type, $pref ) {
2113 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2114 if ( $pref == 'default' ) {
2115 $pref = $this->getDefaultDateFormat();
2116 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2118 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2120 if ( $type === 'pretty' && $df === null ) {
2121 $df = $this->getDateFormatString( 'date', $pref );
2124 if ( $df === null ) {
2125 $pref = $this->getDefaultDateFormat();
2126 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2129 $this->dateFormatStrings
[$type][$pref] = $df;
2131 return $this->dateFormatStrings
[$type][$pref];
2135 * @param string $ts The time format which needs to be turned into a
2136 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2137 * @param bool $adj Whether to adjust the time output according to the
2138 * user configured offset ($timecorrection)
2139 * @param mixed $format True to use user's date format preference
2140 * @param string|bool $timecorrection The time offset as returned by
2141 * validateTimeZone() in Special:Preferences
2144 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2145 $ts = wfTimestamp( TS_MW
, $ts );
2147 $ts = $this->userAdjust( $ts, $timecorrection );
2149 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2150 return $this->sprintfDate( $df, $ts );
2154 * @param string $ts The time format which needs to be turned into a
2155 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2156 * @param bool $adj Whether to adjust the time output according to the
2157 * user configured offset ($timecorrection)
2158 * @param mixed $format True to use user's date format preference
2159 * @param string|bool $timecorrection The time offset as returned by
2160 * validateTimeZone() in Special:Preferences
2163 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2164 $ts = wfTimestamp( TS_MW
, $ts );
2166 $ts = $this->userAdjust( $ts, $timecorrection );
2168 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2169 return $this->sprintfDate( $df, $ts );
2173 * @param string $ts The time format which needs to be turned into a
2174 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2175 * @param bool $adj Whether to adjust the time output according to the
2176 * user configured offset ($timecorrection)
2177 * @param mixed $format What format to return, if it's false output the
2178 * default one (default true)
2179 * @param string|bool $timecorrection The time offset as returned by
2180 * validateTimeZone() in Special:Preferences
2183 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2184 $ts = wfTimestamp( TS_MW
, $ts );
2186 $ts = $this->userAdjust( $ts, $timecorrection );
2188 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2189 return $this->sprintfDate( $df, $ts );
2193 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2197 * @param int $seconds The amount of seconds.
2198 * @param array $chosenIntervals The intervals to enable.
2202 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2203 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2205 $segments = array();
2207 foreach ( $intervals as $intervalName => $intervalValue ) {
2208 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2209 // duration-years, duration-decades, duration-centuries, duration-millennia
2210 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2211 $segments[] = $message->inLanguage( $this )->escaped();
2214 return $this->listToText( $segments );
2218 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2219 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2223 * @param int $seconds The amount of seconds.
2224 * @param array $chosenIntervals The intervals to enable.
2228 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2229 if ( empty( $chosenIntervals ) ) {
2230 $chosenIntervals = array(
2242 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2243 $sortedNames = array_keys( $intervals );
2244 $smallestInterval = array_pop( $sortedNames );
2246 $segments = array();
2248 foreach ( $intervals as $name => $length ) {
2249 $value = floor( $seconds / $length );
2251 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2252 $seconds -= $value * $length;
2253 $segments[$name] = $value;
2261 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2263 * @param string $type Can be 'date', 'time' or 'both'
2264 * @param string $ts The time format which needs to be turned into a
2265 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2266 * @param User $user User object used to get preferences for timezone and format
2267 * @param array $options Array, can contain the following keys:
2268 * - 'timecorrection': time correction, can have the following values:
2269 * - true: use user's preference
2270 * - false: don't use time correction
2271 * - int: value of time correction in minutes
2272 * - 'format': format to use, can have the following values:
2273 * - true: use user's preference
2274 * - false: use default preference
2275 * - string: format to use
2279 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2280 $ts = wfTimestamp( TS_MW
, $ts );
2281 $options +
= array( 'timecorrection' => true, 'format' => true );
2282 if ( $options['timecorrection'] !== false ) {
2283 if ( $options['timecorrection'] === true ) {
2284 $offset = $user->getOption( 'timecorrection' );
2286 $offset = $options['timecorrection'];
2288 $ts = $this->userAdjust( $ts, $offset );
2290 if ( $options['format'] === true ) {
2291 $format = $user->getDatePreference();
2293 $format = $options['format'];
2295 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2296 return $this->sprintfDate( $df, $ts );
2300 * Get the formatted date for the given timestamp and formatted for
2303 * @param mixed $ts Mixed: the time format which needs to be turned into a
2304 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2305 * @param User $user User object used to get preferences for timezone and format
2306 * @param array $options Array, can contain the following keys:
2307 * - 'timecorrection': time correction, can have the following values:
2308 * - true: use user's preference
2309 * - false: don't use time correction
2310 * - int: value of time correction in minutes
2311 * - 'format': format to use, can have the following values:
2312 * - true: use user's preference
2313 * - false: use default preference
2314 * - string: format to use
2318 public function userDate( $ts, User
$user, array $options = array() ) {
2319 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2323 * Get the formatted time for the given timestamp and formatted for
2326 * @param mixed $ts The time format which needs to be turned into a
2327 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2328 * @param User $user User object used to get preferences for timezone and format
2329 * @param array $options Array, can contain the following keys:
2330 * - 'timecorrection': time correction, can have the following values:
2331 * - true: use user's preference
2332 * - false: don't use time correction
2333 * - int: value of time correction in minutes
2334 * - 'format': format to use, can have the following values:
2335 * - true: use user's preference
2336 * - false: use default preference
2337 * - string: format to use
2341 public function userTime( $ts, User
$user, array $options = array() ) {
2342 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2346 * Get the formatted date and time for the given timestamp and formatted for
2349 * @param mixed $ts the time format which needs to be turned into a
2350 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2351 * @param User $user User object used to get preferences for timezone and format
2352 * @param array $options Array, can contain the following keys:
2353 * - 'timecorrection': time correction, can have the following values:
2354 * - true: use user's preference
2355 * - false: don't use time correction
2356 * - int: value of time correction in minutes
2357 * - 'format': format to use, can have the following values:
2358 * - true: use user's preference
2359 * - false: use default preference
2360 * - string: format to use
2364 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2365 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2369 * Convert an MWTimestamp into a pretty human-readable timestamp using
2370 * the given user preferences and relative base time.
2372 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2373 * on your timestamp object, which will then call this function. Calling
2374 * this function directly will cause hooks to be skipped over.
2376 * @see MWTimestamp::getHumanTimestamp
2377 * @param MWTimestamp $ts Timestamp to prettify
2378 * @param MWTimestamp $relativeTo Base timestamp
2379 * @param User $user User preferences to use
2380 * @return string Human timestamp
2383 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2384 $diff = $ts->diff( $relativeTo );
2385 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) -
2386 (int)$relativeTo->timestamp
->format( 'w' ) );
2387 $days = $diff->days ?
: (int)$diffDay;
2388 if ( $diff->invert ||
$days > 5
2389 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' )
2391 // Timestamps are in different years: use full timestamp
2392 // Also do full timestamp for future dates
2394 * @FIXME Add better handling of future timestamps.
2396 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2397 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2398 } elseif ( $days > 5 ) {
2399 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2400 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2401 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2402 } elseif ( $days > 1 ) {
2403 // Timestamp within the past week: show the day of the week and time
2404 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2405 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2407 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2408 $ts = wfMessage( "$weekday-at" )
2409 ->inLanguage( $this )
2410 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2412 } elseif ( $days == 1 ) {
2413 // Timestamp was yesterday: say 'yesterday' and the time.
2414 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2415 $ts = wfMessage( 'yesterday-at' )
2416 ->inLanguage( $this )
2417 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2419 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2420 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2421 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2422 $ts = wfMessage( 'today-at' )
2423 ->inLanguage( $this )
2424 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2427 // From here on in, the timestamp was soon enough ago so that we can simply say
2428 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2429 } elseif ( $diff->h
== 1 ) {
2430 // Less than 90 minutes, but more than an hour ago.
2431 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2432 } elseif ( $diff->i
>= 1 ) {
2433 // A few minutes ago.
2434 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2435 } elseif ( $diff->s
>= 30 ) {
2436 // Less than a minute, but more than 30 sec ago.
2437 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2439 // Less than 30 seconds ago.
2440 $ts = wfMessage( 'just-now' )->text();
2447 * @param string $key
2448 * @return array|null
2450 function getMessage( $key ) {
2451 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2457 function getAllMessages() {
2458 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2463 * @param string $out
2464 * @param string $string
2467 function iconv( $in, $out, $string ) {
2468 # This is a wrapper for iconv in all languages except esperanto,
2469 # which does some nasty x-conversions beforehand
2471 # Even with //IGNORE iconv can whine about illegal characters in
2472 # *input* string. We just ignore those too.
2473 # REF: http://bugs.php.net/bug.php?id=37166
2474 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2475 wfSuppressWarnings();
2476 $text = iconv( $in, $out . '//IGNORE', $string );
2477 wfRestoreWarnings();
2481 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2484 * @param array $matches
2485 * @return mixed|string
2487 function ucwordbreaksCallbackAscii( $matches ) {
2488 return $this->ucfirst( $matches[1] );
2492 * @param array $matches
2495 function ucwordbreaksCallbackMB( $matches ) {
2496 return mb_strtoupper( $matches[0] );
2500 * @param array $matches
2503 function ucCallback( $matches ) {
2504 list( $wikiUpperChars ) = self
::getCaseMaps();
2505 return strtr( $matches[1], $wikiUpperChars );
2509 * @param array $matches
2512 function lcCallback( $matches ) {
2513 list( , $wikiLowerChars ) = self
::getCaseMaps();
2514 return strtr( $matches[1], $wikiLowerChars );
2518 * @param array $matches
2521 function ucwordsCallbackMB( $matches ) {
2522 return mb_strtoupper( $matches[0] );
2526 * @param array $matches
2529 function ucwordsCallbackWiki( $matches ) {
2530 list( $wikiUpperChars ) = self
::getCaseMaps();
2531 return strtr( $matches[0], $wikiUpperChars );
2535 * Make a string's first character uppercase
2537 * @param string $str
2541 function ucfirst( $str ) {
2543 if ( $o < 96 ) { // if already uppercase...
2545 } elseif ( $o < 128 ) {
2546 return ucfirst( $str ); // use PHP's ucfirst()
2548 // fall back to more complex logic in case of multibyte strings
2549 return $this->uc( $str, true );
2554 * Convert a string to uppercase
2556 * @param string $str
2557 * @param bool $first
2561 function uc( $str, $first = false ) {
2562 if ( function_exists( 'mb_strtoupper' ) ) {
2564 if ( $this->isMultibyte( $str ) ) {
2565 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2567 return ucfirst( $str );
2570 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2573 if ( $this->isMultibyte( $str ) ) {
2574 $x = $first ?
'^' : '';
2575 return preg_replace_callback(
2576 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2577 array( $this, 'ucCallback' ),
2581 return $first ?
ucfirst( $str ) : strtoupper( $str );
2587 * @param string $str
2588 * @return mixed|string
2590 function lcfirst( $str ) {
2593 return strval( $str );
2594 } elseif ( $o >= 128 ) {
2595 return $this->lc( $str, true );
2596 } elseif ( $o > 96 ) {
2599 $str[0] = strtolower( $str[0] );
2605 * @param string $str
2606 * @param bool $first
2607 * @return mixed|string
2609 function lc( $str, $first = false ) {
2610 if ( function_exists( 'mb_strtolower' ) ) {
2612 if ( $this->isMultibyte( $str ) ) {
2613 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2615 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2618 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2621 if ( $this->isMultibyte( $str ) ) {
2622 $x = $first ?
'^' : '';
2623 return preg_replace_callback(
2624 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2625 array( $this, 'lcCallback' ),
2629 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2635 * @param string $str
2638 function isMultibyte( $str ) {
2639 return (bool)preg_match( '/[\x80-\xff]/', $str );
2643 * @param string $str
2644 * @return mixed|string
2646 function ucwords( $str ) {
2647 if ( $this->isMultibyte( $str ) ) {
2648 $str = $this->lc( $str );
2650 // regexp to find first letter in each word (i.e. after each space)
2651 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2653 // function to use to capitalize a single char
2654 if ( function_exists( 'mb_strtoupper' ) ) {
2655 return preg_replace_callback(
2657 array( $this, 'ucwordsCallbackMB' ),
2661 return preg_replace_callback(
2663 array( $this, 'ucwordsCallbackWiki' ),
2668 return ucwords( strtolower( $str ) );
2673 * capitalize words at word breaks
2675 * @param string $str
2678 function ucwordbreaks( $str ) {
2679 if ( $this->isMultibyte( $str ) ) {
2680 $str = $this->lc( $str );
2682 // since \b doesn't work for UTF-8, we explicitely define word break chars
2683 $breaks = "[ \-\(\)\}\{\.,\?!]";
2685 // find first letter after word break
2686 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2687 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2689 if ( function_exists( 'mb_strtoupper' ) ) {
2690 return preg_replace_callback(
2692 array( $this, 'ucwordbreaksCallbackMB' ),
2696 return preg_replace_callback(
2698 array( $this, 'ucwordsCallbackWiki' ),
2703 return preg_replace_callback(
2704 '/\b([\w\x80-\xff]+)\b/',
2705 array( $this, 'ucwordbreaksCallbackAscii' ),
2712 * Return a case-folded representation of $s
2714 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2715 * and $s2 are the same except for the case of their characters. It is not
2716 * necessary for the value returned to make sense when displayed.
2718 * Do *not* perform any other normalisation in this function. If a caller
2719 * uses this function when it should be using a more general normalisation
2720 * function, then fix the caller.
2726 function caseFold( $s ) {
2727 return $this->uc( $s );
2734 function checkTitleEncoding( $s ) {
2735 if ( is_array( $s ) ) {
2736 throw new MWException( 'Given array to checkTitleEncoding.' );
2738 if ( StringUtils
::isUtf8( $s ) ) {
2742 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2748 function fallback8bitEncoding() {
2749 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2753 * Most writing systems use whitespace to break up words.
2754 * Some languages such as Chinese don't conventionally do this,
2755 * which requires special handling when breaking up words for
2760 function hasWordBreaks() {
2765 * Some languages such as Chinese require word segmentation,
2766 * Specify such segmentation when overridden in derived class.
2768 * @param string $string
2771 function segmentByWord( $string ) {
2776 * Some languages have special punctuation need to be normalized.
2777 * Make such changes here.
2779 * @param string $string
2782 function normalizeForSearch( $string ) {
2783 return self
::convertDoubleWidth( $string );
2787 * convert double-width roman characters to single-width.
2788 * range: ff00-ff5f ~= 0020-007f
2790 * @param string $string
2794 protected static function convertDoubleWidth( $string ) {
2795 static $full = null;
2796 static $half = null;
2798 if ( $full === null ) {
2799 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2800 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2801 $full = str_split( $fullWidth, 3 );
2802 $half = str_split( $halfWidth );
2805 $string = str_replace( $full, $half, $string );
2810 * @param string $string
2811 * @param string $pattern
2814 protected static function insertSpace( $string, $pattern ) {
2815 $string = preg_replace( $pattern, " $1 ", $string );
2816 $string = preg_replace( '/ +/', ' ', $string );
2821 * @param array $termsArray
2824 function convertForSearchResult( $termsArray ) {
2825 # some languages, e.g. Chinese, need to do a conversion
2826 # in order for search results to be displayed correctly
2831 * Get the first character of a string.
2836 function firstChar( $s ) {
2839 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2840 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2845 if ( isset( $matches[1] ) ) {
2846 if ( strlen( $matches[1] ) != 3 ) {
2850 // Break down Hangul syllables to grab the first jamo
2851 $code = utf8ToCodepoint( $matches[1] );
2852 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2854 } elseif ( $code < 0xb098 ) {
2855 return "\xe3\x84\xb1";
2856 } elseif ( $code < 0xb2e4 ) {
2857 return "\xe3\x84\xb4";
2858 } elseif ( $code < 0xb77c ) {
2859 return "\xe3\x84\xb7";
2860 } elseif ( $code < 0xb9c8 ) {
2861 return "\xe3\x84\xb9";
2862 } elseif ( $code < 0xbc14 ) {
2863 return "\xe3\x85\x81";
2864 } elseif ( $code < 0xc0ac ) {
2865 return "\xe3\x85\x82";
2866 } elseif ( $code < 0xc544 ) {
2867 return "\xe3\x85\x85";
2868 } elseif ( $code < 0xc790 ) {
2869 return "\xe3\x85\x87";
2870 } elseif ( $code < 0xcc28 ) {
2871 return "\xe3\x85\x88";
2872 } elseif ( $code < 0xce74 ) {
2873 return "\xe3\x85\x8a";
2874 } elseif ( $code < 0xd0c0 ) {
2875 return "\xe3\x85\x8b";
2876 } elseif ( $code < 0xd30c ) {
2877 return "\xe3\x85\x8c";
2878 } elseif ( $code < 0xd558 ) {
2879 return "\xe3\x85\x8d";
2881 return "\xe3\x85\x8e";
2888 function initEncoding() {
2889 # Some languages may have an alternate char encoding option
2890 # (Esperanto X-coding, Japanese furigana conversion, etc)
2891 # If this language is used as the primary content language,
2892 # an override to the defaults can be set here on startup.
2899 function recodeForEdit( $s ) {
2900 # For some languages we'll want to explicitly specify
2901 # which characters make it into the edit box raw
2902 # or are converted in some way or another.
2903 global $wgEditEncoding;
2904 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2907 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2915 function recodeInput( $s ) {
2916 # Take the previous into account.
2917 global $wgEditEncoding;
2918 if ( $wgEditEncoding != '' ) {
2919 $enc = $wgEditEncoding;
2923 if ( $enc == 'UTF-8' ) {
2926 return $this->iconv( $enc, 'UTF-8', $s );
2931 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2932 * also cleans up certain backwards-compatible sequences, converting them
2933 * to the modern Unicode equivalent.
2935 * This is language-specific for performance reasons only.
2941 function normalize( $s ) {
2942 global $wgAllUnicodeFixes;
2943 $s = UtfNormal
::cleanUp( $s );
2944 if ( $wgAllUnicodeFixes ) {
2945 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2946 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2953 * Transform a string using serialized data stored in the given file (which
2954 * must be in the serialized subdirectory of $IP). The file contains pairs
2955 * mapping source characters to destination characters.
2957 * The data is cached in process memory. This will go faster if you have the
2958 * FastStringSearch extension.
2960 * @param string $file
2961 * @param string $string
2963 * @throws MWException
2966 function transformUsingPairFile( $file, $string ) {
2967 if ( !isset( $this->transformData
[$file] ) ) {
2968 $data = wfGetPrecompiledData( $file );
2969 if ( $data === false ) {
2970 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2972 $this->transformData
[$file] = new ReplacementArray( $data );
2974 return $this->transformData
[$file]->replace( $string );
2978 * For right-to-left language support
2983 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2987 * Return the correct HTML 'dir' attribute value for this language.
2991 return $this->isRTL() ?
'rtl' : 'ltr';
2995 * Return 'left' or 'right' as appropriate alignment for line-start
2996 * for this language's text direction.
2998 * Should be equivalent to CSS3 'start' text-align value....
3002 function alignStart() {
3003 return $this->isRTL() ?
'right' : 'left';
3007 * Return 'right' or 'left' as appropriate alignment for line-end
3008 * for this language's text direction.
3010 * Should be equivalent to CSS3 'end' text-align value....
3014 function alignEnd() {
3015 return $this->isRTL() ?
'left' : 'right';
3019 * A hidden direction mark (LRM or RLM), depending on the language direction.
3020 * Unlike getDirMark(), this function returns the character as an HTML entity.
3021 * This function should be used when the output is guaranteed to be HTML,
3022 * because it makes the output HTML source code more readable. When
3023 * the output is plain text or can be escaped, getDirMark() should be used.
3025 * @param bool $opposite Get the direction mark opposite to your language
3029 function getDirMarkEntity( $opposite = false ) {
3031 return $this->isRTL() ?
'‎' : '‏';
3033 return $this->isRTL() ?
'‏' : '‎';
3037 * A hidden direction mark (LRM or RLM), depending on the language direction.
3038 * This function produces them as invisible Unicode characters and
3039 * the output may be hard to read and debug, so it should only be used
3040 * when the output is plain text or can be escaped. When the output is
3041 * HTML, use getDirMarkEntity() instead.
3043 * @param bool $opposite Get the direction mark opposite to your language
3046 function getDirMark( $opposite = false ) {
3047 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3048 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3050 return $this->isRTL() ?
$lrm : $rlm;
3052 return $this->isRTL() ?
$rlm : $lrm;
3058 function capitalizeAllNouns() {
3059 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
3063 * An arrow, depending on the language direction.
3065 * @param string $direction The direction of the arrow: forwards (default),
3066 * backwards, left, right, up, down.
3069 function getArrow( $direction = 'forwards' ) {
3070 switch ( $direction ) {
3072 return $this->isRTL() ?
'←' : '→';
3074 return $this->isRTL() ?
'→' : '←';
3087 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3091 function linkPrefixExtension() {
3092 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
3096 * Get all magic words from cache.
3099 function getMagicWords() {
3100 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
3104 * Run the LanguageGetMagic hook once.
3106 protected function doMagicHook() {
3107 if ( $this->mMagicHookDone
) {
3110 $this->mMagicHookDone
= true;
3111 wfProfileIn( 'LanguageGetMagic' );
3112 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3113 wfProfileOut( 'LanguageGetMagic' );
3117 * Fill a MagicWord object with data from here
3119 * @param MagicWord $mw
3121 function getMagic( $mw ) {
3122 // Saves a function call
3123 if ( ! $this->mMagicHookDone
) {
3124 $this->doMagicHook();
3127 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3128 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3130 $rawEntry = self
::$dataCache->getSubitem(
3131 $this->mCode
, 'magicWords', $mw->mId
);
3134 if ( !is_array( $rawEntry ) ) {
3135 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3137 $mw->mCaseSensitive
= $rawEntry[0];
3138 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3143 * Add magic words to the extension array
3145 * @param array $newWords
3147 function addMagicWordsByLang( $newWords ) {
3148 $fallbackChain = $this->getFallbackLanguages();
3149 $fallbackChain = array_reverse( $fallbackChain );
3150 foreach ( $fallbackChain as $code ) {
3151 if ( isset( $newWords[$code] ) ) {
3152 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3158 * Get special page names, as an associative array
3159 * case folded alias => real name
3162 function getSpecialPageAliases() {
3163 // Cache aliases because it may be slow to load them
3164 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3166 $this->mExtendedSpecialPageAliases
=
3167 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3168 wfRunHooks( 'LanguageGetSpecialPageAliases',
3169 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3172 return $this->mExtendedSpecialPageAliases
;
3176 * Italic is unsuitable for some languages
3178 * @param string $text The text to be emphasized.
3181 function emphasize( $text ) {
3182 return "<em>$text</em>";
3186 * Normally we output all numbers in plain en_US style, that is
3187 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3188 * point twohundredthirtyfive. However this is not suitable for all
3189 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3190 * Icelandic just want to use commas instead of dots, and dots instead
3191 * of commas like "293.291,235".
3193 * An example of this function being called:
3195 * wfMessage( 'message' )->numParams( $num )->text()
3198 * See $separatorTransformTable on MessageIs.php for
3199 * the , => . and . => , implementation.
3201 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3202 * @param int|float $number The string to be formatted, should be an integer
3203 * or a floating point number.
3204 * @param bool $nocommafy Set to true for special numbers like dates
3207 public function formatNum( $number, $nocommafy = false ) {
3208 global $wgTranslateNumerals;
3209 if ( !$nocommafy ) {
3210 $number = $this->commafy( $number );
3211 $s = $this->separatorTransformTable();
3213 $number = strtr( $number, $s );
3217 if ( $wgTranslateNumerals ) {
3218 $s = $this->digitTransformTable();
3220 $number = strtr( $number, $s );
3228 * Front-end for non-commafied formatNum
3230 * @param int|float $number The string to be formatted, should be an integer
3231 * or a floating point number.
3235 public function formatNumNoSeparators( $number ) {
3236 return $this->formatNum( $number, true );
3240 * @param string $number
3243 public function parseFormattedNumber( $number ) {
3244 $s = $this->digitTransformTable();
3246 // eliminate empty array values such as ''. (bug 64347)
3247 $s = array_filter( $s );
3248 $number = strtr( $number, array_flip( $s ) );
3251 $s = $this->separatorTransformTable();
3253 // eliminate empty array values such as ''. (bug 64347)
3254 $s = array_filter( $s );
3255 $number = strtr( $number, array_flip( $s ) );
3258 $number = strtr( $number, array( ',' => '' ) );
3263 * Adds commas to a given number
3265 * @param mixed $number
3268 function commafy( $number ) {
3269 $digitGroupingPattern = $this->digitGroupingPattern();
3270 if ( $number === null ) {
3274 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3275 // default grouping is at thousands, use the same for ###,###,### pattern too.
3276 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3278 // Ref: http://cldr.unicode.org/translation/number-patterns
3280 if ( intval( $number ) < 0 ) {
3281 // For negative numbers apply the algorithm like positive number and add sign.
3283 $number = substr( $number, 1 );
3285 $integerPart = array();
3286 $decimalPart = array();
3287 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3288 preg_match( "/\d+/", $number, $integerPart );
3289 preg_match( "/\.\d*/", $number, $decimalPart );
3290 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3291 if ( $groupedNumber === $number ) {
3292 // the string does not have any number part. Eg: .12345
3293 return $sign . $groupedNumber;
3295 $start = $end = strlen( $integerPart[0] );
3296 while ( $start > 0 ) {
3297 $match = $matches[0][$numMatches - 1];
3298 $matchLen = strlen( $match );
3299 $start = $end - $matchLen;
3303 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3305 if ( $numMatches > 1 ) {
3306 // use the last pattern for the rest of the number
3310 $groupedNumber = "," . $groupedNumber;
3313 return $sign . $groupedNumber;
3320 function digitGroupingPattern() {
3321 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3327 function digitTransformTable() {
3328 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3334 function separatorTransformTable() {
3335 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3339 * Take a list of strings and build a locale-friendly comma-separated
3340 * list, using the local comma-separator message.
3341 * The last two strings are chained with an "and".
3342 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3344 * @param string[] $l
3347 function listToText( array $l ) {
3348 $m = count( $l ) - 1;
3353 $and = $this->getMessageFromDB( 'and' );
3354 $space = $this->getMessageFromDB( 'word-separator' );
3356 $comma = $this->getMessageFromDB( 'comma-separator' );
3360 for ( $i = $m - 1; $i >= 0; $i-- ) {
3361 if ( $i == $m - 1 ) {
3362 $s = $l[$i] . $and . $space . $s;
3364 $s = $l[$i] . $comma . $s;
3371 * Take a list of strings and build a locale-friendly comma-separated
3372 * list, using the local comma-separator message.
3373 * @param string[] $list Array of strings to put in a comma list
3376 function commaList( array $list ) {
3378 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3384 * Take a list of strings and build a locale-friendly semicolon-separated
3385 * list, using the local semicolon-separator message.
3386 * @param string[] $list Array of strings to put in a semicolon list
3389 function semicolonList( array $list ) {
3391 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3397 * Same as commaList, but separate it with the pipe instead.
3398 * @param string[] $list Array of strings to put in a pipe list
3401 function pipeList( array $list ) {
3403 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3409 * Truncate a string to a specified length in bytes, appending an optional
3410 * string (e.g. for ellipses)
3412 * The database offers limited byte lengths for some columns in the database;
3413 * multi-byte character sets mean we need to ensure that only whole characters
3414 * are included, otherwise broken characters can be passed to the user
3416 * If $length is negative, the string will be truncated from the beginning
3418 * @param string $string String to truncate
3419 * @param int $length Maximum length (including ellipses)
3420 * @param string $ellipsis String to append to the truncated text
3421 * @param bool $adjustLength Subtract length of ellipsis from $length.
3422 * $adjustLength was introduced in 1.18, before that behaved as if false.
3425 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3426 # Use the localized ellipsis character
3427 if ( $ellipsis == '...' ) {
3428 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3430 # Check if there is no need to truncate
3431 if ( $length == 0 ) {
3432 return $ellipsis; // convention
3433 } elseif ( strlen( $string ) <= abs( $length ) ) {
3434 return $string; // no need to truncate
3436 $stringOriginal = $string;
3437 # If ellipsis length is >= $length then we can't apply $adjustLength
3438 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3439 $string = $ellipsis; // this can be slightly unexpected
3440 # Otherwise, truncate and add ellipsis...
3442 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3443 if ( $length > 0 ) {
3444 $length -= $eLength;
3445 $string = substr( $string, 0, $length ); // xyz...
3446 $string = $this->removeBadCharLast( $string );
3447 $string = rtrim( $string );
3448 $string = $string . $ellipsis;
3450 $length +
= $eLength;
3451 $string = substr( $string, $length ); // ...xyz
3452 $string = $this->removeBadCharFirst( $string );
3453 $string = ltrim( $string );
3454 $string = $ellipsis . $string;
3457 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3458 # This check is *not* redundant if $adjustLength, due to the single case where
3459 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3460 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3463 return $stringOriginal;
3468 * Remove bytes that represent an incomplete Unicode character
3469 * at the end of string (e.g. bytes of the char are missing)
3471 * @param string $string
3474 protected function removeBadCharLast( $string ) {
3475 if ( $string != '' ) {
3476 $char = ord( $string[strlen( $string ) - 1] );
3478 if ( $char >= 0xc0 ) {
3479 # We got the first byte only of a multibyte char; remove it.
3480 $string = substr( $string, 0, -1 );
3481 } elseif ( $char >= 0x80 &&
3482 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3483 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3485 # We chopped in the middle of a character; remove it
3493 * Remove bytes that represent an incomplete Unicode character
3494 * at the start of string (e.g. bytes of the char are missing)
3496 * @param string $string
3499 protected function removeBadCharFirst( $string ) {
3500 if ( $string != '' ) {
3501 $char = ord( $string[0] );
3502 if ( $char >= 0x80 && $char < 0xc0 ) {
3503 # We chopped in the middle of a character; remove the whole thing
3504 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3511 * Truncate a string of valid HTML to a specified length in bytes,
3512 * appending an optional string (e.g. for ellipses), and return valid HTML
3514 * This is only intended for styled/linked text, such as HTML with
3515 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3516 * Also, this will not detect things like "display:none" CSS.
3518 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3520 * @param string $text HTML string to truncate
3521 * @param int $length (zero/positive) Maximum length (including ellipses)
3522 * @param string $ellipsis String to append to the truncated text
3525 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3526 # Use the localized ellipsis character
3527 if ( $ellipsis == '...' ) {
3528 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3530 # Check if there is clearly no need to truncate
3531 if ( $length <= 0 ) {
3532 return $ellipsis; // no text shown, nothing to format (convention)
3533 } elseif ( strlen( $text ) <= $length ) {
3534 return $text; // string short enough even *with* HTML (short-circuit)
3537 $dispLen = 0; // innerHTML legth so far
3538 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3539 $tagType = 0; // 0-open, 1-close
3540 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3541 $entityState = 0; // 0-not entity, 1-entity
3542 $tag = $ret = ''; // accumulated tag name, accumulated result string
3543 $openTags = array(); // open tag stack
3544 $maybeState = null; // possible truncation state
3546 $textLen = strlen( $text );
3547 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3548 for ( $pos = 0; true; ++
$pos ) {
3549 # Consider truncation once the display length has reached the maximim.
3550 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3551 # Check that we're not in the middle of a bracket/entity...
3552 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3553 if ( !$testingEllipsis ) {
3554 $testingEllipsis = true;
3555 # Save where we are; we will truncate here unless there turn out to
3556 # be so few remaining characters that truncation is not necessary.
3557 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3558 $maybeState = array( $ret, $openTags ); // save state
3560 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3561 # String in fact does need truncation, the truncation point was OK.
3562 list( $ret, $openTags ) = $maybeState; // reload state
3563 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3564 $ret .= $ellipsis; // add ellipsis
3568 if ( $pos >= $textLen ) {
3569 break; // extra iteration just for above checks
3572 # Read the next char...
3574 $lastCh = $pos ?
$text[$pos - 1] : '';
3575 $ret .= $ch; // add to result string
3577 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3578 $entityState = 0; // for bad HTML
3579 $bracketState = 1; // tag started (checking for backslash)
3580 } elseif ( $ch == '>' ) {
3581 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3582 $entityState = 0; // for bad HTML
3583 $bracketState = 0; // out of brackets
3584 } elseif ( $bracketState == 1 ) {
3586 $tagType = 1; // close tag (e.g. "</span>")
3588 $tagType = 0; // open tag (e.g. "<span>")
3591 $bracketState = 2; // building tag name
3592 } elseif ( $bracketState == 2 ) {
3596 // Name found (e.g. "<a href=..."), add on tag attributes...
3597 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3599 } elseif ( $bracketState == 0 ) {
3600 if ( $entityState ) {
3603 $dispLen++
; // entity is one displayed char
3606 if ( $neLength == 0 && !$maybeState ) {
3607 // Save state without $ch. We want to *hit* the first
3608 // display char (to get tags) but not *use* it if truncating.
3609 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3612 $entityState = 1; // entity found, (e.g. " ")
3614 $dispLen++
; // this char is displayed
3615 // Add the next $max display text chars after this in one swoop...
3616 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3617 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3618 $dispLen +
= $skipped;
3624 // Close the last tag if left unclosed by bad HTML
3625 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3626 while ( count( $openTags ) > 0 ) {
3627 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3633 * truncateHtml() helper function
3634 * like strcspn() but adds the skipped chars to $ret
3636 * @param string $ret
3637 * @param string $text
3638 * @param string $search
3640 * @param null|int $len
3643 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3644 if ( $len === null ) {
3645 $len = -1; // -1 means "no limit" for strcspn
3646 } elseif ( $len < 0 ) {
3650 if ( $start < strlen( $text ) ) {
3651 $skipCount = strcspn( $text, $search, $start, $len );
3652 $ret .= substr( $text, $start, $skipCount );
3658 * truncateHtml() helper function
3659 * (a) push or pop $tag from $openTags as needed
3660 * (b) clear $tag value
3661 * @param string &$tag Current HTML tag name we are looking at
3662 * @param int $tagType (0-open tag, 1-close tag)
3663 * @param string $lastCh Character before the '>' that ended this tag
3664 * @param array &$openTags Open tag stack (not accounting for $tag)
3666 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3667 $tag = ltrim( $tag );
3669 if ( $tagType == 0 && $lastCh != '/' ) {
3670 $openTags[] = $tag; // tag opened (didn't close itself)
3671 } elseif ( $tagType == 1 ) {
3672 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3673 array_pop( $openTags ); // tag closed
3681 * Grammatical transformations, needed for inflected languages
3682 * Invoked by putting {{grammar:case|word}} in a message
3684 * @param string $word
3685 * @param string $case
3688 function convertGrammar( $word, $case ) {
3689 global $wgGrammarForms;
3690 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3691 return $wgGrammarForms[$this->getCode()][$case][$word];
3697 * Get the grammar forms for the content language
3698 * @return array Array of grammar forms
3701 function getGrammarForms() {
3702 global $wgGrammarForms;
3703 if ( isset( $wgGrammarForms[$this->getCode()] )
3704 && is_array( $wgGrammarForms[$this->getCode()] )
3706 return $wgGrammarForms[$this->getCode()];
3712 * Provides an alternative text depending on specified gender.
3713 * Usage {{gender:username|masculine|feminine|unknown}}.
3714 * username is optional, in which case the gender of current user is used,
3715 * but only in (some) interface messages; otherwise default gender is used.
3717 * If no forms are given, an empty string is returned. If only one form is
3718 * given, it will be returned unconditionally. These details are implied by
3719 * the caller and cannot be overridden in subclasses.
3721 * If three forms are given, the default is to use the third (unknown) form.
3722 * If fewer than three forms are given, the default is to use the first (masculine) form.
3723 * These details can be overridden in subclasses.
3725 * @param string $gender
3726 * @param array $forms
3730 function gender( $gender, $forms ) {
3731 if ( !count( $forms ) ) {
3734 $forms = $this->preConvertPlural( $forms, 2 );
3735 if ( $gender === 'male' ) {
3738 if ( $gender === 'female' ) {
3741 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3745 * Plural form transformations, needed for some languages.
3746 * For example, there are 3 form of plural in Russian and Polish,
3747 * depending on "count mod 10". See [[w:Plural]]
3748 * For English it is pretty simple.
3750 * Invoked by putting {{plural:count|wordform1|wordform2}}
3751 * or {{plural:count|wordform1|wordform2|wordform3}}
3753 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3755 * @param int $count Non-localized number
3756 * @param array $forms Different plural forms
3757 * @return string Correct form of plural for $count in this language
3759 function convertPlural( $count, $forms ) {
3760 // Handle explicit n=pluralform cases
3761 $forms = $this->handleExplicitPluralForms( $count, $forms );
3762 if ( is_string( $forms ) ) {
3765 if ( !count( $forms ) ) {
3769 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3770 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3771 return $forms[$pluralForm];
3775 * Handles explicit plural forms for Language::convertPlural()
3777 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3778 * If an explicitly defined plural form matches the $count, then
3779 * string value returned, otherwise array returned for further consideration
3780 * by CLDR rules or overridden convertPlural().
3784 * @param int $count non-localized number
3785 * @param array $forms different plural forms
3787 * @return array|string
3789 protected function handleExplicitPluralForms( $count, array $forms ) {
3790 foreach ( $forms as $index => $form ) {
3791 if ( preg_match( '/\d+=/i', $form ) ) {
3792 $pos = strpos( $form, '=' );
3793 if ( substr( $form, 0, $pos ) === (string) $count ) {
3794 return substr( $form, $pos +
1 );
3796 unset( $forms[$index] );
3799 return array_values( $forms );
3803 * Checks that convertPlural was given an array and pads it to requested
3804 * amount of forms by copying the last one.
3806 * @param int $count How many forms should there be at least
3807 * @param array $forms Array of forms given to convertPlural
3808 * @return array Padded array of forms or an exception if not an array
3810 protected function preConvertPlural( /* Array */ $forms, $count ) {
3811 while ( count( $forms ) < $count ) {
3812 $forms[] = $forms[count( $forms ) - 1];
3818 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3819 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3820 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3821 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3824 * @param string $str The validated block duration in English
3825 * @return string Somehow translated block duration
3826 * @see LanguageFi.php for example implementation
3828 function translateBlockExpiry( $str ) {
3829 $duration = SpecialBlock
::getSuggestedDurations( $this );
3830 foreach ( $duration as $show => $value ) {
3831 if ( strcmp( $str, $value ) == 0 ) {
3832 return htmlspecialchars( trim( $show ) );
3836 // Since usually only infinite or indefinite is only on list, so try
3837 // equivalents if still here.
3838 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3839 if ( in_array( $str, $indefs ) ) {
3840 foreach ( $indefs as $val ) {
3841 $show = array_search( $val, $duration, true );
3842 if ( $show !== false ) {
3843 return htmlspecialchars( trim( $show ) );
3848 // If all else fails, return a standard duration or timestamp description.
3849 $time = strtotime( $str, 0 );
3850 if ( $time === false ) { // Unknown format. Return it as-is in case.
3852 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3853 // $time is relative to 0 so it's a duration length.
3854 return $this->formatDuration( $time );
3855 } else { // It's an absolute timestamp.
3856 if ( $time === 0 ) {
3857 // wfTimestamp() handles 0 as current time instead of epoch.
3858 return $this->timeanddate( '19700101000000' );
3860 return $this->timeanddate( $time );
3866 * languages like Chinese need to be segmented in order for the diff
3869 * @param string $text
3872 public function segmentForDiff( $text ) {
3877 * and unsegment to show the result
3879 * @param string $text
3882 public function unsegmentForDiff( $text ) {
3887 * Return the LanguageConverter used in the Language
3890 * @return LanguageConverter
3892 public function getConverter() {
3893 return $this->mConverter
;
3897 * convert text to all supported variants
3899 * @param string $text
3902 public function autoConvertToAllVariants( $text ) {
3903 return $this->mConverter
->autoConvertToAllVariants( $text );
3907 * convert text to different variants of a language.
3909 * @param string $text
3912 public function convert( $text ) {
3913 return $this->mConverter
->convert( $text );
3917 * Convert a Title object to a string in the preferred variant
3919 * @param Title $title
3922 public function convertTitle( $title ) {
3923 return $this->mConverter
->convertTitle( $title );
3927 * Convert a namespace index to a string in the preferred variant
3932 public function convertNamespace( $ns ) {
3933 return $this->mConverter
->convertNamespace( $ns );
3937 * Check if this is a language with variants
3941 public function hasVariants() {
3942 return count( $this->getVariants() ) > 1;
3946 * Check if the language has the specific variant
3949 * @param string $variant
3952 public function hasVariant( $variant ) {
3953 return (bool)$this->mConverter
->validateVariant( $variant );
3957 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3959 * @param string $text
3961 * @deprecated since 1.22 is no longer used
3963 public function armourMath( $text ) {
3964 return $this->mConverter
->armourMath( $text );
3968 * Perform output conversion on a string, and encode for safe HTML output.
3969 * @param string $text Text to be converted
3970 * @param bool $isTitle Whether this conversion is for the article title
3972 * @todo this should get integrated somewhere sane
3974 public function convertHtml( $text, $isTitle = false ) {
3975 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3979 * @param string $key
3982 public function convertCategoryKey( $key ) {
3983 return $this->mConverter
->convertCategoryKey( $key );
3987 * Get the list of variants supported by this language
3988 * see sample implementation in LanguageZh.php
3990 * @return array an array of language codes
3992 public function getVariants() {
3993 return $this->mConverter
->getVariants();
3999 public function getPreferredVariant() {
4000 return $this->mConverter
->getPreferredVariant();
4006 public function getDefaultVariant() {
4007 return $this->mConverter
->getDefaultVariant();
4013 public function getURLVariant() {
4014 return $this->mConverter
->getURLVariant();
4018 * If a language supports multiple variants, it is
4019 * possible that non-existing link in one variant
4020 * actually exists in another variant. this function
4021 * tries to find it. See e.g. LanguageZh.php
4023 * @param string $link The name of the link
4024 * @param Title $nt The title object of the link
4025 * @param bool $ignoreOtherCond To disable other conditions when
4026 * we need to transclude a template or update a category's link
4027 * @return null the input parameters may be modified upon return
4029 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4030 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
4034 * returns language specific options used by User::getPageRenderHash()
4035 * for example, the preferred language variant
4039 function getExtraHashOptions() {
4040 return $this->mConverter
->getExtraHashOptions();
4044 * For languages that support multiple variants, the title of an
4045 * article may be displayed differently in different variants. this
4046 * function returns the apporiate title defined in the body of the article.
4050 public function getParsedTitle() {
4051 return $this->mConverter
->getParsedTitle();
4055 * Prepare external link text for conversion. When the text is
4056 * a URL, it shouldn't be converted, and it'll be wrapped in
4057 * the "raw" tag (-{R| }-) to prevent conversion.
4059 * This function is called "markNoConversion" for historical
4062 * @param string $text Text to be used for external link
4063 * @param bool $noParse Wrap it without confirming it's a real URL first
4064 * @return string The tagged text
4066 public function markNoConversion( $text, $noParse = false ) {
4067 // Excluding protocal-relative URLs may avoid many false positives.
4068 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4069 return $this->mConverter
->markNoConversion( $text );
4076 * A regular expression to match legal word-trailing characters
4077 * which should be merged onto a link of the form [[foo]]bar.
4081 public function linkTrail() {
4082 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
4086 * A regular expression character set to match legal word-prefixing
4087 * characters which should be merged onto a link of the form foo[[bar]].
4091 public function linkPrefixCharset() {
4092 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
4096 * @deprecated since 1.24, will be removed in 1.25
4099 function getLangObj() {
4100 wfDeprecated( __METHOD__
, '1.24' );
4105 * Get the "parent" language which has a converter to convert a "compatible" language
4106 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4108 * @return Language|null
4111 public function getParentLanguage() {
4112 if ( $this->mParentLanguage
!== false ) {
4113 return $this->mParentLanguage
;
4116 $pieces = explode( '-', $this->getCode() );
4118 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
4119 $this->mParentLanguage
= null;
4122 $lang = Language
::factory( $code );
4123 if ( !$lang->hasVariant( $this->getCode() ) ) {
4124 $this->mParentLanguage
= null;
4128 $this->mParentLanguage
= $lang;
4133 * Get the RFC 3066 code for this language object
4135 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4136 * htmlspecialchars() or similar
4140 public function getCode() {
4141 return $this->mCode
;
4145 * Get the code in Bcp47 format which we can use
4146 * inside of html lang="" tags.
4148 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4149 * htmlspecialchars() or similar.
4154 public function getHtmlCode() {
4155 if ( is_null( $this->mHtmlCode
) ) {
4156 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4158 return $this->mHtmlCode
;
4162 * @param string $code
4164 public function setCode( $code ) {
4165 $this->mCode
= $code;
4166 // Ensure we don't leave incorrect cached data lying around
4167 $this->mHtmlCode
= null;
4168 $this->mParentLanguage
= false;
4172 * Get the name of a file for a certain language code
4173 * @param string $prefix Prepend this to the filename
4174 * @param string $code Language code
4175 * @param string $suffix Append this to the filename
4176 * @throws MWException
4177 * @return string $prefix . $mangledCode . $suffix
4179 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4180 if ( !self
::isValidBuiltInCode( $code ) ) {
4181 throw new MWException( "Invalid language code \"$code\"" );
4184 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4188 * Get the language code from a file name. Inverse of getFileName()
4189 * @param string $filename $prefix . $languageCode . $suffix
4190 * @param string $prefix Prefix before the language code
4191 * @param string $suffix Suffix after the language code
4192 * @return string Language code, or false if $prefix or $suffix isn't found
4194 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4196 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4197 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4198 if ( !count( $m ) ) {
4201 return str_replace( '_', '-', strtolower( $m[1] ) );
4205 * @param string $code
4208 public static function getMessagesFileName( $code ) {
4210 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4211 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4216 * @param string $code
4220 public static function getJsonMessagesFileName( $code ) {
4223 if ( !self
::isValidBuiltInCode( $code ) ) {
4224 throw new MWException( "Invalid language code \"$code\"" );
4227 return "$IP/languages/i18n/$code.json";
4231 * @param string $code
4234 public static function getClassFileName( $code ) {
4236 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4240 * Get the first fallback for a given language.
4242 * @param string $code
4244 * @return bool|string
4246 public static function getFallbackFor( $code ) {
4247 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4250 $fallbacks = self
::getFallbacksFor( $code );
4251 $first = array_shift( $fallbacks );
4257 * Get the ordered list of fallback languages.
4260 * @param string $code Language code
4263 public static function getFallbacksFor( $code ) {
4264 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4267 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4268 $v = array_map( 'trim', explode( ',', $v ) );
4269 if ( $v[count( $v ) - 1] !== 'en' ) {
4277 * Get the ordered list of fallback languages, ending with the fallback
4278 * language chain for the site language.
4281 * @param string $code Language code
4282 * @return array array( fallbacks, site fallbacks )
4284 public static function getFallbacksIncludingSiteLanguage( $code ) {
4285 global $wgLanguageCode;
4287 // Usually, we will only store a tiny number of fallback chains, so we
4288 // keep them in static memory.
4289 $cacheKey = "{$code}-{$wgLanguageCode}";
4291 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4292 $fallbacks = self
::getFallbacksFor( $code );
4294 // Append the site's fallback chain, including the site language itself
4295 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4296 array_unshift( $siteFallbacks, $wgLanguageCode );
4298 // Eliminate any languages already included in the chain
4299 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4301 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4303 return self
::$fallbackLanguageCache[$cacheKey];
4307 * Get all messages for a given language
4308 * WARNING: this may take a long time. If you just need all message *keys*
4309 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4311 * @param string $code
4315 public static function getMessagesFor( $code ) {
4316 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4320 * Get a message for a given language
4322 * @param string $key
4323 * @param string $code
4327 public static function getMessageFor( $key, $code ) {
4328 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4332 * Get all message keys for a given language. This is a faster alternative to
4333 * array_keys( Language::getMessagesFor( $code ) )
4336 * @param string $code Language code
4337 * @return array of message keys (strings)
4339 public static function getMessageKeysFor( $code ) {
4340 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4344 * @param string $talk
4347 function fixVariableInNamespace( $talk ) {
4348 if ( strpos( $talk, '$1' ) === false ) {
4352 global $wgMetaNamespace;
4353 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4355 # Allow grammar transformations
4356 # Allowing full message-style parsing would make simple requests
4357 # such as action=raw much more expensive than they need to be.
4358 # This will hopefully cover most cases.
4359 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4360 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4361 return str_replace( ' ', '_', $talk );
4368 function replaceGrammarInNamespace( $m ) {
4369 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4373 * @throws MWException
4376 static function getCaseMaps() {
4377 static $wikiUpperChars, $wikiLowerChars;
4378 if ( isset( $wikiUpperChars ) ) {
4379 return array( $wikiUpperChars, $wikiLowerChars );
4382 wfProfileIn( __METHOD__
);
4383 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4384 if ( $arr === false ) {
4385 throw new MWException(
4386 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4388 $wikiUpperChars = $arr['wikiUpperChars'];
4389 $wikiLowerChars = $arr['wikiLowerChars'];
4390 wfProfileOut( __METHOD__
);
4391 return array( $wikiUpperChars, $wikiLowerChars );
4395 * Decode an expiry (block, protection, etc) which has come from the DB
4397 * @todo FIXME: why are we returnings DBMS-dependent strings???
4399 * @param string $expiry Database expiry String
4400 * @param bool|int $format True to process using language functions, or TS_ constant
4401 * to return the expiry in a given timestamp
4405 public function formatExpiry( $expiry, $format = true ) {
4407 if ( $infinity === null ) {
4408 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4411 if ( $expiry == '' ||
$expiry == $infinity ) {
4412 return $format === true
4413 ?
$this->getMessageFromDB( 'infiniteblock' )
4416 return $format === true
4417 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4418 : wfTimestamp( $format, $expiry );
4424 * @param int|float $seconds
4425 * @param array $format Optional
4426 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4427 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4428 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4430 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4431 * or 'avoidminutes'.
4434 function formatTimePeriod( $seconds, $format = array() ) {
4435 if ( !is_array( $format ) ) {
4436 $format = array( 'avoid' => $format ); // For backwards compatibility
4438 if ( !isset( $format['avoid'] ) ) {
4439 $format['avoid'] = false;
4441 if ( !isset( $format['noabbrevs' ] ) ) {
4442 $format['noabbrevs'] = false;
4444 $secondsMsg = wfMessage(
4445 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4446 $minutesMsg = wfMessage(
4447 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4448 $hoursMsg = wfMessage(
4449 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4450 $daysMsg = wfMessage(
4451 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4453 if ( round( $seconds * 10 ) < 100 ) {
4454 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4455 $s = $secondsMsg->params( $s )->text();
4456 } elseif ( round( $seconds ) < 60 ) {
4457 $s = $this->formatNum( round( $seconds ) );
4458 $s = $secondsMsg->params( $s )->text();
4459 } elseif ( round( $seconds ) < 3600 ) {
4460 $minutes = floor( $seconds / 60 );
4461 $secondsPart = round( fmod( $seconds, 60 ) );
4462 if ( $secondsPart == 60 ) {
4466 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4468 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4469 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4470 $hours = floor( $seconds / 3600 );
4471 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4472 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4473 if ( $secondsPart == 60 ) {
4477 if ( $minutes == 60 ) {
4481 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4483 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4484 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4485 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4488 $days = floor( $seconds / 86400 );
4489 if ( $format['avoid'] === 'avoidminutes' ) {
4490 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4491 if ( $hours == 24 ) {
4495 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4497 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4498 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4499 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4500 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4501 if ( $minutes == 60 ) {
4505 if ( $hours == 24 ) {
4509 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4511 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4513 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4515 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4517 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4524 * Format a bitrate for output, using an appropriate
4525 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4526 * the magnitude in question.
4528 * This use base 1000. For base 1024 use formatSize(), for another base
4529 * see formatComputingNumbers().
4534 function formatBitrate( $bps ) {
4535 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4539 * @param int $size Size of the unit
4540 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4541 * @param string $messageKey Message key to be uesd
4544 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4546 return str_replace( '$1', $this->formatNum( $size ),
4547 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4550 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4553 $maxIndex = count( $sizes ) - 1;
4554 while ( $size >= $boundary && $index < $maxIndex ) {
4559 // For small sizes no decimal places necessary
4562 // For MB and bigger two decimal places are smarter
4565 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4567 $size = round( $size, $round );
4568 $text = $this->getMessageFromDB( $msg );
4569 return str_replace( '$1', $this->formatNum( $size ), $text );
4573 * Format a size in bytes for output, using an appropriate
4574 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4576 * This method use base 1024. For base 1000 use formatBitrate(), for
4577 * another base see formatComputingNumbers()
4579 * @param int $size Size to format
4580 * @return string Plain text (not HTML)
4582 function formatSize( $size ) {
4583 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4587 * Make a list item, used by various special pages
4589 * @param string $page Page link
4590 * @param string $details Text between brackets
4591 * @param bool $oppositedm Add the direction mark opposite to your
4592 * language, to display text properly
4595 function specialList( $page, $details, $oppositedm = true ) {
4596 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4597 $this->getDirMark();
4598 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4599 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4600 return $page . $details;
4604 * Generate (prev x| next x) (20|50|100...) type links for paging
4606 * @param Title $title Title object to link
4607 * @param int $offset
4609 * @param array|string $query Optional URL query parameter string
4610 * @param bool $atend Optional param for specified if this is the last page
4613 public function viewPrevNext( Title
$title, $offset, $limit,
4614 array $query = array(), $atend = false
4616 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4618 # Make 'previous' link
4619 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4620 if ( $offset > 0 ) {
4621 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4622 $query, $prev, 'prevn-title', 'mw-prevlink' );
4624 $plink = htmlspecialchars( $prev );
4628 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4630 $nlink = htmlspecialchars( $next );
4632 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4633 $query, $next, 'nextn-title', 'mw-nextlink' );
4636 # Make links to set number of items per page
4637 $numLinks = array();
4638 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4639 $numLinks[] = $this->numLink( $title, $offset, $num,
4640 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4643 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4644 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4648 * Helper function for viewPrevNext() that generates links
4650 * @param Title $title Title object to link
4651 * @param int $offset
4653 * @param array $query Extra query parameters
4654 * @param string $link Text to use for the link; will be escaped
4655 * @param string $tooltipMsg Name of the message to use as tooltip
4656 * @param string $class Value of the "class" attribute of the link
4657 * @return string HTML fragment
4659 private function numLink( Title
$title, $offset, $limit, array $query, $link,
4662 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4663 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4664 ->numParams( $limit )->text();
4666 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4667 'title' => $tooltip, 'class' => $class ), $link );
4671 * Get the conversion rule title, if any.
4675 public function getConvRuleTitle() {
4676 return $this->mConverter
->getConvRuleTitle();
4680 * Get the compiled plural rules for the language
4682 * @return array Associative array with plural form, and plural rule as key-value pairs
4684 public function getCompiledPluralRules() {
4685 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4686 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4687 if ( !$pluralRules ) {
4688 foreach ( $fallbacks as $fallbackCode ) {
4689 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4690 if ( $pluralRules ) {
4695 return $pluralRules;
4699 * Get the plural rules for the language
4701 * @return array Associative array with plural form number and plural rule as key-value pairs
4703 public function getPluralRules() {
4704 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4705 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4706 if ( !$pluralRules ) {
4707 foreach ( $fallbacks as $fallbackCode ) {
4708 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4709 if ( $pluralRules ) {
4714 return $pluralRules;
4718 * Get the plural rule types for the language
4720 * @return array Associative array with plural form number and plural rule type as key-value pairs
4722 public function getPluralRuleTypes() {
4723 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4724 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4725 if ( !$pluralRuleTypes ) {
4726 foreach ( $fallbacks as $fallbackCode ) {
4727 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4728 if ( $pluralRuleTypes ) {
4733 return $pluralRuleTypes;
4737 * Find the index number of the plural rule appropriate for the given number
4738 * @return int The index number of the plural rule
4740 public function getPluralRuleIndexNumber( $number ) {
4741 $pluralRules = $this->getCompiledPluralRules();
4742 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4747 * Find the plural rule type appropriate for the given number
4748 * For example, if the language is set to Arabic, getPluralType(5) should
4751 * @return string The name of the plural rule type, e.g. one, two, few, many
4753 public function getPluralRuleType( $number ) {
4754 $index = $this->getPluralRuleIndexNumber( $number );
4755 $pluralRuleTypes = $this->getPluralRuleTypes();
4756 if ( isset( $pluralRuleTypes[$index] ) ) {
4757 return $pluralRuleTypes[$index];