Localisation updates from http://translatewiki.net.
[mediawiki.git] / languages / Language.php
blob2fd4bb75d024460fe6b1a962fa25fb70a927d2a9
1 <?php
2 /**
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
20 * @file
21 * @ingroup Language
24 /**
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
30 exit( 1 );
33 # Read language names
34 global $wgLanguageNames;
35 require_once( __DIR__ . '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
41 /**
42 * a fake language converter
44 * @ingroup Language
46 class FakeConverter {
47 /**
48 * @var Language
50 public $mLang;
51 function __construct( $langobj ) { $this->mLang = $langobj; }
52 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
53 function convert( $t ) { return $t; }
54 function convertTo( $text, $variant ) { return $text; }
55 function convertTitle( $t ) { return $t->getPrefixedText(); }
56 function convertNamespace( $ns ) { return $this->mLang->getFormattedNsText( $ns ); }
57 function getVariants() { return array( $this->mLang->getCode() ); }
58 function getPreferredVariant() { return $this->mLang->getCode(); }
59 function getDefaultVariant() { return $this->mLang->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
71 /**
72 * Internationalisation code
73 * @ingroup Language
75 class Language {
77 /**
78 * @var LanguageConverter
80 public $mConverter;
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 public $dateFormatStrings = array();
87 public $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
91 /**
92 * ReplacementArray object caches
94 public $transformData = array();
96 /**
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
105 'friday', 'saturday'
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
115 'december'
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
120 'december-gen'
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
158 * @since 1.20
159 * @var array
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
166 'weeks' => 604800,
167 'days' => 86400,
168 'hours' => 3600,
169 'minutes' => 60,
170 'seconds' => 1,
174 * Get a cached or new language object for a given language code
175 * @param $code String
176 * @return Language
178 static function factory( $code ) {
179 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
181 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
182 $code = $wgDummyLanguageCodes[$code];
185 // get the language object to process
186 $langObj = isset( self::$mLangObjCache[$code] )
187 ? self::$mLangObjCache[$code]
188 : self::newFromCode( $code );
190 // merge the language object in to get it up front in the cache
191 self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache );
192 // get rid of the oldest ones in case we have an overflow
193 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
195 return $langObj;
199 * Create a language object for a given language code
200 * @param $code String
201 * @throws MWException
202 * @return Language
204 protected static function newFromCode( $code ) {
205 // Protect against path traversal below
206 if ( !Language::isValidCode( $code )
207 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
209 throw new MWException( "Invalid language code \"$code\"" );
212 if ( !Language::isValidBuiltInCode( $code ) ) {
213 // It's not possible to customise this code with class files, so
214 // just return a Language object. This is to support uselang= hacks.
215 $lang = new Language;
216 $lang->setCode( $code );
217 return $lang;
220 // Check if there is a language class for the code
221 $class = self::classFromCode( $code );
222 self::preloadLanguageClass( $class );
223 if ( MWInit::classExists( $class ) ) {
224 $lang = new $class;
225 return $lang;
228 // Keep trying the fallback list until we find an existing class
229 $fallbacks = Language::getFallbacksFor( $code );
230 foreach ( $fallbacks as $fallbackCode ) {
231 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
232 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
235 $class = self::classFromCode( $fallbackCode );
236 self::preloadLanguageClass( $class );
237 if ( MWInit::classExists( $class ) ) {
238 $lang = Language::newFromCode( $fallbackCode );
239 $lang->setCode( $code );
240 return $lang;
244 throw new MWException( "Invalid fallback sequence for language '$code'" );
248 * Checks whether any localisation is available for that language tag
249 * in MediaWiki (MessagesXx.php exists).
251 * @param string $code Language tag (in lower case)
252 * @return bool Whether language is supported
253 * @since 1.21
255 public static function isSupportedLanguage( $code ) {
256 return $code === strtolower( $code ) && is_readable( self::getMessagesFileName( $code ) );
260 * Returns true if a language code string is a well-formed language tag
261 * according to RFC 5646.
262 * This function only checks well-formedness; it doesn't check that
263 * language, script or variant codes actually exist in the repositories.
265 * Based on regexes by Mark Davis of the Unicode Consortium:
266 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
268 * @param $code string
269 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
271 * @return bool
272 * @since 1.21
274 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
275 $alpha = '[a-z]';
276 $digit = '[0-9]';
277 $alphanum = '[a-z0-9]';
278 $x = 'x'; # private use singleton
279 $singleton = '[a-wy-z]'; # other singleton
280 $s = $lenient ? '[-_]' : '-';
282 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
283 $script = "$alpha{4}"; # ISO 15924
284 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
285 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
286 $extension = "$singleton(?:$s$alphanum{2,8})+";
287 $privateUse = "$x(?:$s$alphanum{1,8})+";
289 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
290 # Since these are limited, this is safe even later changes to the registry --
291 # the only oddity is that it might change the type of the tag, and thus
292 # the results from the capturing groups.
293 # http://www.iana.org/assignments/language-subtag-registry
295 $grandfathered = "en{$s}GB{$s}oed"
296 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
297 . "|no{$s}(?:bok|nyn)"
298 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
299 . "|zh{$s}min{$s}nan";
301 $variantList = "$variant(?:$s$variant)*";
302 $extensionList = "$extension(?:$s$extension)*";
304 $langtag = "(?:($language)"
305 . "(?:$s$script)?"
306 . "(?:$s$region)?"
307 . "(?:$s$variantList)?"
308 . "(?:$s$extensionList)?"
309 . "(?:$s$privateUse)?)";
311 # The final breakdown, with capturing groups for each of these components
312 # The variants, extensions, grandfathered, and private-use may have interior '-'
314 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
316 return (bool)preg_match( "/$root/", strtolower( $code ) );
320 * Returns true if a language code string is of a valid form, whether or
321 * not it exists. This includes codes which are used solely for
322 * customisation via the MediaWiki namespace.
324 * @param $code string
326 * @return bool
328 public static function isValidCode( $code ) {
329 static $cache = array();
330 if ( isset( $cache[$code] ) ) {
331 return $cache[$code];
333 // People think language codes are html safe, so enforce it.
334 // Ideally we should only allow a-zA-Z0-9-
335 // but, .+ and other chars are often used for {{int:}} hacks
336 // see bugs 37564, 37587, 36938
337 $cache[$code] =
338 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
339 && !preg_match( Title::getTitleInvalidRegex(), $code );
341 return $cache[$code];
345 * Returns true if a language code is of a valid form for the purposes of
346 * internal customisation of MediaWiki, via Messages*.php.
348 * @param $code string
350 * @throws MWException
351 * @since 1.18
352 * @return bool
354 public static function isValidBuiltInCode( $code ) {
356 if ( !is_string( $code ) ) {
357 if ( is_object( $code ) ) {
358 $addmsg = " of class " . get_class( $code );
359 } else {
360 $addmsg = '';
362 $type = gettype( $code );
363 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
366 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
370 * Returns true if a language code is an IETF tag known to MediaWiki.
372 * @param $code string
374 * @since 1.21
375 * @return bool
377 public static function isKnownLanguageTag( $tag ) {
378 static $coreLanguageNames;
380 if ( $coreLanguageNames === null ) {
381 include( MWInit::compiledPath( 'languages/Names.php' ) );
384 if ( isset( $coreLanguageNames[$tag] )
385 || self::fetchLanguageName( $tag, $tag ) !== ''
387 return true;
390 return false;
394 * @param $code
395 * @return String Name of the language class
397 public static function classFromCode( $code ) {
398 if ( $code == 'en' ) {
399 return 'Language';
400 } else {
401 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
406 * Includes language class files
408 * @param $class string Name of the language class
410 public static function preloadLanguageClass( $class ) {
411 global $IP;
413 if ( $class === 'Language' ) {
414 return;
417 if ( !defined( 'MW_COMPILED' ) ) {
418 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
419 include_once( "$IP/languages/classes/$class.php" );
425 * Get the LocalisationCache instance
427 * @return LocalisationCache
429 public static function getLocalisationCache() {
430 if ( is_null( self::$dataCache ) ) {
431 global $wgLocalisationCacheConf;
432 $class = $wgLocalisationCacheConf['class'];
433 self::$dataCache = new $class( $wgLocalisationCacheConf );
435 return self::$dataCache;
438 function __construct() {
439 $this->mConverter = new FakeConverter( $this );
440 // Set the code to the name of the descendant
441 if ( get_class( $this ) == 'Language' ) {
442 $this->mCode = 'en';
443 } else {
444 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
446 self::getLocalisationCache();
450 * Reduce memory usage
452 function __destruct() {
453 foreach ( $this as $name => $value ) {
454 unset( $this->$name );
459 * Hook which will be called if this is the content language.
460 * Descendants can use this to register hook functions or modify globals
462 function initContLang() { }
465 * Same as getFallbacksFor for current language.
466 * @return array|bool
467 * @deprecated in 1.19
469 function getFallbackLanguageCode() {
470 wfDeprecated( __METHOD__, '1.19' );
471 return self::getFallbackFor( $this->mCode );
475 * @return array
476 * @since 1.19
478 function getFallbackLanguages() {
479 return self::getFallbacksFor( $this->mCode );
483 * Exports $wgBookstoreListEn
484 * @return array
486 function getBookstoreList() {
487 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
491 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
492 * available in localised form, it will be included in English.
494 * @return array
496 public function getNamespaces() {
497 if ( is_null( $this->namespaceNames ) ) {
498 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
500 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
501 $validNamespaces = MWNamespace::getCanonicalNamespaces();
503 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
505 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
506 if ( $wgMetaNamespaceTalk ) {
507 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
508 } else {
509 $talk = $this->namespaceNames[NS_PROJECT_TALK];
510 $this->namespaceNames[NS_PROJECT_TALK] =
511 $this->fixVariableInNamespace( $talk );
514 # Sometimes a language will be localised but not actually exist on this wiki.
515 foreach ( $this->namespaceNames as $key => $text ) {
516 if ( !isset( $validNamespaces[$key] ) ) {
517 unset( $this->namespaceNames[$key] );
521 # The above mixing may leave namespaces out of canonical order.
522 # Re-order by namespace ID number...
523 ksort( $this->namespaceNames );
525 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
527 return $this->namespaceNames;
531 * Arbitrarily set all of the namespace names at once. Mainly used for testing
532 * @param $namespaces Array of namespaces (id => name)
534 public function setNamespaces( array $namespaces ) {
535 $this->namespaceNames = $namespaces;
536 $this->mNamespaceIds = null;
540 * Resets all of the namespace caches. Mainly used for testing
542 public function resetNamespaces() {
543 $this->namespaceNames = null;
544 $this->mNamespaceIds = null;
545 $this->namespaceAliases = null;
549 * A convenience function that returns the same thing as
550 * getNamespaces() except with the array values changed to ' '
551 * where it found '_', useful for producing output to be displayed
552 * e.g. in <select> forms.
554 * @return array
556 function getFormattedNamespaces() {
557 $ns = $this->getNamespaces();
558 foreach ( $ns as $k => $v ) {
559 $ns[$k] = strtr( $v, '_', ' ' );
561 return $ns;
565 * Get a namespace value by key
566 * <code>
567 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
568 * echo $mw_ns; // prints 'MediaWiki'
569 * </code>
571 * @param $index Int: the array key of the namespace to return
572 * @return mixed, string if the namespace value exists, otherwise false
574 function getNsText( $index ) {
575 $ns = $this->getNamespaces();
576 return isset( $ns[$index] ) ? $ns[$index] : false;
580 * A convenience function that returns the same thing as
581 * getNsText() except with '_' changed to ' ', useful for
582 * producing output.
584 * <code>
585 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
586 * echo $mw_ns; // prints 'MediaWiki talk'
587 * </code>
589 * @param int $index The array key of the namespace to return
590 * @return string Namespace name without underscores (empty string if namespace does not exist)
592 function getFormattedNsText( $index ) {
593 $ns = $this->getNsText( $index );
594 return strtr( $ns, '_', ' ' );
598 * Returns gender-dependent namespace alias if available.
599 * @param $index Int: namespace index
600 * @param $gender String: gender key (male, female... )
601 * @return String
602 * @since 1.18
604 function getGenderNsText( $index, $gender ) {
605 global $wgExtraGenderNamespaces;
607 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
608 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
612 * Whether this language makes distinguishes genders for example in
613 * namespaces.
614 * @return bool
615 * @since 1.18
617 function needsGenderDistinction() {
618 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
619 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
620 // $wgExtraGenderNamespaces overrides everything
621 return true;
622 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
623 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
624 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
625 return false;
626 } else {
627 // Check what is in i18n files
628 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
629 return count( $aliases ) > 0;
634 * Get a namespace key by value, case insensitive.
635 * Only matches namespace names for the current language, not the
636 * canonical ones defined in Namespace.php.
638 * @param $text String
639 * @return mixed An integer if $text is a valid value otherwise false
641 function getLocalNsIndex( $text ) {
642 $lctext = $this->lc( $text );
643 $ids = $this->getNamespaceIds();
644 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
648 * @return array
650 function getNamespaceAliases() {
651 if ( is_null( $this->namespaceAliases ) ) {
652 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
653 if ( !$aliases ) {
654 $aliases = array();
655 } else {
656 foreach ( $aliases as $name => $index ) {
657 if ( $index === NS_PROJECT_TALK ) {
658 unset( $aliases[$name] );
659 $name = $this->fixVariableInNamespace( $name );
660 $aliases[$name] = $index;
665 global $wgExtraGenderNamespaces;
666 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
667 foreach ( $genders as $index => $forms ) {
668 foreach ( $forms as $alias ) {
669 $aliases[$alias] = $index;
673 $this->namespaceAliases = $aliases;
675 return $this->namespaceAliases;
679 * @return array
681 function getNamespaceIds() {
682 if ( is_null( $this->mNamespaceIds ) ) {
683 global $wgNamespaceAliases;
684 # Put namespace names and aliases into a hashtable.
685 # If this is too slow, then we should arrange it so that it is done
686 # before caching. The catch is that at pre-cache time, the above
687 # class-specific fixup hasn't been done.
688 $this->mNamespaceIds = array();
689 foreach ( $this->getNamespaces() as $index => $name ) {
690 $this->mNamespaceIds[$this->lc( $name )] = $index;
692 foreach ( $this->getNamespaceAliases() as $name => $index ) {
693 $this->mNamespaceIds[$this->lc( $name )] = $index;
695 if ( $wgNamespaceAliases ) {
696 foreach ( $wgNamespaceAliases as $name => $index ) {
697 $this->mNamespaceIds[$this->lc( $name )] = $index;
701 return $this->mNamespaceIds;
705 * Get a namespace key by value, case insensitive. Canonical namespace
706 * names override custom ones defined for the current language.
708 * @param $text String
709 * @return mixed An integer if $text is a valid value otherwise false
711 function getNsIndex( $text ) {
712 $lctext = $this->lc( $text );
713 $ns = MWNamespace::getCanonicalIndex( $lctext );
714 if ( $ns !== null ) {
715 return $ns;
717 $ids = $this->getNamespaceIds();
718 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
722 * short names for language variants used for language conversion links.
724 * @param $code String
725 * @param $usemsg bool Use the "variantname-xyz" message if it exists
726 * @return string
728 function getVariantname( $code, $usemsg = true ) {
729 $msg = "variantname-$code";
730 if ( $usemsg && wfMessage( $msg )->exists() ) {
731 return $this->getMessageFromDB( $msg );
733 $name = self::fetchLanguageName( $code );
734 if ( $name ) {
735 return $name; # if it's defined as a language name, show that
736 } else {
737 # otherwise, output the language code
738 return $code;
743 * @param $name string
744 * @return string
746 function specialPage( $name ) {
747 $aliases = $this->getSpecialPageAliases();
748 if ( isset( $aliases[$name][0] ) ) {
749 $name = $aliases[$name][0];
751 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
755 * @return array
757 function getDatePreferences() {
758 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
762 * @return array
764 function getDateFormats() {
765 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
769 * @return array|string
771 function getDefaultDateFormat() {
772 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
773 if ( $df === 'dmy or mdy' ) {
774 global $wgAmericanDates;
775 return $wgAmericanDates ? 'mdy' : 'dmy';
776 } else {
777 return $df;
782 * @return array
784 function getDatePreferenceMigrationMap() {
785 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
789 * @param $image
790 * @return array|null
792 function getImageFile( $image ) {
793 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
797 * @return array
799 function getExtraUserToggles() {
800 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
804 * @param $tog
805 * @return string
807 function getUserToggle( $tog ) {
808 return $this->getMessageFromDB( "tog-$tog" );
812 * Get native language names, indexed by code.
813 * Only those defined in MediaWiki, no other data like CLDR.
814 * If $customisedOnly is true, only returns codes with a messages file
816 * @param $customisedOnly bool
818 * @return array
819 * @deprecated in 1.20, use fetchLanguageNames()
821 public static function getLanguageNames( $customisedOnly = false ) {
822 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
826 * Get translated language names. This is done on best effort and
827 * by default this is exactly the same as Language::getLanguageNames.
828 * The CLDR extension provides translated names.
829 * @param $code String Language code.
830 * @return Array language code => language name
831 * @since 1.18.0
832 * @deprecated in 1.20, use fetchLanguageNames()
834 public static function getTranslatedLanguageNames( $code ) {
835 return self::fetchLanguageNames( $code, 'all' );
839 * Get an array of language names, indexed by code.
840 * @param $inLanguage null|string: Code of language in which to return the names
841 * Use null for autonyms (native names)
842 * @param $include string:
843 * 'all' all available languages
844 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
845 * 'mwfile' only if the language is in 'mw' *and* has a message file
846 * @return array: language code => language name
847 * @since 1.20
849 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
850 global $wgExtraLanguageNames;
851 static $coreLanguageNames;
853 if ( $coreLanguageNames === null ) {
854 include( MWInit::compiledPath( 'languages/Names.php' ) );
857 $names = array();
859 if ( $inLanguage ) {
860 # TODO: also include when $inLanguage is null, when this code is more efficient
861 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
864 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
865 foreach ( $mwNames as $mwCode => $mwName ) {
866 # - Prefer own MediaWiki native name when not using the hook
867 # - For other names just add if not added through the hook
868 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
869 $names[$mwCode] = $mwName;
873 if ( $include === 'all' ) {
874 return $names;
877 $returnMw = array();
878 $coreCodes = array_keys( $mwNames );
879 foreach ( $coreCodes as $coreCode ) {
880 $returnMw[$coreCode] = $names[$coreCode];
883 if ( $include === 'mwfile' ) {
884 $namesMwFile = array();
885 # We do this using a foreach over the codes instead of a directory
886 # loop so that messages files in extensions will work correctly.
887 foreach ( $returnMw as $code => $value ) {
888 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
889 $namesMwFile[$code] = $names[$code];
892 return $namesMwFile;
894 # 'mw' option; default if it's not one of the other two options (all/mwfile)
895 return $returnMw;
899 * @param $code string: The code of the language for which to get the name
900 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
901 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
902 * @return string: Language name or empty
903 * @since 1.20
905 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
906 $array = self::fetchLanguageNames( $inLanguage, $include );
907 return !array_key_exists( $code, $array ) ? '' : $array[$code];
911 * Get a message from the MediaWiki namespace.
913 * @param $msg String: message name
914 * @return string
916 function getMessageFromDB( $msg ) {
917 return wfMessage( $msg )->inLanguage( $this )->text();
921 * Get the native language name of $code.
922 * Only if defined in MediaWiki, no other data like CLDR.
923 * @param $code string
924 * @return string
925 * @deprecated in 1.20, use fetchLanguageName()
927 function getLanguageName( $code ) {
928 return self::fetchLanguageName( $code );
932 * @param $key string
933 * @return string
935 function getMonthName( $key ) {
936 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
940 * @return array
942 function getMonthNamesArray() {
943 $monthNames = array( '' );
944 for ( $i = 1; $i < 13; $i++ ) {
945 $monthNames[] = $this->getMonthName( $i );
947 return $monthNames;
951 * @param $key string
952 * @return string
954 function getMonthNameGen( $key ) {
955 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
959 * @param $key string
960 * @return string
962 function getMonthAbbreviation( $key ) {
963 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
967 * @return array
969 function getMonthAbbreviationsArray() {
970 $monthNames = array( '' );
971 for ( $i = 1; $i < 13; $i++ ) {
972 $monthNames[] = $this->getMonthAbbreviation( $i );
974 return $monthNames;
978 * @param $key string
979 * @return string
981 function getWeekdayName( $key ) {
982 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
986 * @param $key string
987 * @return string
989 function getWeekdayAbbreviation( $key ) {
990 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
994 * @param $key string
995 * @return string
997 function getIranianCalendarMonthName( $key ) {
998 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1002 * @param $key string
1003 * @return string
1005 function getHebrewCalendarMonthName( $key ) {
1006 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1010 * @param $key string
1011 * @return string
1013 function getHebrewCalendarMonthNameGen( $key ) {
1014 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1018 * @param $key string
1019 * @return string
1021 function getHijriCalendarMonthName( $key ) {
1022 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1026 * This is a workalike of PHP's date() function, but with better
1027 * internationalisation, a reduced set of format characters, and a better
1028 * escaping format.
1030 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1031 * the PHP manual for definitions. There are a number of extensions, which
1032 * start with "x":
1034 * xn Do not translate digits of the next numeric format character
1035 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1036 * xr Use roman numerals for the next numeric format character
1037 * xh Use hebrew numerals for the next numeric format character
1038 * xx Literal x
1039 * xg Genitive month name
1041 * xij j (day number) in Iranian calendar
1042 * xiF F (month name) in Iranian calendar
1043 * xin n (month number) in Iranian calendar
1044 * xiy y (two digit year) in Iranian calendar
1045 * xiY Y (full year) in Iranian calendar
1047 * xjj j (day number) in Hebrew calendar
1048 * xjF F (month name) in Hebrew calendar
1049 * xjt t (days in month) in Hebrew calendar
1050 * xjx xg (genitive month name) in Hebrew calendar
1051 * xjn n (month number) in Hebrew calendar
1052 * xjY Y (full year) in Hebrew calendar
1054 * xmj j (day number) in Hijri calendar
1055 * xmF F (month name) in Hijri calendar
1056 * xmn n (month number) in Hijri calendar
1057 * xmY Y (full year) in Hijri calendar
1059 * xkY Y (full year) in Thai solar calendar. Months and days are
1060 * identical to the Gregorian calendar
1061 * xoY Y (full year) in Minguo calendar or Juche year.
1062 * Months and days are identical to the
1063 * Gregorian calendar
1064 * xtY Y (full year) in Japanese nengo. Months and days are
1065 * identical to the Gregorian calendar
1067 * Characters enclosed in double quotes will be considered literal (with
1068 * the quotes themselves removed). Unmatched quotes will be considered
1069 * literal quotes. Example:
1071 * "The month is" F => The month is January
1072 * i's" => 20'11"
1074 * Backslash escaping is also supported.
1076 * Input timestamp is assumed to be pre-normalized to the desired local
1077 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1078 * $ts is UTC if $zone is not given.
1080 * @param $format String
1081 * @param $ts String: 14-character timestamp
1082 * YYYYMMDDHHMMSS
1083 * 01234567890123
1084 * @param $zone DateTimeZone: Timezone of $ts
1085 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1087 * @throws MWException
1088 * @return string
1090 function sprintfDate( $format, $ts, DateTimeZone $zone = null ) {
1091 $s = '';
1092 $raw = false;
1093 $roman = false;
1094 $hebrewNum = false;
1095 $dateTimeObj = false;
1096 $rawToggle = false;
1097 $iranian = false;
1098 $hebrew = false;
1099 $hijri = false;
1100 $thai = false;
1101 $minguo = false;
1102 $tenno = false;
1104 if ( strlen( $ts ) !== 14 ) {
1105 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1108 if ( !ctype_digit( $ts ) ) {
1109 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1112 for ( $p = 0; $p < strlen( $format ); $p++ ) {
1113 $num = false;
1114 $code = $format[$p];
1115 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1116 $code .= $format[++$p];
1119 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1120 $code .= $format[++$p];
1123 switch ( $code ) {
1124 case 'xx':
1125 $s .= 'x';
1126 break;
1127 case 'xn':
1128 $raw = true;
1129 break;
1130 case 'xN':
1131 $rawToggle = !$rawToggle;
1132 break;
1133 case 'xr':
1134 $roman = true;
1135 break;
1136 case 'xh':
1137 $hebrewNum = true;
1138 break;
1139 case 'xg':
1140 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1141 break;
1142 case 'xjx':
1143 if ( !$hebrew ) {
1144 $hebrew = self::tsToHebrew( $ts );
1146 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1147 break;
1148 case 'd':
1149 $num = substr( $ts, 6, 2 );
1150 break;
1151 case 'D':
1152 if ( !$dateTimeObj ) {
1153 $dateTimeObj = DateTime::createFromFormat(
1154 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1157 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) + 1 );
1158 break;
1159 case 'j':
1160 $num = intval( substr( $ts, 6, 2 ) );
1161 break;
1162 case 'xij':
1163 if ( !$iranian ) {
1164 $iranian = self::tsToIranian( $ts );
1166 $num = $iranian[2];
1167 break;
1168 case 'xmj':
1169 if ( !$hijri ) {
1170 $hijri = self::tsToHijri( $ts );
1172 $num = $hijri[2];
1173 break;
1174 case 'xjj':
1175 if ( !$hebrew ) {
1176 $hebrew = self::tsToHebrew( $ts );
1178 $num = $hebrew[2];
1179 break;
1180 case 'l':
1181 if ( !$dateTimeObj ) {
1182 $dateTimeObj = DateTime::createFromFormat(
1183 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1186 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) + 1 );
1187 break;
1188 case 'F':
1189 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1190 break;
1191 case 'xiF':
1192 if ( !$iranian ) {
1193 $iranian = self::tsToIranian( $ts );
1195 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1196 break;
1197 case 'xmF':
1198 if ( !$hijri ) {
1199 $hijri = self::tsToHijri( $ts );
1201 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1202 break;
1203 case 'xjF':
1204 if ( !$hebrew ) {
1205 $hebrew = self::tsToHebrew( $ts );
1207 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1208 break;
1209 case 'm':
1210 $num = substr( $ts, 4, 2 );
1211 break;
1212 case 'M':
1213 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1214 break;
1215 case 'n':
1216 $num = intval( substr( $ts, 4, 2 ) );
1217 break;
1218 case 'xin':
1219 if ( !$iranian ) {
1220 $iranian = self::tsToIranian( $ts );
1222 $num = $iranian[1];
1223 break;
1224 case 'xmn':
1225 if ( !$hijri ) {
1226 $hijri = self::tsToHijri ( $ts );
1228 $num = $hijri[1];
1229 break;
1230 case 'xjn':
1231 if ( !$hebrew ) {
1232 $hebrew = self::tsToHebrew( $ts );
1234 $num = $hebrew[1];
1235 break;
1236 case 'xjt':
1237 if ( !$hebrew ) {
1238 $hebrew = self::tsToHebrew( $ts );
1240 $num = $hebrew[3];
1241 break;
1242 case 'Y':
1243 $num = substr( $ts, 0, 4 );
1244 break;
1245 case 'xiY':
1246 if ( !$iranian ) {
1247 $iranian = self::tsToIranian( $ts );
1249 $num = $iranian[0];
1250 break;
1251 case 'xmY':
1252 if ( !$hijri ) {
1253 $hijri = self::tsToHijri( $ts );
1255 $num = $hijri[0];
1256 break;
1257 case 'xjY':
1258 if ( !$hebrew ) {
1259 $hebrew = self::tsToHebrew( $ts );
1261 $num = $hebrew[0];
1262 break;
1263 case 'xkY':
1264 if ( !$thai ) {
1265 $thai = self::tsToYear( $ts, 'thai' );
1267 $num = $thai[0];
1268 break;
1269 case 'xoY':
1270 if ( !$minguo ) {
1271 $minguo = self::tsToYear( $ts, 'minguo' );
1273 $num = $minguo[0];
1274 break;
1275 case 'xtY':
1276 if ( !$tenno ) {
1277 $tenno = self::tsToYear( $ts, 'tenno' );
1279 $num = $tenno[0];
1280 break;
1281 case 'y':
1282 $num = substr( $ts, 2, 2 );
1283 break;
1284 case 'xiy':
1285 if ( !$iranian ) {
1286 $iranian = self::tsToIranian( $ts );
1288 $num = substr( $iranian[0], -2 );
1289 break;
1290 case 'a':
1291 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1292 break;
1293 case 'A':
1294 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1295 break;
1296 case 'g':
1297 $h = substr( $ts, 8, 2 );
1298 $num = $h % 12 ? $h % 12 : 12;
1299 break;
1300 case 'G':
1301 $num = intval( substr( $ts, 8, 2 ) );
1302 break;
1303 case 'h':
1304 $h = substr( $ts, 8, 2 );
1305 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1306 break;
1307 case 'H':
1308 $num = substr( $ts, 8, 2 );
1309 break;
1310 case 'i':
1311 $num = substr( $ts, 10, 2 );
1312 break;
1313 case 's':
1314 $num = substr( $ts, 12, 2 );
1315 break;
1316 case 'c':
1317 case 'r':
1318 case 'e':
1319 case 'O':
1320 case 'P':
1321 case 'T':
1322 // Pass through string from $dateTimeObj->format()
1323 if ( !$dateTimeObj ) {
1324 $dateTimeObj = DateTime::createFromFormat(
1325 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1328 $s .= $dateTimeObj->format( $code );
1329 break;
1330 case 'w':
1331 case 'N':
1332 case 'z':
1333 case 'W':
1334 case 't':
1335 case 'L':
1336 case 'o':
1337 case 'U':
1338 case 'I':
1339 case 'Z':
1340 // Pass through number from $dateTimeObj->format()
1341 if ( !$dateTimeObj ) {
1342 $dateTimeObj = DateTime::createFromFormat(
1343 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1346 $num = $dateTimeObj->format( $code );
1347 break;
1348 case '\\':
1349 # Backslash escaping
1350 if ( $p < strlen( $format ) - 1 ) {
1351 $s .= $format[++$p];
1352 } else {
1353 $s .= '\\';
1355 break;
1356 case '"':
1357 # Quoted literal
1358 if ( $p < strlen( $format ) - 1 ) {
1359 $endQuote = strpos( $format, '"', $p + 1 );
1360 if ( $endQuote === false ) {
1361 # No terminating quote, assume literal "
1362 $s .= '"';
1363 } else {
1364 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1365 $p = $endQuote;
1367 } else {
1368 # Quote at end of string, assume literal "
1369 $s .= '"';
1371 break;
1372 default:
1373 $s .= $format[$p];
1375 if ( $num !== false ) {
1376 if ( $rawToggle || $raw ) {
1377 $s .= $num;
1378 $raw = false;
1379 } elseif ( $roman ) {
1380 $s .= Language::romanNumeral( $num );
1381 $roman = false;
1382 } elseif ( $hebrewNum ) {
1383 $s .= self::hebrewNumeral( $num );
1384 $hebrewNum = false;
1385 } else {
1386 $s .= $this->formatNum( $num, true );
1390 return $s;
1393 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1394 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1397 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1398 * Gregorian dates to Iranian dates. Originally written in C, it
1399 * is released under the terms of GNU Lesser General Public
1400 * License. Conversion to PHP was performed by Niklas Laxström.
1402 * Link: http://www.farsiweb.info/jalali/jalali.c
1404 * @param $ts string
1406 * @return string
1408 private static function tsToIranian( $ts ) {
1409 $gy = substr( $ts, 0, 4 ) -1600;
1410 $gm = substr( $ts, 4, 2 ) -1;
1411 $gd = substr( $ts, 6, 2 ) -1;
1413 # Days passed from the beginning (including leap years)
1414 $gDayNo = 365 * $gy
1415 + floor( ( $gy + 3 ) / 4 )
1416 - floor( ( $gy + 99 ) / 100 )
1417 + floor( ( $gy + 399 ) / 400 );
1419 // Add days of the past months of this year
1420 for ( $i = 0; $i < $gm; $i++ ) {
1421 $gDayNo += self::$GREG_DAYS[$i];
1424 // Leap years
1425 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1426 $gDayNo++;
1429 // Days passed in current month
1430 $gDayNo += (int)$gd;
1432 $jDayNo = $gDayNo - 79;
1434 $jNp = floor( $jDayNo / 12053 );
1435 $jDayNo %= 12053;
1437 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1438 $jDayNo %= 1461;
1440 if ( $jDayNo >= 366 ) {
1441 $jy += floor( ( $jDayNo - 1 ) / 365 );
1442 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1445 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1446 $jDayNo -= self::$IRANIAN_DAYS[$i];
1449 $jm = $i + 1;
1450 $jd = $jDayNo + 1;
1452 return array( $jy, $jm, $jd );
1456 * Converting Gregorian dates to Hijri dates.
1458 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1460 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1462 * @param $ts string
1464 * @return string
1466 private static function tsToHijri( $ts ) {
1467 $year = substr( $ts, 0, 4 );
1468 $month = substr( $ts, 4, 2 );
1469 $day = substr( $ts, 6, 2 );
1471 $zyr = $year;
1472 $zd = $day;
1473 $zm = $month;
1474 $zy = $zyr;
1476 if (
1477 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1478 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1481 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1482 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1483 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1484 $zd - 32075;
1485 } else {
1486 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1487 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1490 $zl = $zjd -1948440 + 10632;
1491 $zn = (int)( ( $zl - 1 ) / 10631 );
1492 $zl = $zl - 10631 * $zn + 354;
1493 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1494 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1495 $zm = (int)( ( 24 * $zl ) / 709 );
1496 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1497 $zy = 30 * $zn + $zj - 30;
1499 return array( $zy, $zm, $zd );
1503 * Converting Gregorian dates to Hebrew dates.
1505 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1506 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1507 * to translate the relevant functions into PHP and release them under
1508 * GNU GPL.
1510 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1511 * and Adar II is 14. In a non-leap year, Adar is 6.
1513 * @param $ts string
1515 * @return string
1517 private static function tsToHebrew( $ts ) {
1518 # Parse date
1519 $year = substr( $ts, 0, 4 );
1520 $month = substr( $ts, 4, 2 );
1521 $day = substr( $ts, 6, 2 );
1523 # Calculate Hebrew year
1524 $hebrewYear = $year + 3760;
1526 # Month number when September = 1, August = 12
1527 $month += 4;
1528 if ( $month > 12 ) {
1529 # Next year
1530 $month -= 12;
1531 $year++;
1532 $hebrewYear++;
1535 # Calculate day of year from 1 September
1536 $dayOfYear = $day;
1537 for ( $i = 1; $i < $month; $i++ ) {
1538 if ( $i == 6 ) {
1539 # February
1540 $dayOfYear += 28;
1541 # Check if the year is leap
1542 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1543 $dayOfYear++;
1545 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1546 $dayOfYear += 30;
1547 } else {
1548 $dayOfYear += 31;
1552 # Calculate the start of the Hebrew year
1553 $start = self::hebrewYearStart( $hebrewYear );
1555 # Calculate next year's start
1556 if ( $dayOfYear <= $start ) {
1557 # Day is before the start of the year - it is the previous year
1558 # Next year's start
1559 $nextStart = $start;
1560 # Previous year
1561 $year--;
1562 $hebrewYear--;
1563 # Add days since previous year's 1 September
1564 $dayOfYear += 365;
1565 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1566 # Leap year
1567 $dayOfYear++;
1569 # Start of the new (previous) year
1570 $start = self::hebrewYearStart( $hebrewYear );
1571 } else {
1572 # Next year's start
1573 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1576 # Calculate Hebrew day of year
1577 $hebrewDayOfYear = $dayOfYear - $start;
1579 # Difference between year's days
1580 $diff = $nextStart - $start;
1581 # Add 12 (or 13 for leap years) days to ignore the difference between
1582 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1583 # difference is only about the year type
1584 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1585 $diff += 13;
1586 } else {
1587 $diff += 12;
1590 # Check the year pattern, and is leap year
1591 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1592 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1593 # and non-leap years
1594 $yearPattern = $diff % 30;
1595 # Check if leap year
1596 $isLeap = $diff >= 30;
1598 # Calculate day in the month from number of day in the Hebrew year
1599 # Don't check Adar - if the day is not in Adar, we will stop before;
1600 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1601 $hebrewDay = $hebrewDayOfYear;
1602 $hebrewMonth = 1;
1603 $days = 0;
1604 while ( $hebrewMonth <= 12 ) {
1605 # Calculate days in this month
1606 if ( $isLeap && $hebrewMonth == 6 ) {
1607 # Adar in a leap year
1608 if ( $isLeap ) {
1609 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1610 $days = 30;
1611 if ( $hebrewDay <= $days ) {
1612 # Day in Adar I
1613 $hebrewMonth = 13;
1614 } else {
1615 # Subtract the days of Adar I
1616 $hebrewDay -= $days;
1617 # Try Adar II
1618 $days = 29;
1619 if ( $hebrewDay <= $days ) {
1620 # Day in Adar II
1621 $hebrewMonth = 14;
1625 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1626 # Cheshvan in a complete year (otherwise as the rule below)
1627 $days = 30;
1628 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1629 # Kislev in an incomplete year (otherwise as the rule below)
1630 $days = 29;
1631 } else {
1632 # Odd months have 30 days, even have 29
1633 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1635 if ( $hebrewDay <= $days ) {
1636 # In the current month
1637 break;
1638 } else {
1639 # Subtract the days of the current month
1640 $hebrewDay -= $days;
1641 # Try in the next month
1642 $hebrewMonth++;
1646 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1650 * This calculates the Hebrew year start, as days since 1 September.
1651 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1652 * Used for Hebrew date.
1654 * @param $year int
1656 * @return string
1658 private static function hebrewYearStart( $year ) {
1659 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1660 $b = intval( ( $year - 1 ) % 4 );
1661 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1662 if ( $m < 0 ) {
1663 $m--;
1665 $Mar = intval( $m );
1666 if ( $m < 0 ) {
1667 $m++;
1669 $m -= $Mar;
1671 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1672 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1673 $Mar++;
1674 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1675 $Mar += 2;
1676 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1677 $Mar++;
1680 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1681 return $Mar;
1685 * Algorithm to convert Gregorian dates to Thai solar dates,
1686 * Minguo dates or Minguo dates.
1688 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1689 * http://en.wikipedia.org/wiki/Minguo_calendar
1690 * http://en.wikipedia.org/wiki/Japanese_era_name
1692 * @param $ts String: 14-character timestamp
1693 * @param $cName String: calender name
1694 * @return Array: converted year, month, day
1696 private static function tsToYear( $ts, $cName ) {
1697 $gy = substr( $ts, 0, 4 );
1698 $gm = substr( $ts, 4, 2 );
1699 $gd = substr( $ts, 6, 2 );
1701 if ( !strcmp( $cName, 'thai' ) ) {
1702 # Thai solar dates
1703 # Add 543 years to the Gregorian calendar
1704 # Months and days are identical
1705 $gy_offset = $gy + 543;
1706 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1707 # Minguo dates
1708 # Deduct 1911 years from the Gregorian calendar
1709 # Months and days are identical
1710 $gy_offset = $gy - 1911;
1711 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1712 # Nengō dates up to Meiji period
1713 # Deduct years from the Gregorian calendar
1714 # depending on the nengo periods
1715 # Months and days are identical
1716 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1717 # Meiji period
1718 $gy_gannen = $gy - 1868 + 1;
1719 $gy_offset = $gy_gannen;
1720 if ( $gy_gannen == 1 ) {
1721 $gy_offset = '元';
1723 $gy_offset = '明治' . $gy_offset;
1724 } elseif (
1725 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1726 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1727 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1728 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1729 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1732 # Taishō period
1733 $gy_gannen = $gy - 1912 + 1;
1734 $gy_offset = $gy_gannen;
1735 if ( $gy_gannen == 1 ) {
1736 $gy_offset = '元';
1738 $gy_offset = '大正' . $gy_offset;
1739 } elseif (
1740 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1741 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1742 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1745 # Shōwa period
1746 $gy_gannen = $gy - 1926 + 1;
1747 $gy_offset = $gy_gannen;
1748 if ( $gy_gannen == 1 ) {
1749 $gy_offset = '元';
1751 $gy_offset = '昭和' . $gy_offset;
1752 } else {
1753 # Heisei period
1754 $gy_gannen = $gy - 1989 + 1;
1755 $gy_offset = $gy_gannen;
1756 if ( $gy_gannen == 1 ) {
1757 $gy_offset = '元';
1759 $gy_offset = '平成' . $gy_offset;
1761 } else {
1762 $gy_offset = $gy;
1765 return array( $gy_offset, $gm, $gd );
1769 * Roman number formatting up to 10000
1771 * @param $num int
1773 * @return string
1775 static function romanNumeral( $num ) {
1776 static $table = array(
1777 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1778 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1779 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1780 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1783 $num = intval( $num );
1784 if ( $num > 10000 || $num <= 0 ) {
1785 return $num;
1788 $s = '';
1789 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1790 if ( $num >= $pow10 ) {
1791 $s .= $table[$i][(int)floor( $num / $pow10 )];
1793 $num = $num % $pow10;
1795 return $s;
1799 * Hebrew Gematria number formatting up to 9999
1801 * @param $num int
1803 * @return string
1805 static function hebrewNumeral( $num ) {
1806 static $table = array(
1807 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1808 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1809 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1810 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1813 $num = intval( $num );
1814 if ( $num > 9999 || $num <= 0 ) {
1815 return $num;
1818 $s = '';
1819 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1820 if ( $num >= $pow10 ) {
1821 if ( $num == 15 || $num == 16 ) {
1822 $s .= $table[0][9] . $table[0][$num - 9];
1823 $num = 0;
1824 } else {
1825 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1826 if ( $pow10 == 1000 ) {
1827 $s .= "'";
1831 $num = $num % $pow10;
1833 if ( strlen( $s ) == 2 ) {
1834 $str = $s . "'";
1835 } else {
1836 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1837 $str .= substr( $s, strlen( $s ) - 2, 2 );
1839 $start = substr( $str, 0, strlen( $str ) - 2 );
1840 $end = substr( $str, strlen( $str ) - 2 );
1841 switch ( $end ) {
1842 case 'כ':
1843 $str = $start . 'ך';
1844 break;
1845 case 'מ':
1846 $str = $start . 'ם';
1847 break;
1848 case 'נ':
1849 $str = $start . 'ן';
1850 break;
1851 case 'פ':
1852 $str = $start . 'ף';
1853 break;
1854 case 'צ':
1855 $str = $start . 'ץ';
1856 break;
1858 return $str;
1862 * Used by date() and time() to adjust the time output.
1864 * @param $ts Int the time in date('YmdHis') format
1865 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1866 * get user timecorrection setting)
1867 * @return int
1869 function userAdjust( $ts, $tz = false ) {
1870 global $wgUser, $wgLocalTZoffset;
1872 if ( $tz === false ) {
1873 $tz = $wgUser->getOption( 'timecorrection' );
1876 $data = explode( '|', $tz, 3 );
1878 if ( $data[0] == 'ZoneInfo' ) {
1879 wfSuppressWarnings();
1880 $userTZ = timezone_open( $data[2] );
1881 wfRestoreWarnings();
1882 if ( $userTZ !== false ) {
1883 $date = date_create( $ts, timezone_open( 'UTC' ) );
1884 date_timezone_set( $date, $userTZ );
1885 $date = date_format( $date, 'YmdHis' );
1886 return $date;
1888 # Unrecognized timezone, default to 'Offset' with the stored offset.
1889 $data[0] = 'Offset';
1892 $minDiff = 0;
1893 if ( $data[0] == 'System' || $tz == '' ) {
1894 #  Global offset in minutes.
1895 if ( isset( $wgLocalTZoffset ) ) {
1896 $minDiff = $wgLocalTZoffset;
1898 } elseif ( $data[0] == 'Offset' ) {
1899 $minDiff = intval( $data[1] );
1900 } else {
1901 $data = explode( ':', $tz );
1902 if ( count( $data ) == 2 ) {
1903 $data[0] = intval( $data[0] );
1904 $data[1] = intval( $data[1] );
1905 $minDiff = abs( $data[0] ) * 60 + $data[1];
1906 if ( $data[0] < 0 ) {
1907 $minDiff = -$minDiff;
1909 } else {
1910 $minDiff = intval( $data[0] ) * 60;
1914 # No difference ? Return time unchanged
1915 if ( 0 == $minDiff ) {
1916 return $ts;
1919 wfSuppressWarnings(); // E_STRICT system time bitching
1920 # Generate an adjusted date; take advantage of the fact that mktime
1921 # will normalize out-of-range values so we don't have to split $minDiff
1922 # into hours and minutes.
1923 $t = mktime( (
1924 (int)substr( $ts, 8, 2 ) ), # Hours
1925 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1926 (int)substr( $ts, 12, 2 ), # Seconds
1927 (int)substr( $ts, 4, 2 ), # Month
1928 (int)substr( $ts, 6, 2 ), # Day
1929 (int)substr( $ts, 0, 4 ) ); # Year
1931 $date = date( 'YmdHis', $t );
1932 wfRestoreWarnings();
1934 return $date;
1938 * This is meant to be used by time(), date(), and timeanddate() to get
1939 * the date preference they're supposed to use, it should be used in
1940 * all children.
1942 *<code>
1943 * function timeanddate([...], $format = true) {
1944 * $datePreference = $this->dateFormat($format);
1945 * [...]
1947 *</code>
1949 * @param $usePrefs Mixed: if true, the user's preference is used
1950 * if false, the site/language default is used
1951 * if int/string, assumed to be a format.
1952 * @return string
1954 function dateFormat( $usePrefs = true ) {
1955 global $wgUser;
1957 if ( is_bool( $usePrefs ) ) {
1958 if ( $usePrefs ) {
1959 $datePreference = $wgUser->getDatePreference();
1960 } else {
1961 $datePreference = (string)User::getDefaultOption( 'date' );
1963 } else {
1964 $datePreference = (string)$usePrefs;
1967 // return int
1968 if ( $datePreference == '' ) {
1969 return 'default';
1972 return $datePreference;
1976 * Get a format string for a given type and preference
1977 * @param $type string May be date, time or both
1978 * @param $pref string The format name as it appears in Messages*.php
1980 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1982 * @return string
1984 function getDateFormatString( $type, $pref ) {
1985 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1986 if ( $pref == 'default' ) {
1987 $pref = $this->getDefaultDateFormat();
1988 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1989 } else {
1990 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1992 if ( $type === 'pretty' && $df === null ) {
1993 $df = $this->getDateFormatString( 'date', $pref );
1996 if ( $df === null ) {
1997 $pref = $this->getDefaultDateFormat();
1998 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2001 $this->dateFormatStrings[$type][$pref] = $df;
2003 return $this->dateFormatStrings[$type][$pref];
2007 * @param $ts Mixed: the time format which needs to be turned into a
2008 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2009 * @param $adj Bool: whether to adjust the time output according to the
2010 * user configured offset ($timecorrection)
2011 * @param $format Mixed: true to use user's date format preference
2012 * @param $timecorrection String|bool the time offset as returned by
2013 * validateTimeZone() in Special:Preferences
2014 * @return string
2016 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2017 $ts = wfTimestamp( TS_MW, $ts );
2018 if ( $adj ) {
2019 $ts = $this->userAdjust( $ts, $timecorrection );
2021 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2022 return $this->sprintfDate( $df, $ts );
2026 * @param $ts Mixed: the time format which needs to be turned into a
2027 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2028 * @param $adj Bool: whether to adjust the time output according to the
2029 * user configured offset ($timecorrection)
2030 * @param $format Mixed: true to use user's date format preference
2031 * @param $timecorrection String|bool the time offset as returned by
2032 * validateTimeZone() in Special:Preferences
2033 * @return string
2035 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2036 $ts = wfTimestamp( TS_MW, $ts );
2037 if ( $adj ) {
2038 $ts = $this->userAdjust( $ts, $timecorrection );
2040 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2041 return $this->sprintfDate( $df, $ts );
2045 * @param $ts Mixed: the time format which needs to be turned into a
2046 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2047 * @param $adj Bool: whether to adjust the time output according to the
2048 * user configured offset ($timecorrection)
2049 * @param $format Mixed: what format to return, if it's false output the
2050 * default one (default true)
2051 * @param $timecorrection String|bool the time offset as returned by
2052 * validateTimeZone() in Special:Preferences
2053 * @return string
2055 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2056 $ts = wfTimestamp( TS_MW, $ts );
2057 if ( $adj ) {
2058 $ts = $this->userAdjust( $ts, $timecorrection );
2060 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2061 return $this->sprintfDate( $df, $ts );
2065 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2067 * @since 1.20
2069 * @param integer $seconds The amount of seconds.
2070 * @param array $chosenIntervals The intervals to enable.
2072 * @return string
2074 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2075 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2077 $segments = array();
2079 foreach ( $intervals as $intervalName => $intervalValue ) {
2080 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2081 $segments[] = $message->inLanguage( $this )->escaped();
2084 return $this->listToText( $segments );
2088 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2089 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2091 * @since 1.20
2093 * @param integer $seconds The amount of seconds.
2094 * @param array $chosenIntervals The intervals to enable.
2096 * @return array
2098 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2099 if ( empty( $chosenIntervals ) ) {
2100 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2103 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2104 $sortedNames = array_keys( $intervals );
2105 $smallestInterval = array_pop( $sortedNames );
2107 $segments = array();
2109 foreach ( $intervals as $name => $length ) {
2110 $value = floor( $seconds / $length );
2112 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2113 $seconds -= $value * $length;
2114 $segments[$name] = $value;
2118 return $segments;
2122 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2124 * @param $type String: can be 'date', 'time' or 'both'
2125 * @param $ts Mixed: the time format which needs to be turned into a
2126 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2127 * @param $user User object used to get preferences for timezone and format
2128 * @param $options Array, can contain the following keys:
2129 * - 'timecorrection': time correction, can have the following values:
2130 * - true: use user's preference
2131 * - false: don't use time correction
2132 * - integer: value of time correction in minutes
2133 * - 'format': format to use, can have the following values:
2134 * - true: use user's preference
2135 * - false: use default preference
2136 * - string: format to use
2137 * @since 1.19
2138 * @return String
2140 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2141 $ts = wfTimestamp( TS_MW, $ts );
2142 $options += array( 'timecorrection' => true, 'format' => true );
2143 if ( $options['timecorrection'] !== false ) {
2144 if ( $options['timecorrection'] === true ) {
2145 $offset = $user->getOption( 'timecorrection' );
2146 } else {
2147 $offset = $options['timecorrection'];
2149 $ts = $this->userAdjust( $ts, $offset );
2151 if ( $options['format'] === true ) {
2152 $format = $user->getDatePreference();
2153 } else {
2154 $format = $options['format'];
2156 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2157 return $this->sprintfDate( $df, $ts );
2161 * Get the formatted date for the given timestamp and formatted for
2162 * the given user.
2164 * @param $ts Mixed: the time format which needs to be turned into a
2165 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2166 * @param $user User object used to get preferences for timezone and format
2167 * @param $options Array, can contain the following keys:
2168 * - 'timecorrection': time correction, can have the following values:
2169 * - true: use user's preference
2170 * - false: don't use time correction
2171 * - integer: value of time correction in minutes
2172 * - 'format': format to use, can have the following values:
2173 * - true: use user's preference
2174 * - false: use default preference
2175 * - string: format to use
2176 * @since 1.19
2177 * @return String
2179 public function userDate( $ts, User $user, array $options = array() ) {
2180 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2184 * Get the formatted time for the given timestamp and formatted for
2185 * the given user.
2187 * @param $ts Mixed: the time format which needs to be turned into a
2188 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2189 * @param $user User object used to get preferences for timezone and format
2190 * @param $options Array, can contain the following keys:
2191 * - 'timecorrection': time correction, can have the following values:
2192 * - true: use user's preference
2193 * - false: don't use time correction
2194 * - integer: value of time correction in minutes
2195 * - 'format': format to use, can have the following values:
2196 * - true: use user's preference
2197 * - false: use default preference
2198 * - string: format to use
2199 * @since 1.19
2200 * @return String
2202 public function userTime( $ts, User $user, array $options = array() ) {
2203 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2207 * Get the formatted date and time for the given timestamp and formatted for
2208 * the given user.
2210 * @param $ts Mixed: the time format which needs to be turned into a
2211 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2212 * @param $user User object used to get preferences for timezone and format
2213 * @param $options Array, can contain the following keys:
2214 * - 'timecorrection': time correction, can have the following values:
2215 * - true: use user's preference
2216 * - false: don't use time correction
2217 * - integer: value of time correction in minutes
2218 * - 'format': format to use, can have the following values:
2219 * - true: use user's preference
2220 * - false: use default preference
2221 * - string: format to use
2222 * @since 1.19
2223 * @return String
2225 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2226 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2230 * Convert an MWTimestamp into a pretty human-readable timestamp using
2231 * the given user preferences and relative base time.
2233 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2234 * on your timestamp object, which will then call this function. Calling
2235 * this function directly will cause hooks to be skipped over.
2237 * @see MWTimestamp::getHumanTimestamp
2238 * @param MWTimestamp $ts Timestamp to prettify
2239 * @param MWTimestamp $relativeTo Base timestamp
2240 * @param User $user User preferences to use
2241 * @return string Human timestamp
2242 * @since 1.21
2244 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2245 $diff = $ts->diff( $relativeTo );
2246 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) - (int)$relativeTo->timestamp->format( 'w' ) );
2247 $days = $diff->days ?: (int)$diffDay;
2248 if ( $diff->invert || $days > 5 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' ) ) {
2249 // Timestamps are in different years: use full timestamp
2250 // Also do full timestamp for future dates
2252 * @FIXME Add better handling of future timestamps.
2254 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2255 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2256 } elseif ( $days > 5 ) {
2257 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2258 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2259 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2260 } elseif ( $days > 1 ) {
2261 // Timestamp within the past week: show the day of the week and time
2262 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2263 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2264 $ts = wfMessage( "$weekday-at" )
2265 ->inLanguage( $this )
2266 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2267 ->text();
2268 } elseif ( $days == 1 ) {
2269 // Timestamp was yesterday: say 'yesterday' and the time.
2270 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2271 $ts = wfMessage( 'yesterday-at' )
2272 ->inLanguage( $this )
2273 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2274 ->text();
2275 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2276 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2277 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2278 $ts = wfMessage( 'today-at' )
2279 ->inLanguage( $this )
2280 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2281 ->text();
2283 // From here on in, the timestamp was soon enough ago so that we can simply say
2284 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2285 } elseif ( $diff->h == 1 ) {
2286 // Less than 90 minutes, but more than an hour ago.
2287 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2288 } elseif ( $diff->i >= 1 ) {
2289 // A few minutes ago.
2290 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2291 } elseif ( $diff->s >= 30 ) {
2292 // Less than a minute, but more than 30 sec ago.
2293 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2294 } else {
2295 // Less than 30 seconds ago.
2296 $ts = wfMessage( 'just-now' )->text();
2299 return $ts;
2303 * @param $key string
2304 * @return array|null
2306 function getMessage( $key ) {
2307 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2311 * @return array
2313 function getAllMessages() {
2314 return self::$dataCache->getItem( $this->mCode, 'messages' );
2318 * @param $in
2319 * @param $out
2320 * @param $string
2321 * @return string
2323 function iconv( $in, $out, $string ) {
2324 # This is a wrapper for iconv in all languages except esperanto,
2325 # which does some nasty x-conversions beforehand
2327 # Even with //IGNORE iconv can whine about illegal characters in
2328 # *input* string. We just ignore those too.
2329 # REF: http://bugs.php.net/bug.php?id=37166
2330 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2331 wfSuppressWarnings();
2332 $text = iconv( $in, $out . '//IGNORE', $string );
2333 wfRestoreWarnings();
2334 return $text;
2337 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2340 * @param $matches array
2341 * @return mixed|string
2343 function ucwordbreaksCallbackAscii( $matches ) {
2344 return $this->ucfirst( $matches[1] );
2348 * @param $matches array
2349 * @return string
2351 function ucwordbreaksCallbackMB( $matches ) {
2352 return mb_strtoupper( $matches[0] );
2356 * @param $matches array
2357 * @return string
2359 function ucCallback( $matches ) {
2360 list( $wikiUpperChars ) = self::getCaseMaps();
2361 return strtr( $matches[1], $wikiUpperChars );
2365 * @param $matches array
2366 * @return string
2368 function lcCallback( $matches ) {
2369 list( , $wikiLowerChars ) = self::getCaseMaps();
2370 return strtr( $matches[1], $wikiLowerChars );
2374 * @param $matches array
2375 * @return string
2377 function ucwordsCallbackMB( $matches ) {
2378 return mb_strtoupper( $matches[0] );
2382 * @param $matches array
2383 * @return string
2385 function ucwordsCallbackWiki( $matches ) {
2386 list( $wikiUpperChars ) = self::getCaseMaps();
2387 return strtr( $matches[0], $wikiUpperChars );
2391 * Make a string's first character uppercase
2393 * @param $str string
2395 * @return string
2397 function ucfirst( $str ) {
2398 $o = ord( $str );
2399 if ( $o < 96 ) { // if already uppercase...
2400 return $str;
2401 } elseif ( $o < 128 ) {
2402 return ucfirst( $str ); // use PHP's ucfirst()
2403 } else {
2404 // fall back to more complex logic in case of multibyte strings
2405 return $this->uc( $str, true );
2410 * Convert a string to uppercase
2412 * @param $str string
2413 * @param $first bool
2415 * @return string
2417 function uc( $str, $first = false ) {
2418 if ( function_exists( 'mb_strtoupper' ) ) {
2419 if ( $first ) {
2420 if ( $this->isMultibyte( $str ) ) {
2421 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2422 } else {
2423 return ucfirst( $str );
2425 } else {
2426 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2428 } else {
2429 if ( $this->isMultibyte( $str ) ) {
2430 $x = $first ? '^' : '';
2431 return preg_replace_callback(
2432 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2433 array( $this, 'ucCallback' ),
2434 $str
2436 } else {
2437 return $first ? ucfirst( $str ) : strtoupper( $str );
2443 * @param $str string
2444 * @return mixed|string
2446 function lcfirst( $str ) {
2447 $o = ord( $str );
2448 if ( !$o ) {
2449 return strval( $str );
2450 } elseif ( $o >= 128 ) {
2451 return $this->lc( $str, true );
2452 } elseif ( $o > 96 ) {
2453 return $str;
2454 } else {
2455 $str[0] = strtolower( $str[0] );
2456 return $str;
2461 * @param $str string
2462 * @param $first bool
2463 * @return mixed|string
2465 function lc( $str, $first = false ) {
2466 if ( function_exists( 'mb_strtolower' ) ) {
2467 if ( $first ) {
2468 if ( $this->isMultibyte( $str ) ) {
2469 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2470 } else {
2471 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2473 } else {
2474 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2476 } else {
2477 if ( $this->isMultibyte( $str ) ) {
2478 $x = $first ? '^' : '';
2479 return preg_replace_callback(
2480 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2481 array( $this, 'lcCallback' ),
2482 $str
2484 } else {
2485 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2491 * @param $str string
2492 * @return bool
2494 function isMultibyte( $str ) {
2495 return (bool)preg_match( '/[\x80-\xff]/', $str );
2499 * @param $str string
2500 * @return mixed|string
2502 function ucwords( $str ) {
2503 if ( $this->isMultibyte( $str ) ) {
2504 $str = $this->lc( $str );
2506 // regexp to find first letter in each word (i.e. after each space)
2507 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2509 // function to use to capitalize a single char
2510 if ( function_exists( 'mb_strtoupper' ) ) {
2511 return preg_replace_callback(
2512 $replaceRegexp,
2513 array( $this, 'ucwordsCallbackMB' ),
2514 $str
2516 } else {
2517 return preg_replace_callback(
2518 $replaceRegexp,
2519 array( $this, 'ucwordsCallbackWiki' ),
2520 $str
2523 } else {
2524 return ucwords( strtolower( $str ) );
2529 * capitalize words at word breaks
2531 * @param $str string
2532 * @return mixed
2534 function ucwordbreaks( $str ) {
2535 if ( $this->isMultibyte( $str ) ) {
2536 $str = $this->lc( $str );
2538 // since \b doesn't work for UTF-8, we explicitely define word break chars
2539 $breaks = "[ \-\(\)\}\{\.,\?!]";
2541 // find first letter after word break
2542 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2544 if ( function_exists( 'mb_strtoupper' ) ) {
2545 return preg_replace_callback(
2546 $replaceRegexp,
2547 array( $this, 'ucwordbreaksCallbackMB' ),
2548 $str
2550 } else {
2551 return preg_replace_callback(
2552 $replaceRegexp,
2553 array( $this, 'ucwordsCallbackWiki' ),
2554 $str
2557 } else {
2558 return preg_replace_callback(
2559 '/\b([\w\x80-\xff]+)\b/',
2560 array( $this, 'ucwordbreaksCallbackAscii' ),
2561 $str
2567 * Return a case-folded representation of $s
2569 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2570 * and $s2 are the same except for the case of their characters. It is not
2571 * necessary for the value returned to make sense when displayed.
2573 * Do *not* perform any other normalisation in this function. If a caller
2574 * uses this function when it should be using a more general normalisation
2575 * function, then fix the caller.
2577 * @param $s string
2579 * @return string
2581 function caseFold( $s ) {
2582 return $this->uc( $s );
2586 * @param $s string
2587 * @return string
2589 function checkTitleEncoding( $s ) {
2590 if ( is_array( $s ) ) {
2591 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2593 if ( StringUtils::isUtf8( $s ) ) {
2594 return $s;
2597 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2601 * @return array
2603 function fallback8bitEncoding() {
2604 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2608 * Most writing systems use whitespace to break up words.
2609 * Some languages such as Chinese don't conventionally do this,
2610 * which requires special handling when breaking up words for
2611 * searching etc.
2613 * @return bool
2615 function hasWordBreaks() {
2616 return true;
2620 * Some languages such as Chinese require word segmentation,
2621 * Specify such segmentation when overridden in derived class.
2623 * @param $string String
2624 * @return String
2626 function segmentByWord( $string ) {
2627 return $string;
2631 * Some languages have special punctuation need to be normalized.
2632 * Make such changes here.
2634 * @param $string String
2635 * @return String
2637 function normalizeForSearch( $string ) {
2638 return self::convertDoubleWidth( $string );
2642 * convert double-width roman characters to single-width.
2643 * range: ff00-ff5f ~= 0020-007f
2645 * @param $string string
2647 * @return string
2649 protected static function convertDoubleWidth( $string ) {
2650 static $full = null;
2651 static $half = null;
2653 if ( $full === null ) {
2654 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2655 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2656 $full = str_split( $fullWidth, 3 );
2657 $half = str_split( $halfWidth );
2660 $string = str_replace( $full, $half, $string );
2661 return $string;
2665 * @param $string string
2666 * @param $pattern string
2667 * @return string
2669 protected static function insertSpace( $string, $pattern ) {
2670 $string = preg_replace( $pattern, " $1 ", $string );
2671 $string = preg_replace( '/ +/', ' ', $string );
2672 return $string;
2676 * @param $termsArray array
2677 * @return array
2679 function convertForSearchResult( $termsArray ) {
2680 # some languages, e.g. Chinese, need to do a conversion
2681 # in order for search results to be displayed correctly
2682 return $termsArray;
2686 * Get the first character of a string.
2688 * @param $s string
2689 * @return string
2691 function firstChar( $s ) {
2692 $matches = array();
2693 preg_match(
2694 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2695 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2697 $matches
2700 if ( isset( $matches[1] ) ) {
2701 if ( strlen( $matches[1] ) != 3 ) {
2702 return $matches[1];
2705 // Break down Hangul syllables to grab the first jamo
2706 $code = utf8ToCodepoint( $matches[1] );
2707 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2708 return $matches[1];
2709 } elseif ( $code < 0xb098 ) {
2710 return "\xe3\x84\xb1";
2711 } elseif ( $code < 0xb2e4 ) {
2712 return "\xe3\x84\xb4";
2713 } elseif ( $code < 0xb77c ) {
2714 return "\xe3\x84\xb7";
2715 } elseif ( $code < 0xb9c8 ) {
2716 return "\xe3\x84\xb9";
2717 } elseif ( $code < 0xbc14 ) {
2718 return "\xe3\x85\x81";
2719 } elseif ( $code < 0xc0ac ) {
2720 return "\xe3\x85\x82";
2721 } elseif ( $code < 0xc544 ) {
2722 return "\xe3\x85\x85";
2723 } elseif ( $code < 0xc790 ) {
2724 return "\xe3\x85\x87";
2725 } elseif ( $code < 0xcc28 ) {
2726 return "\xe3\x85\x88";
2727 } elseif ( $code < 0xce74 ) {
2728 return "\xe3\x85\x8a";
2729 } elseif ( $code < 0xd0c0 ) {
2730 return "\xe3\x85\x8b";
2731 } elseif ( $code < 0xd30c ) {
2732 return "\xe3\x85\x8c";
2733 } elseif ( $code < 0xd558 ) {
2734 return "\xe3\x85\x8d";
2735 } else {
2736 return "\xe3\x85\x8e";
2738 } else {
2739 return '';
2743 function initEncoding() {
2744 # Some languages may have an alternate char encoding option
2745 # (Esperanto X-coding, Japanese furigana conversion, etc)
2746 # If this language is used as the primary content language,
2747 # an override to the defaults can be set here on startup.
2751 * @param $s string
2752 * @return string
2754 function recodeForEdit( $s ) {
2755 # For some languages we'll want to explicitly specify
2756 # which characters make it into the edit box raw
2757 # or are converted in some way or another.
2758 global $wgEditEncoding;
2759 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2760 return $s;
2761 } else {
2762 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2767 * @param $s string
2768 * @return string
2770 function recodeInput( $s ) {
2771 # Take the previous into account.
2772 global $wgEditEncoding;
2773 if ( $wgEditEncoding != '' ) {
2774 $enc = $wgEditEncoding;
2775 } else {
2776 $enc = 'UTF-8';
2778 if ( $enc == 'UTF-8' ) {
2779 return $s;
2780 } else {
2781 return $this->iconv( $enc, 'UTF-8', $s );
2786 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2787 * also cleans up certain backwards-compatible sequences, converting them
2788 * to the modern Unicode equivalent.
2790 * This is language-specific for performance reasons only.
2792 * @param $s string
2794 * @return string
2796 function normalize( $s ) {
2797 global $wgAllUnicodeFixes;
2798 $s = UtfNormal::cleanUp( $s );
2799 if ( $wgAllUnicodeFixes ) {
2800 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2801 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2804 return $s;
2808 * Transform a string using serialized data stored in the given file (which
2809 * must be in the serialized subdirectory of $IP). The file contains pairs
2810 * mapping source characters to destination characters.
2812 * The data is cached in process memory. This will go faster if you have the
2813 * FastStringSearch extension.
2815 * @param $file string
2816 * @param $string string
2818 * @throws MWException
2819 * @return string
2821 function transformUsingPairFile( $file, $string ) {
2822 if ( !isset( $this->transformData[$file] ) ) {
2823 $data = wfGetPrecompiledData( $file );
2824 if ( $data === false ) {
2825 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2827 $this->transformData[$file] = new ReplacementArray( $data );
2829 return $this->transformData[$file]->replace( $string );
2833 * For right-to-left language support
2835 * @return bool
2837 function isRTL() {
2838 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2842 * Return the correct HTML 'dir' attribute value for this language.
2843 * @return String
2845 function getDir() {
2846 return $this->isRTL() ? 'rtl' : 'ltr';
2850 * Return 'left' or 'right' as appropriate alignment for line-start
2851 * for this language's text direction.
2853 * Should be equivalent to CSS3 'start' text-align value....
2855 * @return String
2857 function alignStart() {
2858 return $this->isRTL() ? 'right' : 'left';
2862 * Return 'right' or 'left' as appropriate alignment for line-end
2863 * for this language's text direction.
2865 * Should be equivalent to CSS3 'end' text-align value....
2867 * @return String
2869 function alignEnd() {
2870 return $this->isRTL() ? 'left' : 'right';
2874 * A hidden direction mark (LRM or RLM), depending on the language direction.
2875 * Unlike getDirMark(), this function returns the character as an HTML entity.
2876 * This function should be used when the output is guaranteed to be HTML,
2877 * because it makes the output HTML source code more readable. When
2878 * the output is plain text or can be escaped, getDirMark() should be used.
2880 * @param $opposite Boolean Get the direction mark opposite to your language
2881 * @return string
2882 * @since 1.20
2884 function getDirMarkEntity( $opposite = false ) {
2885 if ( $opposite ) {
2886 return $this->isRTL() ? '&lrm;' : '&rlm;';
2888 return $this->isRTL() ? '&rlm;' : '&lrm;';
2892 * A hidden direction mark (LRM or RLM), depending on the language direction.
2893 * This function produces them as invisible Unicode characters and
2894 * the output may be hard to read and debug, so it should only be used
2895 * when the output is plain text or can be escaped. When the output is
2896 * HTML, use getDirMarkEntity() instead.
2898 * @param $opposite Boolean Get the direction mark opposite to your language
2899 * @return string
2901 function getDirMark( $opposite = false ) {
2902 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2903 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2904 if ( $opposite ) {
2905 return $this->isRTL() ? $lrm : $rlm;
2907 return $this->isRTL() ? $rlm : $lrm;
2911 * @return array
2913 function capitalizeAllNouns() {
2914 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2918 * An arrow, depending on the language direction.
2920 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2921 * @return string
2923 function getArrow( $direction = 'forwards' ) {
2924 switch ( $direction ) {
2925 case 'forwards':
2926 return $this->isRTL() ? '←' : '→';
2927 case 'backwards':
2928 return $this->isRTL() ? '→' : '←';
2929 case 'left':
2930 return '←';
2931 case 'right':
2932 return '→';
2933 case 'up':
2934 return '↑';
2935 case 'down':
2936 return '↓';
2941 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2943 * @return bool
2945 function linkPrefixExtension() {
2946 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2950 * @return array
2952 function getMagicWords() {
2953 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2956 protected function doMagicHook() {
2957 if ( $this->mMagicHookDone ) {
2958 return;
2960 $this->mMagicHookDone = true;
2961 wfProfileIn( 'LanguageGetMagic' );
2962 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2963 wfProfileOut( 'LanguageGetMagic' );
2967 * Fill a MagicWord object with data from here
2969 * @param $mw
2971 function getMagic( $mw ) {
2972 $this->doMagicHook();
2974 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2975 $rawEntry = $this->mMagicExtensions[$mw->mId];
2976 } else {
2977 $magicWords = $this->getMagicWords();
2978 if ( isset( $magicWords[$mw->mId] ) ) {
2979 $rawEntry = $magicWords[$mw->mId];
2980 } else {
2981 $rawEntry = false;
2985 if ( !is_array( $rawEntry ) ) {
2986 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2987 } else {
2988 $mw->mCaseSensitive = $rawEntry[0];
2989 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2994 * Add magic words to the extension array
2996 * @param $newWords array
2998 function addMagicWordsByLang( $newWords ) {
2999 $fallbackChain = $this->getFallbackLanguages();
3000 $fallbackChain = array_reverse( $fallbackChain );
3001 foreach ( $fallbackChain as $code ) {
3002 if ( isset( $newWords[$code] ) ) {
3003 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3009 * Get special page names, as an associative array
3010 * case folded alias => real name
3012 function getSpecialPageAliases() {
3013 // Cache aliases because it may be slow to load them
3014 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3015 // Initialise array
3016 $this->mExtendedSpecialPageAliases =
3017 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3018 wfRunHooks( 'LanguageGetSpecialPageAliases',
3019 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3022 return $this->mExtendedSpecialPageAliases;
3026 * Italic is unsuitable for some languages
3028 * @param $text String: the text to be emphasized.
3029 * @return string
3031 function emphasize( $text ) {
3032 return "<em>$text</em>";
3036 * Normally we output all numbers in plain en_US style, that is
3037 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3038 * point twohundredthirtyfive. However this is not suitable for all
3039 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3040 * Icelandic just want to use commas instead of dots, and dots instead
3041 * of commas like "293.291,235".
3043 * An example of this function being called:
3044 * <code>
3045 * wfMessage( 'message' )->numParams( $num )->text()
3046 * </code>
3048 * See LanguageGu.php for the Gujarati implementation and
3049 * $separatorTransformTable on MessageIs.php for
3050 * the , => . and . => , implementation.
3052 * @todo check if it's viable to use localeconv() for the decimal
3053 * separator thing.
3054 * @param $number Mixed: the string to be formatted, should be an integer
3055 * or a floating point number.
3056 * @param $nocommafy Bool: set to true for special numbers like dates
3057 * @return string
3059 public function formatNum( $number, $nocommafy = false ) {
3060 global $wgTranslateNumerals;
3061 if ( !$nocommafy ) {
3062 $number = $this->commafy( $number );
3063 $s = $this->separatorTransformTable();
3064 if ( $s ) {
3065 $number = strtr( $number, $s );
3069 if ( $wgTranslateNumerals ) {
3070 $s = $this->digitTransformTable();
3071 if ( $s ) {
3072 $number = strtr( $number, $s );
3076 return $number;
3080 * Front-end for non-commafied formatNum
3082 * @param mixed $number the string to be formatted, should be an integer
3083 * or a floating point number.
3084 * @since 1.21
3085 * @return string
3087 public function formatNumNoSeparators( $number ) {
3088 return $this->formatNum( $number, true );
3092 * @param $number string
3093 * @return string
3095 function parseFormattedNumber( $number ) {
3096 $s = $this->digitTransformTable();
3097 if ( $s ) {
3098 $number = strtr( $number, array_flip( $s ) );
3101 $s = $this->separatorTransformTable();
3102 if ( $s ) {
3103 $number = strtr( $number, array_flip( $s ) );
3106 $number = strtr( $number, array( ',' => '' ) );
3107 return $number;
3111 * Adds commas to a given number
3112 * @since 1.19
3113 * @param $number mixed
3114 * @return string
3116 function commafy( $number ) {
3117 $digitGroupingPattern = $this->digitGroupingPattern();
3118 if ( $number === null ) {
3119 return '';
3122 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3123 // default grouping is at thousands, use the same for ###,###,### pattern too.
3124 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3125 } else {
3126 // Ref: http://cldr.unicode.org/translation/number-patterns
3127 $sign = "";
3128 if ( intval( $number ) < 0 ) {
3129 // For negative numbers apply the algorithm like positive number and add sign.
3130 $sign = "-";
3131 $number = substr( $number, 1 );
3133 $integerPart = array();
3134 $decimalPart = array();
3135 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3136 preg_match( "/\d+/", $number, $integerPart );
3137 preg_match( "/\.\d*/", $number, $decimalPart );
3138 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3139 if ( $groupedNumber === $number ) {
3140 // the string does not have any number part. Eg: .12345
3141 return $sign . $groupedNumber;
3143 $start = $end = strlen( $integerPart[0] );
3144 while ( $start > 0 ) {
3145 $match = $matches[0][$numMatches - 1];
3146 $matchLen = strlen( $match );
3147 $start = $end - $matchLen;
3148 if ( $start < 0 ) {
3149 $start = 0;
3151 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3152 $end = $start;
3153 if ( $numMatches > 1 ) {
3154 // use the last pattern for the rest of the number
3155 $numMatches--;
3157 if ( $start > 0 ) {
3158 $groupedNumber = "," . $groupedNumber;
3161 return $sign . $groupedNumber;
3166 * @return String
3168 function digitGroupingPattern() {
3169 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3173 * @return array
3175 function digitTransformTable() {
3176 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3180 * @return array
3182 function separatorTransformTable() {
3183 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3187 * Take a list of strings and build a locale-friendly comma-separated
3188 * list, using the local comma-separator message.
3189 * The last two strings are chained with an "and".
3190 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3192 * @param $l Array
3193 * @return string
3195 function listToText( array $l ) {
3196 $m = count( $l ) - 1;
3197 if ( $m < 0 ) {
3198 return '';
3200 if ( $m > 0 ) {
3201 $and = $this->getMessageFromDB( 'and' );
3202 $space = $this->getMessageFromDB( 'word-separator' );
3203 if ( $m > 1 ) {
3204 $comma = $this->getMessageFromDB( 'comma-separator' );
3207 $s = $l[$m];
3208 for ( $i = $m - 1; $i >= 0; $i-- ) {
3209 if ( $i == $m - 1 ) {
3210 $s = $l[$i] . $and . $space . $s;
3211 } else {
3212 $s = $l[$i] . $comma . $s;
3215 return $s;
3219 * Take a list of strings and build a locale-friendly comma-separated
3220 * list, using the local comma-separator message.
3221 * @param $list array of strings to put in a comma list
3222 * @return string
3224 function commaList( array $list ) {
3225 return implode(
3226 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3227 $list
3232 * Take a list of strings and build a locale-friendly semicolon-separated
3233 * list, using the local semicolon-separator message.
3234 * @param $list array of strings to put in a semicolon list
3235 * @return string
3237 function semicolonList( array $list ) {
3238 return implode(
3239 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3240 $list
3245 * Same as commaList, but separate it with the pipe instead.
3246 * @param $list array of strings to put in a pipe list
3247 * @return string
3249 function pipeList( array $list ) {
3250 return implode(
3251 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3252 $list
3257 * Truncate a string to a specified length in bytes, appending an optional
3258 * string (e.g. for ellipses)
3260 * The database offers limited byte lengths for some columns in the database;
3261 * multi-byte character sets mean we need to ensure that only whole characters
3262 * are included, otherwise broken characters can be passed to the user
3264 * If $length is negative, the string will be truncated from the beginning
3266 * @param $string String to truncate
3267 * @param $length Int: maximum length (including ellipses)
3268 * @param $ellipsis String to append to the truncated text
3269 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3270 * $adjustLength was introduced in 1.18, before that behaved as if false.
3271 * @return string
3273 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3274 # Use the localized ellipsis character
3275 if ( $ellipsis == '...' ) {
3276 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3278 # Check if there is no need to truncate
3279 if ( $length == 0 ) {
3280 return $ellipsis; // convention
3281 } elseif ( strlen( $string ) <= abs( $length ) ) {
3282 return $string; // no need to truncate
3284 $stringOriginal = $string;
3285 # If ellipsis length is >= $length then we can't apply $adjustLength
3286 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3287 $string = $ellipsis; // this can be slightly unexpected
3288 # Otherwise, truncate and add ellipsis...
3289 } else {
3290 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3291 if ( $length > 0 ) {
3292 $length -= $eLength;
3293 $string = substr( $string, 0, $length ); // xyz...
3294 $string = $this->removeBadCharLast( $string );
3295 $string = $string . $ellipsis;
3296 } else {
3297 $length += $eLength;
3298 $string = substr( $string, $length ); // ...xyz
3299 $string = $this->removeBadCharFirst( $string );
3300 $string = $ellipsis . $string;
3303 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3304 # This check is *not* redundant if $adjustLength, due to the single case where
3305 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3306 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3307 return $string;
3308 } else {
3309 return $stringOriginal;
3314 * Remove bytes that represent an incomplete Unicode character
3315 * at the end of string (e.g. bytes of the char are missing)
3317 * @param $string String
3318 * @return string
3320 protected function removeBadCharLast( $string ) {
3321 if ( $string != '' ) {
3322 $char = ord( $string[strlen( $string ) - 1] );
3323 $m = array();
3324 if ( $char >= 0xc0 ) {
3325 # We got the first byte only of a multibyte char; remove it.
3326 $string = substr( $string, 0, -1 );
3327 } elseif ( $char >= 0x80 &&
3328 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3329 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3331 # We chopped in the middle of a character; remove it
3332 $string = $m[1];
3335 return $string;
3339 * Remove bytes that represent an incomplete Unicode character
3340 * at the start of string (e.g. bytes of the char are missing)
3342 * @param $string String
3343 * @return string
3345 protected function removeBadCharFirst( $string ) {
3346 if ( $string != '' ) {
3347 $char = ord( $string[0] );
3348 if ( $char >= 0x80 && $char < 0xc0 ) {
3349 # We chopped in the middle of a character; remove the whole thing
3350 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3353 return $string;
3357 * Truncate a string of valid HTML to a specified length in bytes,
3358 * appending an optional string (e.g. for ellipses), and return valid HTML
3360 * This is only intended for styled/linked text, such as HTML with
3361 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3362 * Also, this will not detect things like "display:none" CSS.
3364 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3366 * @param string $text HTML string to truncate
3367 * @param int $length (zero/positive) Maximum length (including ellipses)
3368 * @param string $ellipsis String to append to the truncated text
3369 * @return string
3371 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3372 # Use the localized ellipsis character
3373 if ( $ellipsis == '...' ) {
3374 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3376 # Check if there is clearly no need to truncate
3377 if ( $length <= 0 ) {
3378 return $ellipsis; // no text shown, nothing to format (convention)
3379 } elseif ( strlen( $text ) <= $length ) {
3380 return $text; // string short enough even *with* HTML (short-circuit)
3383 $dispLen = 0; // innerHTML legth so far
3384 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3385 $tagType = 0; // 0-open, 1-close
3386 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3387 $entityState = 0; // 0-not entity, 1-entity
3388 $tag = $ret = ''; // accumulated tag name, accumulated result string
3389 $openTags = array(); // open tag stack
3390 $maybeState = null; // possible truncation state
3392 $textLen = strlen( $text );
3393 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3394 for ( $pos = 0; true; ++$pos ) {
3395 # Consider truncation once the display length has reached the maximim.
3396 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3397 # Check that we're not in the middle of a bracket/entity...
3398 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3399 if ( !$testingEllipsis ) {
3400 $testingEllipsis = true;
3401 # Save where we are; we will truncate here unless there turn out to
3402 # be so few remaining characters that truncation is not necessary.
3403 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3404 $maybeState = array( $ret, $openTags ); // save state
3406 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3407 # String in fact does need truncation, the truncation point was OK.
3408 list( $ret, $openTags ) = $maybeState; // reload state
3409 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3410 $ret .= $ellipsis; // add ellipsis
3411 break;
3414 if ( $pos >= $textLen ) {
3415 break; // extra iteration just for above checks
3418 # Read the next char...
3419 $ch = $text[$pos];
3420 $lastCh = $pos ? $text[$pos - 1] : '';
3421 $ret .= $ch; // add to result string
3422 if ( $ch == '<' ) {
3423 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3424 $entityState = 0; // for bad HTML
3425 $bracketState = 1; // tag started (checking for backslash)
3426 } elseif ( $ch == '>' ) {
3427 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3428 $entityState = 0; // for bad HTML
3429 $bracketState = 0; // out of brackets
3430 } elseif ( $bracketState == 1 ) {
3431 if ( $ch == '/' ) {
3432 $tagType = 1; // close tag (e.g. "</span>")
3433 } else {
3434 $tagType = 0; // open tag (e.g. "<span>")
3435 $tag .= $ch;
3437 $bracketState = 2; // building tag name
3438 } elseif ( $bracketState == 2 ) {
3439 if ( $ch != ' ' ) {
3440 $tag .= $ch;
3441 } else {
3442 // Name found (e.g. "<a href=..."), add on tag attributes...
3443 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3445 } elseif ( $bracketState == 0 ) {
3446 if ( $entityState ) {
3447 if ( $ch == ';' ) {
3448 $entityState = 0;
3449 $dispLen++; // entity is one displayed char
3451 } else {
3452 if ( $neLength == 0 && !$maybeState ) {
3453 // Save state without $ch. We want to *hit* the first
3454 // display char (to get tags) but not *use* it if truncating.
3455 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3457 if ( $ch == '&' ) {
3458 $entityState = 1; // entity found, (e.g. "&#160;")
3459 } else {
3460 $dispLen++; // this char is displayed
3461 // Add the next $max display text chars after this in one swoop...
3462 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3463 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3464 $dispLen += $skipped;
3465 $pos += $skipped;
3470 // Close the last tag if left unclosed by bad HTML
3471 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3472 while ( count( $openTags ) > 0 ) {
3473 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3475 return $ret;
3479 * truncateHtml() helper function
3480 * like strcspn() but adds the skipped chars to $ret
3482 * @param $ret
3483 * @param $text
3484 * @param $search
3485 * @param $start
3486 * @param $len
3487 * @return int
3489 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3490 if ( $len === null ) {
3491 $len = -1; // -1 means "no limit" for strcspn
3492 } elseif ( $len < 0 ) {
3493 $len = 0; // sanity
3495 $skipCount = 0;
3496 if ( $start < strlen( $text ) ) {
3497 $skipCount = strcspn( $text, $search, $start, $len );
3498 $ret .= substr( $text, $start, $skipCount );
3500 return $skipCount;
3504 * truncateHtml() helper function
3505 * (a) push or pop $tag from $openTags as needed
3506 * (b) clear $tag value
3507 * @param &$tag string Current HTML tag name we are looking at
3508 * @param $tagType int (0-open tag, 1-close tag)
3509 * @param $lastCh string Character before the '>' that ended this tag
3510 * @param &$openTags array Open tag stack (not accounting for $tag)
3512 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3513 $tag = ltrim( $tag );
3514 if ( $tag != '' ) {
3515 if ( $tagType == 0 && $lastCh != '/' ) {
3516 $openTags[] = $tag; // tag opened (didn't close itself)
3517 } elseif ( $tagType == 1 ) {
3518 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3519 array_pop( $openTags ); // tag closed
3522 $tag = '';
3527 * Grammatical transformations, needed for inflected languages
3528 * Invoked by putting {{grammar:case|word}} in a message
3530 * @param $word string
3531 * @param $case string
3532 * @return string
3534 function convertGrammar( $word, $case ) {
3535 global $wgGrammarForms;
3536 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3537 return $wgGrammarForms[$this->getCode()][$case][$word];
3539 return $word;
3542 * Get the grammar forms for the content language
3543 * @return array of grammar forms
3544 * @since 1.20
3546 function getGrammarForms() {
3547 global $wgGrammarForms;
3548 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3549 return $wgGrammarForms[$this->getCode()];
3551 return array();
3554 * Provides an alternative text depending on specified gender.
3555 * Usage {{gender:username|masculine|feminine|neutral}}.
3556 * username is optional, in which case the gender of current user is used,
3557 * but only in (some) interface messages; otherwise default gender is used.
3559 * If no forms are given, an empty string is returned. If only one form is
3560 * given, it will be returned unconditionally. These details are implied by
3561 * the caller and cannot be overridden in subclasses.
3563 * If more than one form is given, the default is to use the neutral one
3564 * if it is specified, and to use the masculine one otherwise. These
3565 * details can be overridden in subclasses.
3567 * @param $gender string
3568 * @param $forms array
3570 * @return string
3572 function gender( $gender, $forms ) {
3573 if ( !count( $forms ) ) {
3574 return '';
3576 $forms = $this->preConvertPlural( $forms, 2 );
3577 if ( $gender === 'male' ) {
3578 return $forms[0];
3580 if ( $gender === 'female' ) {
3581 return $forms[1];
3583 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3587 * Plural form transformations, needed for some languages.
3588 * For example, there are 3 form of plural in Russian and Polish,
3589 * depending on "count mod 10". See [[w:Plural]]
3590 * For English it is pretty simple.
3592 * Invoked by putting {{plural:count|wordform1|wordform2}}
3593 * or {{plural:count|wordform1|wordform2|wordform3}}
3595 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3597 * @param $count Integer: non-localized number
3598 * @param $forms Array: different plural forms
3599 * @return string Correct form of plural for $count in this language
3601 function convertPlural( $count, $forms ) {
3602 if ( !count( $forms ) ) {
3603 return '';
3606 // Handle explicit n=pluralform cases
3607 foreach ( $forms as $index => $form ) {
3608 if ( preg_match( '/\d+=/i', $form ) ) {
3609 $pos = strpos( $form, '=' );
3610 if ( substr( $form, 0, $pos ) === (string) $count ) {
3611 return substr( $form, $pos + 1 );
3613 unset( $forms[$index] );
3616 $forms = array_values( $forms );
3618 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3619 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3620 return $forms[$pluralForm];
3624 * Checks that convertPlural was given an array and pads it to requested
3625 * amount of forms by copying the last one.
3627 * @param $count Integer: How many forms should there be at least
3628 * @param $forms Array of forms given to convertPlural
3629 * @return array Padded array of forms or an exception if not an array
3631 protected function preConvertPlural( /* Array */ $forms, $count ) {
3632 while ( count( $forms ) < $count ) {
3633 $forms[] = $forms[count( $forms ) - 1];
3635 return $forms;
3639 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3640 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3641 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3642 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3643 * match up with it.
3645 * @param $str String: the validated block duration in English
3646 * @return string Somehow translated block duration
3647 * @see LanguageFi.php for example implementation
3649 function translateBlockExpiry( $str ) {
3650 $duration = SpecialBlock::getSuggestedDurations( $this );
3651 foreach ( $duration as $show => $value ) {
3652 if ( strcmp( $str, $value ) == 0 ) {
3653 return htmlspecialchars( trim( $show ) );
3657 // Since usually only infinite or indefinite is only on list, so try
3658 // equivalents if still here.
3659 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3660 if ( in_array( $str, $indefs ) ) {
3661 foreach ( $indefs as $val ) {
3662 $show = array_search( $val, $duration, true );
3663 if ( $show !== false ) {
3664 return htmlspecialchars( trim( $show ) );
3669 // If all else fails, return a standard duration or timestamp description.
3670 $time = strtotime( $str, 0 );
3671 if ( $time === false ) { // Unknown format. Return it as-is in case.
3672 return $str;
3673 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3674 // $time is relative to 0 so it's a duration length.
3675 return $this->formatDuration( $time );
3676 } else { // It's an absolute timestamp.
3677 if ( $time === 0 ) {
3678 // wfTimestamp() handles 0 as current time instead of epoch.
3679 return $this->timeanddate( '19700101000000' );
3680 } else {
3681 return $this->timeanddate( $time );
3687 * languages like Chinese need to be segmented in order for the diff
3688 * to be of any use
3690 * @param $text String
3691 * @return String
3693 public function segmentForDiff( $text ) {
3694 return $text;
3698 * and unsegment to show the result
3700 * @param $text String
3701 * @return String
3703 public function unsegmentForDiff( $text ) {
3704 return $text;
3708 * Return the LanguageConverter used in the Language
3710 * @since 1.19
3711 * @return LanguageConverter
3713 public function getConverter() {
3714 return $this->mConverter;
3718 * convert text to all supported variants
3720 * @param $text string
3721 * @return array
3723 public function autoConvertToAllVariants( $text ) {
3724 return $this->mConverter->autoConvertToAllVariants( $text );
3728 * convert text to different variants of a language.
3730 * @param $text string
3731 * @return string
3733 public function convert( $text ) {
3734 return $this->mConverter->convert( $text );
3738 * Convert a Title object to a string in the preferred variant
3740 * @param $title Title
3741 * @return string
3743 public function convertTitle( $title ) {
3744 return $this->mConverter->convertTitle( $title );
3748 * Convert a namespace index to a string in the preferred variant
3750 * @param $ns int
3751 * @return string
3753 public function convertNamespace( $ns ) {
3754 return $this->mConverter->convertNamespace( $ns );
3758 * Check if this is a language with variants
3760 * @return bool
3762 public function hasVariants() {
3763 return count( $this->getVariants() ) > 1;
3767 * Check if the language has the specific variant
3769 * @since 1.19
3770 * @param $variant string
3771 * @return bool
3773 public function hasVariant( $variant ) {
3774 return (bool)$this->mConverter->validateVariant( $variant );
3778 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3780 * @param $text string
3781 * @return string
3783 public function armourMath( $text ) {
3784 return $this->mConverter->armourMath( $text );
3788 * Perform output conversion on a string, and encode for safe HTML output.
3789 * @param $text String text to be converted
3790 * @param $isTitle Bool whether this conversion is for the article title
3791 * @return string
3792 * @todo this should get integrated somewhere sane
3794 public function convertHtml( $text, $isTitle = false ) {
3795 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3799 * @param $key string
3800 * @return string
3802 public function convertCategoryKey( $key ) {
3803 return $this->mConverter->convertCategoryKey( $key );
3807 * Get the list of variants supported by this language
3808 * see sample implementation in LanguageZh.php
3810 * @return array an array of language codes
3812 public function getVariants() {
3813 return $this->mConverter->getVariants();
3817 * @return string
3819 public function getPreferredVariant() {
3820 return $this->mConverter->getPreferredVariant();
3824 * @return string
3826 public function getDefaultVariant() {
3827 return $this->mConverter->getDefaultVariant();
3831 * @return string
3833 public function getURLVariant() {
3834 return $this->mConverter->getURLVariant();
3838 * If a language supports multiple variants, it is
3839 * possible that non-existing link in one variant
3840 * actually exists in another variant. this function
3841 * tries to find it. See e.g. LanguageZh.php
3843 * @param $link String: the name of the link
3844 * @param $nt Mixed: the title object of the link
3845 * @param $ignoreOtherCond Boolean: to disable other conditions when
3846 * we need to transclude a template or update a category's link
3847 * @return null the input parameters may be modified upon return
3849 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3850 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3854 * If a language supports multiple variants, converts text
3855 * into an array of all possible variants of the text:
3856 * 'variant' => text in that variant
3858 * @deprecated since 1.17 Use autoConvertToAllVariants()
3860 * @param $text string
3862 * @return string
3864 public function convertLinkToAllVariants( $text ) {
3865 return $this->mConverter->convertLinkToAllVariants( $text );
3869 * returns language specific options used by User::getPageRenderHash()
3870 * for example, the preferred language variant
3872 * @return string
3874 function getExtraHashOptions() {
3875 return $this->mConverter->getExtraHashOptions();
3879 * For languages that support multiple variants, the title of an
3880 * article may be displayed differently in different variants. this
3881 * function returns the apporiate title defined in the body of the article.
3883 * @return string
3885 public function getParsedTitle() {
3886 return $this->mConverter->getParsedTitle();
3890 * Prepare external link text for conversion. When the text is
3891 * a URL, it shouldn't be converted, and it'll be wrapped in
3892 * the "raw" tag (-{R| }-) to prevent conversion.
3894 * This function is called "markNoConversion" for historical
3895 * reasons.
3897 * @param $text String: text to be used for external link
3898 * @param $noParse bool: wrap it without confirming it's a real URL first
3899 * @return string the tagged text
3901 public function markNoConversion( $text, $noParse = false ) {
3902 // Excluding protocal-relative URLs may avoid many false positives.
3903 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3904 return $this->mConverter->markNoConversion( $text );
3905 } else {
3906 return $text;
3911 * A regular expression to match legal word-trailing characters
3912 * which should be merged onto a link of the form [[foo]]bar.
3914 * @return string
3916 public function linkTrail() {
3917 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3921 * @return Language
3923 function getLangObj() {
3924 return $this;
3928 * Get the RFC 3066 code for this language object
3930 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3931 * htmlspecialchars() or similar
3933 * @return string
3935 public function getCode() {
3936 return $this->mCode;
3940 * Get the code in Bcp47 format which we can use
3941 * inside of html lang="" tags.
3943 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3944 * htmlspecialchars() or similar.
3946 * @since 1.19
3947 * @return string
3949 public function getHtmlCode() {
3950 if ( is_null( $this->mHtmlCode ) ) {
3951 $this->mHtmlCode = wfBCP47( $this->getCode() );
3953 return $this->mHtmlCode;
3957 * @param $code string
3959 public function setCode( $code ) {
3960 $this->mCode = $code;
3961 // Ensure we don't leave an incorrect html code lying around
3962 $this->mHtmlCode = null;
3966 * Get the name of a file for a certain language code
3967 * @param $prefix string Prepend this to the filename
3968 * @param $code string Language code
3969 * @param $suffix string Append this to the filename
3970 * @throws MWException
3971 * @return string $prefix . $mangledCode . $suffix
3973 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3974 // Protect against path traversal
3975 if ( !Language::isValidCode( $code )
3976 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3978 throw new MWException( "Invalid language code \"$code\"" );
3981 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3985 * Get the language code from a file name. Inverse of getFileName()
3986 * @param $filename string $prefix . $languageCode . $suffix
3987 * @param $prefix string Prefix before the language code
3988 * @param $suffix string Suffix after the language code
3989 * @return string Language code, or false if $prefix or $suffix isn't found
3991 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3992 $m = null;
3993 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3994 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3995 if ( !count( $m ) ) {
3996 return false;
3998 return str_replace( '_', '-', strtolower( $m[1] ) );
4002 * @param $code string
4003 * @return string
4005 public static function getMessagesFileName( $code ) {
4006 global $IP;
4007 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4008 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4009 return $file;
4013 * @param $code string
4014 * @return string
4016 public static function getClassFileName( $code ) {
4017 global $IP;
4018 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4022 * Get the first fallback for a given language.
4024 * @param $code string
4026 * @return bool|string
4028 public static function getFallbackFor( $code ) {
4029 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4030 return false;
4031 } else {
4032 $fallbacks = self::getFallbacksFor( $code );
4033 $first = array_shift( $fallbacks );
4034 return $first;
4039 * Get the ordered list of fallback languages.
4041 * @since 1.19
4042 * @param $code string Language code
4043 * @return array
4045 public static function getFallbacksFor( $code ) {
4046 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4047 return array();
4048 } else {
4049 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4050 $v = array_map( 'trim', explode( ',', $v ) );
4051 if ( $v[count( $v ) - 1] !== 'en' ) {
4052 $v[] = 'en';
4054 return $v;
4059 * Get all messages for a given language
4060 * WARNING: this may take a long time. If you just need all message *keys*
4061 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4063 * @param $code string
4065 * @return array
4067 public static function getMessagesFor( $code ) {
4068 return self::getLocalisationCache()->getItem( $code, 'messages' );
4072 * Get a message for a given language
4074 * @param $key string
4075 * @param $code string
4077 * @return string
4079 public static function getMessageFor( $key, $code ) {
4080 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4084 * Get all message keys for a given language. This is a faster alternative to
4085 * array_keys( Language::getMessagesFor( $code ) )
4087 * @since 1.19
4088 * @param $code string Language code
4089 * @return array of message keys (strings)
4091 public static function getMessageKeysFor( $code ) {
4092 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4096 * @param $talk
4097 * @return mixed
4099 function fixVariableInNamespace( $talk ) {
4100 if ( strpos( $talk, '$1' ) === false ) {
4101 return $talk;
4104 global $wgMetaNamespace;
4105 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4107 # Allow grammar transformations
4108 # Allowing full message-style parsing would make simple requests
4109 # such as action=raw much more expensive than they need to be.
4110 # This will hopefully cover most cases.
4111 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4112 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4113 return str_replace( ' ', '_', $talk );
4117 * @param $m string
4118 * @return string
4120 function replaceGrammarInNamespace( $m ) {
4121 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4125 * @throws MWException
4126 * @return array
4128 static function getCaseMaps() {
4129 static $wikiUpperChars, $wikiLowerChars;
4130 if ( isset( $wikiUpperChars ) ) {
4131 return array( $wikiUpperChars, $wikiLowerChars );
4134 wfProfileIn( __METHOD__ );
4135 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4136 if ( $arr === false ) {
4137 throw new MWException(
4138 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4140 $wikiUpperChars = $arr['wikiUpperChars'];
4141 $wikiLowerChars = $arr['wikiLowerChars'];
4142 wfProfileOut( __METHOD__ );
4143 return array( $wikiUpperChars, $wikiLowerChars );
4147 * Decode an expiry (block, protection, etc) which has come from the DB
4149 * @todo FIXME: why are we returnings DBMS-dependent strings???
4151 * @param $expiry String: Database expiry String
4152 * @param $format Bool|Int true to process using language functions, or TS_ constant
4153 * to return the expiry in a given timestamp
4154 * @return String
4155 * @since 1.18
4157 public function formatExpiry( $expiry, $format = true ) {
4158 static $infinity;
4159 if ( $infinity === null ) {
4160 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4163 if ( $expiry == '' || $expiry == $infinity ) {
4164 return $format === true
4165 ? $this->getMessageFromDB( 'infiniteblock' )
4166 : $infinity;
4167 } else {
4168 return $format === true
4169 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4170 : wfTimestamp( $format, $expiry );
4175 * @todo Document
4176 * @param $seconds int|float
4177 * @param $format Array Optional
4178 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4179 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4180 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4181 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4182 * @return string
4184 function formatTimePeriod( $seconds, $format = array() ) {
4185 if ( !is_array( $format ) ) {
4186 $format = array( 'avoid' => $format ); // For backwards compatibility
4188 if ( !isset( $format['avoid'] ) ) {
4189 $format['avoid'] = false;
4191 if ( !isset( $format['noabbrevs' ] ) ) {
4192 $format['noabbrevs'] = false;
4194 $secondsMsg = wfMessage(
4195 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4196 $minutesMsg = wfMessage(
4197 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4198 $hoursMsg = wfMessage(
4199 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4200 $daysMsg = wfMessage(
4201 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4203 if ( round( $seconds * 10 ) < 100 ) {
4204 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4205 $s = $secondsMsg->params( $s )->text();
4206 } elseif ( round( $seconds ) < 60 ) {
4207 $s = $this->formatNum( round( $seconds ) );
4208 $s = $secondsMsg->params( $s )->text();
4209 } elseif ( round( $seconds ) < 3600 ) {
4210 $minutes = floor( $seconds / 60 );
4211 $secondsPart = round( fmod( $seconds, 60 ) );
4212 if ( $secondsPart == 60 ) {
4213 $secondsPart = 0;
4214 $minutes++;
4216 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4217 $s .= ' ';
4218 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4219 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4220 $hours = floor( $seconds / 3600 );
4221 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4222 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4223 if ( $secondsPart == 60 ) {
4224 $secondsPart = 0;
4225 $minutes++;
4227 if ( $minutes == 60 ) {
4228 $minutes = 0;
4229 $hours++;
4231 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4232 $s .= ' ';
4233 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4234 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4235 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4237 } else {
4238 $days = floor( $seconds / 86400 );
4239 if ( $format['avoid'] === 'avoidminutes' ) {
4240 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4241 if ( $hours == 24 ) {
4242 $hours = 0;
4243 $days++;
4245 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4246 $s .= ' ';
4247 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4248 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4249 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4250 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4251 if ( $minutes == 60 ) {
4252 $minutes = 0;
4253 $hours++;
4255 if ( $hours == 24 ) {
4256 $hours = 0;
4257 $days++;
4259 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4260 $s .= ' ';
4261 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4262 $s .= ' ';
4263 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4264 } else {
4265 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4266 $s .= ' ';
4267 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4270 return $s;
4274 * Format a bitrate for output, using an appropriate
4275 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4277 * This use base 1000. For base 1024 use formatSize(), for another base
4278 * see formatComputingNumbers()
4280 * @param $bps int
4281 * @return string
4283 function formatBitrate( $bps ) {
4284 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4288 * @param $size int Size of the unit
4289 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4290 * @param $messageKey string Message key to be uesd
4291 * @return string
4293 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4294 if ( $size <= 0 ) {
4295 return str_replace( '$1', $this->formatNum( $size ),
4296 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4299 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4300 $index = 0;
4302 $maxIndex = count( $sizes ) - 1;
4303 while ( $size >= $boundary && $index < $maxIndex ) {
4304 $index++;
4305 $size /= $boundary;
4308 // For small sizes no decimal places necessary
4309 $round = 0;
4310 if ( $index > 1 ) {
4311 // For MB and bigger two decimal places are smarter
4312 $round = 2;
4314 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4316 $size = round( $size, $round );
4317 $text = $this->getMessageFromDB( $msg );
4318 return str_replace( '$1', $this->formatNum( $size ), $text );
4322 * Format a size in bytes for output, using an appropriate
4323 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4325 * This method use base 1024. For base 1000 use formatBitrate(), for
4326 * another base see formatComputingNumbers()
4328 * @param $size int Size to format
4329 * @return string Plain text (not HTML)
4331 function formatSize( $size ) {
4332 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4336 * Make a list item, used by various special pages
4338 * @param $page String Page link
4339 * @param $details String Text between brackets
4340 * @param $oppositedm Boolean Add the direction mark opposite to your
4341 * language, to display text properly
4342 * @return String
4344 function specialList( $page, $details, $oppositedm = true ) {
4345 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4346 $this->getDirMark();
4347 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4348 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4349 return $page . $details;
4353 * Generate (prev x| next x) (20|50|100...) type links for paging
4355 * @param $title Title object to link
4356 * @param $offset Integer offset parameter
4357 * @param $limit Integer limit parameter
4358 * @param $query array|String optional URL query parameter string
4359 * @param $atend Bool optional param for specified if this is the last page
4360 * @return String
4362 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4363 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4365 # Make 'previous' link
4366 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4367 if ( $offset > 0 ) {
4368 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4369 $query, $prev, 'prevn-title', 'mw-prevlink' );
4370 } else {
4371 $plink = htmlspecialchars( $prev );
4374 # Make 'next' link
4375 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4376 if ( $atend ) {
4377 $nlink = htmlspecialchars( $next );
4378 } else {
4379 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4380 $query, $next, 'prevn-title', 'mw-nextlink' );
4383 # Make links to set number of items per page
4384 $numLinks = array();
4385 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4386 $numLinks[] = $this->numLink( $title, $offset, $num,
4387 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4390 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4391 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4395 * Helper function for viewPrevNext() that generates links
4397 * @param $title Title object to link
4398 * @param $offset Integer offset parameter
4399 * @param $limit Integer limit parameter
4400 * @param $query Array extra query parameters
4401 * @param $link String text to use for the link; will be escaped
4402 * @param $tooltipMsg String name of the message to use as tooltip
4403 * @param $class String value of the "class" attribute of the link
4404 * @return String HTML fragment
4406 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4407 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4408 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4409 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4410 'title' => $tooltip, 'class' => $class ), $link );
4414 * Get the conversion rule title, if any.
4416 * @return string
4418 public function getConvRuleTitle() {
4419 return $this->mConverter->getConvRuleTitle();
4423 * Get the compiled plural rules for the language
4424 * @since 1.20
4425 * @return array Associative array with plural form, and plural rule as key-value pairs
4427 public function getCompiledPluralRules() {
4428 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4429 $fallbacks = Language::getFallbacksFor( $this->mCode );
4430 if ( !$pluralRules ) {
4431 foreach ( $fallbacks as $fallbackCode ) {
4432 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4433 if ( $pluralRules ) {
4434 break;
4438 return $pluralRules;
4442 * Get the plural rules for the language
4443 * @since 1.20
4444 * @return array Associative array with plural form number and plural rule as key-value pairs
4446 public function getPluralRules() {
4447 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4448 $fallbacks = Language::getFallbacksFor( $this->mCode );
4449 if ( !$pluralRules ) {
4450 foreach ( $fallbacks as $fallbackCode ) {
4451 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4452 if ( $pluralRules ) {
4453 break;
4457 return $pluralRules;
4461 * Get the plural rule types for the language
4462 * @since 1.21
4463 * @return array Associative array with plural form number and plural rule type as key-value pairs
4465 public function getPluralRuleTypes() {
4466 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4467 $fallbacks = Language::getFallbacksFor( $this->mCode );
4468 if ( !$pluralRuleTypes ) {
4469 foreach ( $fallbacks as $fallbackCode ) {
4470 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4471 if ( $pluralRuleTypes ) {
4472 break;
4476 return $pluralRuleTypes;
4480 * Find the index number of the plural rule appropriate for the given number
4481 * @return int The index number of the plural rule
4483 public function getPluralRuleIndexNumber( $number ) {
4484 $pluralRules = $this->getCompiledPluralRules();
4485 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4486 return $form;
4490 * Find the plural rule type appropriate for the given number
4491 * For example, if the language is set to Arabic, getPluralType(5) should
4492 * return 'few'.
4493 * @since 1.21
4494 * @return string The name of the plural rule type, e.g. one, two, few, many
4496 public function getPluralRuleType( $number ) {
4497 $index = $this->getPluralRuleIndexNumber( $number );
4498 $pluralRuleTypes = $this->getPluralRuleTypes();
4499 if ( isset( $pluralRuleTypes[$index] ) ) {
4500 return $pluralRuleTypes[$index];
4501 } else {
4502 return 'other';