Changed quoting function for oracleDB.
[mediawiki.git] / languages / Language.php
blobea34363b4f85f722d99f9a811680cb1925d4dc71
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 * Cache for language fallbacks.
175 * @see Language::getFallbacksIncludingSiteLanguage
176 * @since 1.21
177 * @var array
179 static private $fallbackLanguageCache = array();
182 * Get a cached or new language object for a given language code
183 * @param $code String
184 * @return Language
186 static function factory( $code ) {
187 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
189 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
190 $code = $wgDummyLanguageCodes[$code];
193 // get the language object to process
194 $langObj = isset( self::$mLangObjCache[$code] )
195 ? self::$mLangObjCache[$code]
196 : self::newFromCode( $code );
198 // merge the language object in to get it up front in the cache
199 self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache );
200 // get rid of the oldest ones in case we have an overflow
201 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
203 return $langObj;
207 * Create a language object for a given language code
208 * @param $code String
209 * @throws MWException
210 * @return Language
212 protected static function newFromCode( $code ) {
213 // Protect against path traversal below
214 if ( !Language::isValidCode( $code )
215 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
217 throw new MWException( "Invalid language code \"$code\"" );
220 if ( !Language::isValidBuiltInCode( $code ) ) {
221 // It's not possible to customise this code with class files, so
222 // just return a Language object. This is to support uselang= hacks.
223 $lang = new Language;
224 $lang->setCode( $code );
225 return $lang;
228 // Check if there is a language class for the code
229 $class = self::classFromCode( $code );
230 self::preloadLanguageClass( $class );
231 if ( MWInit::classExists( $class ) ) {
232 $lang = new $class;
233 return $lang;
236 // Keep trying the fallback list until we find an existing class
237 $fallbacks = Language::getFallbacksFor( $code );
238 foreach ( $fallbacks as $fallbackCode ) {
239 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
240 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
243 $class = self::classFromCode( $fallbackCode );
244 self::preloadLanguageClass( $class );
245 if ( MWInit::classExists( $class ) ) {
246 $lang = Language::newFromCode( $fallbackCode );
247 $lang->setCode( $code );
248 return $lang;
252 throw new MWException( "Invalid fallback sequence for language '$code'" );
256 * Checks whether any localisation is available for that language tag
257 * in MediaWiki (MessagesXx.php exists).
259 * @param string $code Language tag (in lower case)
260 * @return bool Whether language is supported
261 * @since 1.21
263 public static function isSupportedLanguage( $code ) {
264 return $code === strtolower( $code ) && is_readable( self::getMessagesFileName( $code ) );
268 * Returns true if a language code string is a well-formed language tag
269 * according to RFC 5646.
270 * This function only checks well-formedness; it doesn't check that
271 * language, script or variant codes actually exist in the repositories.
273 * Based on regexes by Mark Davis of the Unicode Consortium:
274 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
276 * @param $code string
277 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
279 * @return bool
280 * @since 1.21
282 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
283 $alpha = '[a-z]';
284 $digit = '[0-9]';
285 $alphanum = '[a-z0-9]';
286 $x = 'x'; # private use singleton
287 $singleton = '[a-wy-z]'; # other singleton
288 $s = $lenient ? '[-_]' : '-';
290 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
291 $script = "$alpha{4}"; # ISO 15924
292 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
293 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
294 $extension = "$singleton(?:$s$alphanum{2,8})+";
295 $privateUse = "$x(?:$s$alphanum{1,8})+";
297 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
298 # Since these are limited, this is safe even later changes to the registry --
299 # the only oddity is that it might change the type of the tag, and thus
300 # the results from the capturing groups.
301 # http://www.iana.org/assignments/language-subtag-registry
303 $grandfathered = "en{$s}GB{$s}oed"
304 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
305 . "|no{$s}(?:bok|nyn)"
306 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
307 . "|zh{$s}min{$s}nan";
309 $variantList = "$variant(?:$s$variant)*";
310 $extensionList = "$extension(?:$s$extension)*";
312 $langtag = "(?:($language)"
313 . "(?:$s$script)?"
314 . "(?:$s$region)?"
315 . "(?:$s$variantList)?"
316 . "(?:$s$extensionList)?"
317 . "(?:$s$privateUse)?)";
319 # The final breakdown, with capturing groups for each of these components
320 # The variants, extensions, grandfathered, and private-use may have interior '-'
322 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
324 return (bool)preg_match( "/$root/", strtolower( $code ) );
328 * Returns true if a language code string is of a valid form, whether or
329 * not it exists. This includes codes which are used solely for
330 * customisation via the MediaWiki namespace.
332 * @param $code string
334 * @return bool
336 public static function isValidCode( $code ) {
337 static $cache = array();
338 if ( isset( $cache[$code] ) ) {
339 return $cache[$code];
341 // People think language codes are html safe, so enforce it.
342 // Ideally we should only allow a-zA-Z0-9-
343 // but, .+ and other chars are often used for {{int:}} hacks
344 // see bugs 37564, 37587, 36938
345 $cache[$code] =
346 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
347 && !preg_match( Title::getTitleInvalidRegex(), $code );
349 return $cache[$code];
353 * Returns true if a language code is of a valid form for the purposes of
354 * internal customisation of MediaWiki, via Messages*.php.
356 * @param $code string
358 * @throws MWException
359 * @since 1.18
360 * @return bool
362 public static function isValidBuiltInCode( $code ) {
364 if ( !is_string( $code ) ) {
365 if ( is_object( $code ) ) {
366 $addmsg = " of class " . get_class( $code );
367 } else {
368 $addmsg = '';
370 $type = gettype( $code );
371 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
374 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
378 * Returns true if a language code is an IETF tag known to MediaWiki.
380 * @param $code string
382 * @since 1.21
383 * @return bool
385 public static function isKnownLanguageTag( $tag ) {
386 static $coreLanguageNames;
388 if ( $coreLanguageNames === null ) {
389 include MWInit::compiledPath( 'languages/Names.php' );
392 if ( isset( $coreLanguageNames[$tag] )
393 || self::fetchLanguageName( $tag, $tag ) !== ''
395 return true;
398 return false;
402 * @param $code
403 * @return String Name of the language class
405 public static function classFromCode( $code ) {
406 if ( $code == 'en' ) {
407 return 'Language';
408 } else {
409 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
414 * Includes language class files
416 * @param $class string Name of the language class
418 public static function preloadLanguageClass( $class ) {
419 global $IP;
421 if ( $class === 'Language' ) {
422 return;
425 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
426 include_once "$IP/languages/classes/$class.php";
431 * Get the LocalisationCache instance
433 * @return LocalisationCache
435 public static function getLocalisationCache() {
436 if ( is_null( self::$dataCache ) ) {
437 global $wgLocalisationCacheConf;
438 $class = $wgLocalisationCacheConf['class'];
439 self::$dataCache = new $class( $wgLocalisationCacheConf );
441 return self::$dataCache;
444 function __construct() {
445 $this->mConverter = new FakeConverter( $this );
446 // Set the code to the name of the descendant
447 if ( get_class( $this ) == 'Language' ) {
448 $this->mCode = 'en';
449 } else {
450 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
452 self::getLocalisationCache();
456 * Reduce memory usage
458 function __destruct() {
459 foreach ( $this as $name => $value ) {
460 unset( $this->$name );
465 * Hook which will be called if this is the content language.
466 * Descendants can use this to register hook functions or modify globals
468 function initContLang() { }
471 * Same as getFallbacksFor for current language.
472 * @return array|bool
473 * @deprecated in 1.19
475 function getFallbackLanguageCode() {
476 wfDeprecated( __METHOD__, '1.19' );
477 return self::getFallbackFor( $this->mCode );
481 * @return array
482 * @since 1.19
484 function getFallbackLanguages() {
485 return self::getFallbacksFor( $this->mCode );
489 * Exports $wgBookstoreListEn
490 * @return array
492 function getBookstoreList() {
493 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
497 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
498 * available in localised form, it will be included in English.
500 * @return array
502 public function getNamespaces() {
503 if ( is_null( $this->namespaceNames ) ) {
504 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
506 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
507 $validNamespaces = MWNamespace::getCanonicalNamespaces();
509 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
511 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
512 if ( $wgMetaNamespaceTalk ) {
513 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
514 } else {
515 $talk = $this->namespaceNames[NS_PROJECT_TALK];
516 $this->namespaceNames[NS_PROJECT_TALK] =
517 $this->fixVariableInNamespace( $talk );
520 # Sometimes a language will be localised but not actually exist on this wiki.
521 foreach ( $this->namespaceNames as $key => $text ) {
522 if ( !isset( $validNamespaces[$key] ) ) {
523 unset( $this->namespaceNames[$key] );
527 # The above mixing may leave namespaces out of canonical order.
528 # Re-order by namespace ID number...
529 ksort( $this->namespaceNames );
531 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
533 return $this->namespaceNames;
537 * Arbitrarily set all of the namespace names at once. Mainly used for testing
538 * @param $namespaces Array of namespaces (id => name)
540 public function setNamespaces( array $namespaces ) {
541 $this->namespaceNames = $namespaces;
542 $this->mNamespaceIds = null;
546 * Resets all of the namespace caches. Mainly used for testing
548 public function resetNamespaces() {
549 $this->namespaceNames = null;
550 $this->mNamespaceIds = null;
551 $this->namespaceAliases = null;
555 * A convenience function that returns the same thing as
556 * getNamespaces() except with the array values changed to ' '
557 * where it found '_', useful for producing output to be displayed
558 * e.g. in <select> forms.
560 * @return array
562 function getFormattedNamespaces() {
563 $ns = $this->getNamespaces();
564 foreach ( $ns as $k => $v ) {
565 $ns[$k] = strtr( $v, '_', ' ' );
567 return $ns;
571 * Get a namespace value by key
572 * <code>
573 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
574 * echo $mw_ns; // prints 'MediaWiki'
575 * </code>
577 * @param $index Int: the array key of the namespace to return
578 * @return mixed, string if the namespace value exists, otherwise false
580 function getNsText( $index ) {
581 $ns = $this->getNamespaces();
582 return isset( $ns[$index] ) ? $ns[$index] : false;
586 * A convenience function that returns the same thing as
587 * getNsText() except with '_' changed to ' ', useful for
588 * producing output.
590 * <code>
591 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
592 * echo $mw_ns; // prints 'MediaWiki talk'
593 * </code>
595 * @param int $index The array key of the namespace to return
596 * @return string Namespace name without underscores (empty string if namespace does not exist)
598 function getFormattedNsText( $index ) {
599 $ns = $this->getNsText( $index );
600 return strtr( $ns, '_', ' ' );
604 * Returns gender-dependent namespace alias if available.
605 * @param $index Int: namespace index
606 * @param $gender String: gender key (male, female... )
607 * @return String
608 * @since 1.18
610 function getGenderNsText( $index, $gender ) {
611 global $wgExtraGenderNamespaces;
613 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
614 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
618 * Whether this language makes distinguishes genders for example in
619 * namespaces.
620 * @return bool
621 * @since 1.18
623 function needsGenderDistinction() {
624 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
625 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
626 // $wgExtraGenderNamespaces overrides everything
627 return true;
628 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
629 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
630 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
631 return false;
632 } else {
633 // Check what is in i18n files
634 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
635 return count( $aliases ) > 0;
640 * Get a namespace key by value, case insensitive.
641 * Only matches namespace names for the current language, not the
642 * canonical ones defined in Namespace.php.
644 * @param $text String
645 * @return mixed An integer if $text is a valid value otherwise false
647 function getLocalNsIndex( $text ) {
648 $lctext = $this->lc( $text );
649 $ids = $this->getNamespaceIds();
650 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
654 * @return array
656 function getNamespaceAliases() {
657 if ( is_null( $this->namespaceAliases ) ) {
658 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
659 if ( !$aliases ) {
660 $aliases = array();
661 } else {
662 foreach ( $aliases as $name => $index ) {
663 if ( $index === NS_PROJECT_TALK ) {
664 unset( $aliases[$name] );
665 $name = $this->fixVariableInNamespace( $name );
666 $aliases[$name] = $index;
671 global $wgExtraGenderNamespaces;
672 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
673 foreach ( $genders as $index => $forms ) {
674 foreach ( $forms as $alias ) {
675 $aliases[$alias] = $index;
679 $this->namespaceAliases = $aliases;
681 return $this->namespaceAliases;
685 * @return array
687 function getNamespaceIds() {
688 if ( is_null( $this->mNamespaceIds ) ) {
689 global $wgNamespaceAliases;
690 # Put namespace names and aliases into a hashtable.
691 # If this is too slow, then we should arrange it so that it is done
692 # before caching. The catch is that at pre-cache time, the above
693 # class-specific fixup hasn't been done.
694 $this->mNamespaceIds = array();
695 foreach ( $this->getNamespaces() as $index => $name ) {
696 $this->mNamespaceIds[$this->lc( $name )] = $index;
698 foreach ( $this->getNamespaceAliases() as $name => $index ) {
699 $this->mNamespaceIds[$this->lc( $name )] = $index;
701 if ( $wgNamespaceAliases ) {
702 foreach ( $wgNamespaceAliases as $name => $index ) {
703 $this->mNamespaceIds[$this->lc( $name )] = $index;
707 return $this->mNamespaceIds;
711 * Get a namespace key by value, case insensitive. Canonical namespace
712 * names override custom ones defined for the current language.
714 * @param $text String
715 * @return mixed An integer if $text is a valid value otherwise false
717 function getNsIndex( $text ) {
718 $lctext = $this->lc( $text );
719 $ns = MWNamespace::getCanonicalIndex( $lctext );
720 if ( $ns !== null ) {
721 return $ns;
723 $ids = $this->getNamespaceIds();
724 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
728 * short names for language variants used for language conversion links.
730 * @param $code String
731 * @param $usemsg bool Use the "variantname-xyz" message if it exists
732 * @return string
734 function getVariantname( $code, $usemsg = true ) {
735 $msg = "variantname-$code";
736 if ( $usemsg && wfMessage( $msg )->exists() ) {
737 return $this->getMessageFromDB( $msg );
739 $name = self::fetchLanguageName( $code );
740 if ( $name ) {
741 return $name; # if it's defined as a language name, show that
742 } else {
743 # otherwise, output the language code
744 return $code;
749 * @param $name string
750 * @return string
752 function specialPage( $name ) {
753 $aliases = $this->getSpecialPageAliases();
754 if ( isset( $aliases[$name][0] ) ) {
755 $name = $aliases[$name][0];
757 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
761 * @return array
763 function getDatePreferences() {
764 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
768 * @return array
770 function getDateFormats() {
771 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
775 * @return array|string
777 function getDefaultDateFormat() {
778 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
779 if ( $df === 'dmy or mdy' ) {
780 global $wgAmericanDates;
781 return $wgAmericanDates ? 'mdy' : 'dmy';
782 } else {
783 return $df;
788 * @return array
790 function getDatePreferenceMigrationMap() {
791 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
795 * @param $image
796 * @return array|null
798 function getImageFile( $image ) {
799 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
803 * @return array
805 function getExtraUserToggles() {
806 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
810 * @param $tog
811 * @return string
813 function getUserToggle( $tog ) {
814 return $this->getMessageFromDB( "tog-$tog" );
818 * Get native language names, indexed by code.
819 * Only those defined in MediaWiki, no other data like CLDR.
820 * If $customisedOnly is true, only returns codes with a messages file
822 * @param $customisedOnly bool
824 * @return array
825 * @deprecated in 1.20, use fetchLanguageNames()
827 public static function getLanguageNames( $customisedOnly = false ) {
828 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
832 * Get translated language names. This is done on best effort and
833 * by default this is exactly the same as Language::getLanguageNames.
834 * The CLDR extension provides translated names.
835 * @param $code String Language code.
836 * @return Array language code => language name
837 * @since 1.18.0
838 * @deprecated in 1.20, use fetchLanguageNames()
840 public static function getTranslatedLanguageNames( $code ) {
841 return self::fetchLanguageNames( $code, 'all' );
845 * Get an array of language names, indexed by code.
846 * @param $inLanguage null|string: Code of language in which to return the names
847 * Use null for autonyms (native names)
848 * @param $include string:
849 * 'all' all available languages
850 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
851 * 'mwfile' only if the language is in 'mw' *and* has a message file
852 * @return array: language code => language name
853 * @since 1.20
855 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
856 global $wgExtraLanguageNames;
857 static $coreLanguageNames;
859 if ( $coreLanguageNames === null ) {
860 include MWInit::compiledPath( 'languages/Names.php' );
863 $names = array();
865 if ( $inLanguage ) {
866 # TODO: also include when $inLanguage is null, when this code is more efficient
867 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
870 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
871 foreach ( $mwNames as $mwCode => $mwName ) {
872 # - Prefer own MediaWiki native name when not using the hook
873 # - For other names just add if not added through the hook
874 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
875 $names[$mwCode] = $mwName;
879 if ( $include === 'all' ) {
880 return $names;
883 $returnMw = array();
884 $coreCodes = array_keys( $mwNames );
885 foreach ( $coreCodes as $coreCode ) {
886 $returnMw[$coreCode] = $names[$coreCode];
889 if ( $include === 'mwfile' ) {
890 $namesMwFile = array();
891 # We do this using a foreach over the codes instead of a directory
892 # loop so that messages files in extensions will work correctly.
893 foreach ( $returnMw as $code => $value ) {
894 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
895 $namesMwFile[$code] = $names[$code];
898 return $namesMwFile;
900 # 'mw' option; default if it's not one of the other two options (all/mwfile)
901 return $returnMw;
905 * @param $code string: The code of the language for which to get the name
906 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
907 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
908 * @return string: Language name or empty
909 * @since 1.20
911 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
912 $array = self::fetchLanguageNames( $inLanguage, $include );
913 return !array_key_exists( $code, $array ) ? '' : $array[$code];
917 * Get a message from the MediaWiki namespace.
919 * @param $msg String: message name
920 * @return string
922 function getMessageFromDB( $msg ) {
923 return wfMessage( $msg )->inLanguage( $this )->text();
927 * Get the native language name of $code.
928 * Only if defined in MediaWiki, no other data like CLDR.
929 * @param $code string
930 * @return string
931 * @deprecated in 1.20, use fetchLanguageName()
933 function getLanguageName( $code ) {
934 return self::fetchLanguageName( $code );
938 * @param $key string
939 * @return string
941 function getMonthName( $key ) {
942 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
946 * @return array
948 function getMonthNamesArray() {
949 $monthNames = array( '' );
950 for ( $i = 1; $i < 13; $i++ ) {
951 $monthNames[] = $this->getMonthName( $i );
953 return $monthNames;
957 * @param $key string
958 * @return string
960 function getMonthNameGen( $key ) {
961 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
965 * @param $key string
966 * @return string
968 function getMonthAbbreviation( $key ) {
969 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
973 * @return array
975 function getMonthAbbreviationsArray() {
976 $monthNames = array( '' );
977 for ( $i = 1; $i < 13; $i++ ) {
978 $monthNames[] = $this->getMonthAbbreviation( $i );
980 return $monthNames;
984 * @param $key string
985 * @return string
987 function getWeekdayName( $key ) {
988 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
992 * @param $key string
993 * @return string
995 function getWeekdayAbbreviation( $key ) {
996 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
1000 * @param $key string
1001 * @return string
1003 function getIranianCalendarMonthName( $key ) {
1004 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1008 * @param $key string
1009 * @return string
1011 function getHebrewCalendarMonthName( $key ) {
1012 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1016 * @param $key string
1017 * @return string
1019 function getHebrewCalendarMonthNameGen( $key ) {
1020 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1024 * @param $key string
1025 * @return string
1027 function getHijriCalendarMonthName( $key ) {
1028 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1032 * This is a workalike of PHP's date() function, but with better
1033 * internationalisation, a reduced set of format characters, and a better
1034 * escaping format.
1036 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1037 * the PHP manual for definitions. There are a number of extensions, which
1038 * start with "x":
1040 * xn Do not translate digits of the next numeric format character
1041 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1042 * xr Use roman numerals for the next numeric format character
1043 * xh Use hebrew numerals for the next numeric format character
1044 * xx Literal x
1045 * xg Genitive month name
1047 * xij j (day number) in Iranian calendar
1048 * xiF F (month name) in Iranian calendar
1049 * xin n (month number) in Iranian calendar
1050 * xiy y (two digit year) in Iranian calendar
1051 * xiY Y (full year) in Iranian calendar
1053 * xjj j (day number) in Hebrew calendar
1054 * xjF F (month name) in Hebrew calendar
1055 * xjt t (days in month) in Hebrew calendar
1056 * xjx xg (genitive month name) in Hebrew calendar
1057 * xjn n (month number) in Hebrew calendar
1058 * xjY Y (full year) in Hebrew calendar
1060 * xmj j (day number) in Hijri calendar
1061 * xmF F (month name) in Hijri calendar
1062 * xmn n (month number) in Hijri calendar
1063 * xmY Y (full year) in Hijri calendar
1065 * xkY Y (full year) in Thai solar calendar. Months and days are
1066 * identical to the Gregorian calendar
1067 * xoY Y (full year) in Minguo calendar or Juche year.
1068 * Months and days are identical to the
1069 * Gregorian calendar
1070 * xtY Y (full year) in Japanese nengo. Months and days are
1071 * identical to the Gregorian calendar
1073 * Characters enclosed in double quotes will be considered literal (with
1074 * the quotes themselves removed). Unmatched quotes will be considered
1075 * literal quotes. Example:
1077 * "The month is" F => The month is January
1078 * i's" => 20'11"
1080 * Backslash escaping is also supported.
1082 * Input timestamp is assumed to be pre-normalized to the desired local
1083 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1084 * $ts is UTC if $zone is not given.
1086 * @param $format String
1087 * @param $ts String: 14-character timestamp
1088 * YYYYMMDDHHMMSS
1089 * 01234567890123
1090 * @param $zone DateTimeZone: Timezone of $ts
1091 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1093 * @throws MWException
1094 * @return string
1096 function sprintfDate( $format, $ts, DateTimeZone $zone = null ) {
1097 $s = '';
1098 $raw = false;
1099 $roman = false;
1100 $hebrewNum = false;
1101 $dateTimeObj = false;
1102 $rawToggle = false;
1103 $iranian = false;
1104 $hebrew = false;
1105 $hijri = false;
1106 $thai = false;
1107 $minguo = false;
1108 $tenno = false;
1110 if ( strlen( $ts ) !== 14 ) {
1111 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1114 if ( !ctype_digit( $ts ) ) {
1115 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1118 for ( $p = 0; $p < strlen( $format ); $p++ ) {
1119 $num = false;
1120 $code = $format[$p];
1121 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1122 $code .= $format[++$p];
1125 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1126 $code .= $format[++$p];
1129 switch ( $code ) {
1130 case 'xx':
1131 $s .= 'x';
1132 break;
1133 case 'xn':
1134 $raw = true;
1135 break;
1136 case 'xN':
1137 $rawToggle = !$rawToggle;
1138 break;
1139 case 'xr':
1140 $roman = true;
1141 break;
1142 case 'xh':
1143 $hebrewNum = true;
1144 break;
1145 case 'xg':
1146 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1147 break;
1148 case 'xjx':
1149 if ( !$hebrew ) {
1150 $hebrew = self::tsToHebrew( $ts );
1152 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1153 break;
1154 case 'd':
1155 $num = substr( $ts, 6, 2 );
1156 break;
1157 case 'D':
1158 if ( !$dateTimeObj ) {
1159 $dateTimeObj = DateTime::createFromFormat(
1160 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1163 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) + 1 );
1164 break;
1165 case 'j':
1166 $num = intval( substr( $ts, 6, 2 ) );
1167 break;
1168 case 'xij':
1169 if ( !$iranian ) {
1170 $iranian = self::tsToIranian( $ts );
1172 $num = $iranian[2];
1173 break;
1174 case 'xmj':
1175 if ( !$hijri ) {
1176 $hijri = self::tsToHijri( $ts );
1178 $num = $hijri[2];
1179 break;
1180 case 'xjj':
1181 if ( !$hebrew ) {
1182 $hebrew = self::tsToHebrew( $ts );
1184 $num = $hebrew[2];
1185 break;
1186 case 'l':
1187 if ( !$dateTimeObj ) {
1188 $dateTimeObj = DateTime::createFromFormat(
1189 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1192 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) + 1 );
1193 break;
1194 case 'F':
1195 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1196 break;
1197 case 'xiF':
1198 if ( !$iranian ) {
1199 $iranian = self::tsToIranian( $ts );
1201 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1202 break;
1203 case 'xmF':
1204 if ( !$hijri ) {
1205 $hijri = self::tsToHijri( $ts );
1207 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1208 break;
1209 case 'xjF':
1210 if ( !$hebrew ) {
1211 $hebrew = self::tsToHebrew( $ts );
1213 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1214 break;
1215 case 'm':
1216 $num = substr( $ts, 4, 2 );
1217 break;
1218 case 'M':
1219 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1220 break;
1221 case 'n':
1222 $num = intval( substr( $ts, 4, 2 ) );
1223 break;
1224 case 'xin':
1225 if ( !$iranian ) {
1226 $iranian = self::tsToIranian( $ts );
1228 $num = $iranian[1];
1229 break;
1230 case 'xmn':
1231 if ( !$hijri ) {
1232 $hijri = self::tsToHijri ( $ts );
1234 $num = $hijri[1];
1235 break;
1236 case 'xjn':
1237 if ( !$hebrew ) {
1238 $hebrew = self::tsToHebrew( $ts );
1240 $num = $hebrew[1];
1241 break;
1242 case 'xjt':
1243 if ( !$hebrew ) {
1244 $hebrew = self::tsToHebrew( $ts );
1246 $num = $hebrew[3];
1247 break;
1248 case 'Y':
1249 $num = substr( $ts, 0, 4 );
1250 break;
1251 case 'xiY':
1252 if ( !$iranian ) {
1253 $iranian = self::tsToIranian( $ts );
1255 $num = $iranian[0];
1256 break;
1257 case 'xmY':
1258 if ( !$hijri ) {
1259 $hijri = self::tsToHijri( $ts );
1261 $num = $hijri[0];
1262 break;
1263 case 'xjY':
1264 if ( !$hebrew ) {
1265 $hebrew = self::tsToHebrew( $ts );
1267 $num = $hebrew[0];
1268 break;
1269 case 'xkY':
1270 if ( !$thai ) {
1271 $thai = self::tsToYear( $ts, 'thai' );
1273 $num = $thai[0];
1274 break;
1275 case 'xoY':
1276 if ( !$minguo ) {
1277 $minguo = self::tsToYear( $ts, 'minguo' );
1279 $num = $minguo[0];
1280 break;
1281 case 'xtY':
1282 if ( !$tenno ) {
1283 $tenno = self::tsToYear( $ts, 'tenno' );
1285 $num = $tenno[0];
1286 break;
1287 case 'y':
1288 $num = substr( $ts, 2, 2 );
1289 break;
1290 case 'xiy':
1291 if ( !$iranian ) {
1292 $iranian = self::tsToIranian( $ts );
1294 $num = substr( $iranian[0], -2 );
1295 break;
1296 case 'a':
1297 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1298 break;
1299 case 'A':
1300 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1301 break;
1302 case 'g':
1303 $h = substr( $ts, 8, 2 );
1304 $num = $h % 12 ? $h % 12 : 12;
1305 break;
1306 case 'G':
1307 $num = intval( substr( $ts, 8, 2 ) );
1308 break;
1309 case 'h':
1310 $h = substr( $ts, 8, 2 );
1311 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1312 break;
1313 case 'H':
1314 $num = substr( $ts, 8, 2 );
1315 break;
1316 case 'i':
1317 $num = substr( $ts, 10, 2 );
1318 break;
1319 case 's':
1320 $num = substr( $ts, 12, 2 );
1321 break;
1322 case 'c':
1323 case 'r':
1324 case 'e':
1325 case 'O':
1326 case 'P':
1327 case 'T':
1328 // Pass through string from $dateTimeObj->format()
1329 if ( !$dateTimeObj ) {
1330 $dateTimeObj = DateTime::createFromFormat(
1331 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1334 $s .= $dateTimeObj->format( $code );
1335 break;
1336 case 'w':
1337 case 'N':
1338 case 'z':
1339 case 'W':
1340 case 't':
1341 case 'L':
1342 case 'o':
1343 case 'U':
1344 case 'I':
1345 case 'Z':
1346 // Pass through number from $dateTimeObj->format()
1347 if ( !$dateTimeObj ) {
1348 $dateTimeObj = DateTime::createFromFormat(
1349 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1352 $num = $dateTimeObj->format( $code );
1353 break;
1354 case '\\':
1355 # Backslash escaping
1356 if ( $p < strlen( $format ) - 1 ) {
1357 $s .= $format[++$p];
1358 } else {
1359 $s .= '\\';
1361 break;
1362 case '"':
1363 # Quoted literal
1364 if ( $p < strlen( $format ) - 1 ) {
1365 $endQuote = strpos( $format, '"', $p + 1 );
1366 if ( $endQuote === false ) {
1367 # No terminating quote, assume literal "
1368 $s .= '"';
1369 } else {
1370 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1371 $p = $endQuote;
1373 } else {
1374 # Quote at end of string, assume literal "
1375 $s .= '"';
1377 break;
1378 default:
1379 $s .= $format[$p];
1381 if ( $num !== false ) {
1382 if ( $rawToggle || $raw ) {
1383 $s .= $num;
1384 $raw = false;
1385 } elseif ( $roman ) {
1386 $s .= Language::romanNumeral( $num );
1387 $roman = false;
1388 } elseif ( $hebrewNum ) {
1389 $s .= self::hebrewNumeral( $num );
1390 $hebrewNum = false;
1391 } else {
1392 $s .= $this->formatNum( $num, true );
1396 return $s;
1399 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1400 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1403 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1404 * Gregorian dates to Iranian dates. Originally written in C, it
1405 * is released under the terms of GNU Lesser General Public
1406 * License. Conversion to PHP was performed by Niklas Laxström.
1408 * Link: http://www.farsiweb.info/jalali/jalali.c
1410 * @param $ts string
1412 * @return string
1414 private static function tsToIranian( $ts ) {
1415 $gy = substr( $ts, 0, 4 ) -1600;
1416 $gm = substr( $ts, 4, 2 ) -1;
1417 $gd = substr( $ts, 6, 2 ) -1;
1419 # Days passed from the beginning (including leap years)
1420 $gDayNo = 365 * $gy
1421 + floor( ( $gy + 3 ) / 4 )
1422 - floor( ( $gy + 99 ) / 100 )
1423 + floor( ( $gy + 399 ) / 400 );
1425 // Add days of the past months of this year
1426 for ( $i = 0; $i < $gm; $i++ ) {
1427 $gDayNo += self::$GREG_DAYS[$i];
1430 // Leap years
1431 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1432 $gDayNo++;
1435 // Days passed in current month
1436 $gDayNo += (int)$gd;
1438 $jDayNo = $gDayNo - 79;
1440 $jNp = floor( $jDayNo / 12053 );
1441 $jDayNo %= 12053;
1443 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1444 $jDayNo %= 1461;
1446 if ( $jDayNo >= 366 ) {
1447 $jy += floor( ( $jDayNo - 1 ) / 365 );
1448 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1451 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1452 $jDayNo -= self::$IRANIAN_DAYS[$i];
1455 $jm = $i + 1;
1456 $jd = $jDayNo + 1;
1458 return array( $jy, $jm, $jd );
1462 * Converting Gregorian dates to Hijri dates.
1464 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1466 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1468 * @param $ts string
1470 * @return string
1472 private static function tsToHijri( $ts ) {
1473 $year = substr( $ts, 0, 4 );
1474 $month = substr( $ts, 4, 2 );
1475 $day = substr( $ts, 6, 2 );
1477 $zyr = $year;
1478 $zd = $day;
1479 $zm = $month;
1480 $zy = $zyr;
1482 if (
1483 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1484 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1487 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1488 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1489 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1490 $zd - 32075;
1491 } else {
1492 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1493 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1496 $zl = $zjd -1948440 + 10632;
1497 $zn = (int)( ( $zl - 1 ) / 10631 );
1498 $zl = $zl - 10631 * $zn + 354;
1499 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1500 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1501 $zm = (int)( ( 24 * $zl ) / 709 );
1502 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1503 $zy = 30 * $zn + $zj - 30;
1505 return array( $zy, $zm, $zd );
1509 * Converting Gregorian dates to Hebrew dates.
1511 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1512 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1513 * to translate the relevant functions into PHP and release them under
1514 * GNU GPL.
1516 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1517 * and Adar II is 14. In a non-leap year, Adar is 6.
1519 * @param $ts string
1521 * @return string
1523 private static function tsToHebrew( $ts ) {
1524 # Parse date
1525 $year = substr( $ts, 0, 4 );
1526 $month = substr( $ts, 4, 2 );
1527 $day = substr( $ts, 6, 2 );
1529 # Calculate Hebrew year
1530 $hebrewYear = $year + 3760;
1532 # Month number when September = 1, August = 12
1533 $month += 4;
1534 if ( $month > 12 ) {
1535 # Next year
1536 $month -= 12;
1537 $year++;
1538 $hebrewYear++;
1541 # Calculate day of year from 1 September
1542 $dayOfYear = $day;
1543 for ( $i = 1; $i < $month; $i++ ) {
1544 if ( $i == 6 ) {
1545 # February
1546 $dayOfYear += 28;
1547 # Check if the year is leap
1548 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1549 $dayOfYear++;
1551 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1552 $dayOfYear += 30;
1553 } else {
1554 $dayOfYear += 31;
1558 # Calculate the start of the Hebrew year
1559 $start = self::hebrewYearStart( $hebrewYear );
1561 # Calculate next year's start
1562 if ( $dayOfYear <= $start ) {
1563 # Day is before the start of the year - it is the previous year
1564 # Next year's start
1565 $nextStart = $start;
1566 # Previous year
1567 $year--;
1568 $hebrewYear--;
1569 # Add days since previous year's 1 September
1570 $dayOfYear += 365;
1571 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1572 # Leap year
1573 $dayOfYear++;
1575 # Start of the new (previous) year
1576 $start = self::hebrewYearStart( $hebrewYear );
1577 } else {
1578 # Next year's start
1579 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1582 # Calculate Hebrew day of year
1583 $hebrewDayOfYear = $dayOfYear - $start;
1585 # Difference between year's days
1586 $diff = $nextStart - $start;
1587 # Add 12 (or 13 for leap years) days to ignore the difference between
1588 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1589 # difference is only about the year type
1590 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1591 $diff += 13;
1592 } else {
1593 $diff += 12;
1596 # Check the year pattern, and is leap year
1597 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1598 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1599 # and non-leap years
1600 $yearPattern = $diff % 30;
1601 # Check if leap year
1602 $isLeap = $diff >= 30;
1604 # Calculate day in the month from number of day in the Hebrew year
1605 # Don't check Adar - if the day is not in Adar, we will stop before;
1606 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1607 $hebrewDay = $hebrewDayOfYear;
1608 $hebrewMonth = 1;
1609 $days = 0;
1610 while ( $hebrewMonth <= 12 ) {
1611 # Calculate days in this month
1612 if ( $isLeap && $hebrewMonth == 6 ) {
1613 # Adar in a leap year
1614 if ( $isLeap ) {
1615 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1616 $days = 30;
1617 if ( $hebrewDay <= $days ) {
1618 # Day in Adar I
1619 $hebrewMonth = 13;
1620 } else {
1621 # Subtract the days of Adar I
1622 $hebrewDay -= $days;
1623 # Try Adar II
1624 $days = 29;
1625 if ( $hebrewDay <= $days ) {
1626 # Day in Adar II
1627 $hebrewMonth = 14;
1631 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1632 # Cheshvan in a complete year (otherwise as the rule below)
1633 $days = 30;
1634 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1635 # Kislev in an incomplete year (otherwise as the rule below)
1636 $days = 29;
1637 } else {
1638 # Odd months have 30 days, even have 29
1639 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1641 if ( $hebrewDay <= $days ) {
1642 # In the current month
1643 break;
1644 } else {
1645 # Subtract the days of the current month
1646 $hebrewDay -= $days;
1647 # Try in the next month
1648 $hebrewMonth++;
1652 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1656 * This calculates the Hebrew year start, as days since 1 September.
1657 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1658 * Used for Hebrew date.
1660 * @param $year int
1662 * @return string
1664 private static function hebrewYearStart( $year ) {
1665 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1666 $b = intval( ( $year - 1 ) % 4 );
1667 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1668 if ( $m < 0 ) {
1669 $m--;
1671 $Mar = intval( $m );
1672 if ( $m < 0 ) {
1673 $m++;
1675 $m -= $Mar;
1677 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1678 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1679 $Mar++;
1680 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1681 $Mar += 2;
1682 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1683 $Mar++;
1686 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1687 return $Mar;
1691 * Algorithm to convert Gregorian dates to Thai solar dates,
1692 * Minguo dates or Minguo dates.
1694 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1695 * http://en.wikipedia.org/wiki/Minguo_calendar
1696 * http://en.wikipedia.org/wiki/Japanese_era_name
1698 * @param $ts String: 14-character timestamp
1699 * @param $cName String: calender name
1700 * @return Array: converted year, month, day
1702 private static function tsToYear( $ts, $cName ) {
1703 $gy = substr( $ts, 0, 4 );
1704 $gm = substr( $ts, 4, 2 );
1705 $gd = substr( $ts, 6, 2 );
1707 if ( !strcmp( $cName, 'thai' ) ) {
1708 # Thai solar dates
1709 # Add 543 years to the Gregorian calendar
1710 # Months and days are identical
1711 $gy_offset = $gy + 543;
1712 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1713 # Minguo dates
1714 # Deduct 1911 years from the Gregorian calendar
1715 # Months and days are identical
1716 $gy_offset = $gy - 1911;
1717 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1718 # Nengō dates up to Meiji period
1719 # Deduct years from the Gregorian calendar
1720 # depending on the nengo periods
1721 # Months and days are identical
1722 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1723 # Meiji period
1724 $gy_gannen = $gy - 1868 + 1;
1725 $gy_offset = $gy_gannen;
1726 if ( $gy_gannen == 1 ) {
1727 $gy_offset = '元';
1729 $gy_offset = '明治' . $gy_offset;
1730 } elseif (
1731 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1732 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1733 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1734 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1735 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1738 # Taishō period
1739 $gy_gannen = $gy - 1912 + 1;
1740 $gy_offset = $gy_gannen;
1741 if ( $gy_gannen == 1 ) {
1742 $gy_offset = '元';
1744 $gy_offset = '大正' . $gy_offset;
1745 } elseif (
1746 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1747 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1748 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1751 # Shōwa period
1752 $gy_gannen = $gy - 1926 + 1;
1753 $gy_offset = $gy_gannen;
1754 if ( $gy_gannen == 1 ) {
1755 $gy_offset = '元';
1757 $gy_offset = '昭和' . $gy_offset;
1758 } else {
1759 # Heisei period
1760 $gy_gannen = $gy - 1989 + 1;
1761 $gy_offset = $gy_gannen;
1762 if ( $gy_gannen == 1 ) {
1763 $gy_offset = '元';
1765 $gy_offset = '平成' . $gy_offset;
1767 } else {
1768 $gy_offset = $gy;
1771 return array( $gy_offset, $gm, $gd );
1775 * Roman number formatting up to 10000
1777 * @param $num int
1779 * @return string
1781 static function romanNumeral( $num ) {
1782 static $table = array(
1783 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1784 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1785 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1786 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1789 $num = intval( $num );
1790 if ( $num > 10000 || $num <= 0 ) {
1791 return $num;
1794 $s = '';
1795 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1796 if ( $num >= $pow10 ) {
1797 $s .= $table[$i][(int)floor( $num / $pow10 )];
1799 $num = $num % $pow10;
1801 return $s;
1805 * Hebrew Gematria number formatting up to 9999
1807 * @param $num int
1809 * @return string
1811 static function hebrewNumeral( $num ) {
1812 static $table = array(
1813 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1814 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1815 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1816 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1819 $num = intval( $num );
1820 if ( $num > 9999 || $num <= 0 ) {
1821 return $num;
1824 $s = '';
1825 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1826 if ( $num >= $pow10 ) {
1827 if ( $num == 15 || $num == 16 ) {
1828 $s .= $table[0][9] . $table[0][$num - 9];
1829 $num = 0;
1830 } else {
1831 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1832 if ( $pow10 == 1000 ) {
1833 $s .= "'";
1837 $num = $num % $pow10;
1839 if ( strlen( $s ) == 2 ) {
1840 $str = $s . "'";
1841 } else {
1842 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1843 $str .= substr( $s, strlen( $s ) - 2, 2 );
1845 $start = substr( $str, 0, strlen( $str ) - 2 );
1846 $end = substr( $str, strlen( $str ) - 2 );
1847 switch ( $end ) {
1848 case 'כ':
1849 $str = $start . 'ך';
1850 break;
1851 case 'מ':
1852 $str = $start . 'ם';
1853 break;
1854 case 'נ':
1855 $str = $start . 'ן';
1856 break;
1857 case 'פ':
1858 $str = $start . 'ף';
1859 break;
1860 case 'צ':
1861 $str = $start . 'ץ';
1862 break;
1864 return $str;
1868 * Used by date() and time() to adjust the time output.
1870 * @param $ts Int the time in date('YmdHis') format
1871 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1872 * get user timecorrection setting)
1873 * @return int
1875 function userAdjust( $ts, $tz = false ) {
1876 global $wgUser, $wgLocalTZoffset;
1878 if ( $tz === false ) {
1879 $tz = $wgUser->getOption( 'timecorrection' );
1882 $data = explode( '|', $tz, 3 );
1884 if ( $data[0] == 'ZoneInfo' ) {
1885 wfSuppressWarnings();
1886 $userTZ = timezone_open( $data[2] );
1887 wfRestoreWarnings();
1888 if ( $userTZ !== false ) {
1889 $date = date_create( $ts, timezone_open( 'UTC' ) );
1890 date_timezone_set( $date, $userTZ );
1891 $date = date_format( $date, 'YmdHis' );
1892 return $date;
1894 # Unrecognized timezone, default to 'Offset' with the stored offset.
1895 $data[0] = 'Offset';
1898 $minDiff = 0;
1899 if ( $data[0] == 'System' || $tz == '' ) {
1900 #  Global offset in minutes.
1901 if ( isset( $wgLocalTZoffset ) ) {
1902 $minDiff = $wgLocalTZoffset;
1904 } elseif ( $data[0] == 'Offset' ) {
1905 $minDiff = intval( $data[1] );
1906 } else {
1907 $data = explode( ':', $tz );
1908 if ( count( $data ) == 2 ) {
1909 $data[0] = intval( $data[0] );
1910 $data[1] = intval( $data[1] );
1911 $minDiff = abs( $data[0] ) * 60 + $data[1];
1912 if ( $data[0] < 0 ) {
1913 $minDiff = -$minDiff;
1915 } else {
1916 $minDiff = intval( $data[0] ) * 60;
1920 # No difference ? Return time unchanged
1921 if ( 0 == $minDiff ) {
1922 return $ts;
1925 wfSuppressWarnings(); // E_STRICT system time bitching
1926 # Generate an adjusted date; take advantage of the fact that mktime
1927 # will normalize out-of-range values so we don't have to split $minDiff
1928 # into hours and minutes.
1929 $t = mktime( (
1930 (int)substr( $ts, 8, 2 ) ), # Hours
1931 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1932 (int)substr( $ts, 12, 2 ), # Seconds
1933 (int)substr( $ts, 4, 2 ), # Month
1934 (int)substr( $ts, 6, 2 ), # Day
1935 (int)substr( $ts, 0, 4 ) ); # Year
1937 $date = date( 'YmdHis', $t );
1938 wfRestoreWarnings();
1940 return $date;
1944 * This is meant to be used by time(), date(), and timeanddate() to get
1945 * the date preference they're supposed to use, it should be used in
1946 * all children.
1948 *<code>
1949 * function timeanddate([...], $format = true) {
1950 * $datePreference = $this->dateFormat($format);
1951 * [...]
1953 *</code>
1955 * @param $usePrefs Mixed: if true, the user's preference is used
1956 * if false, the site/language default is used
1957 * if int/string, assumed to be a format.
1958 * @return string
1960 function dateFormat( $usePrefs = true ) {
1961 global $wgUser;
1963 if ( is_bool( $usePrefs ) ) {
1964 if ( $usePrefs ) {
1965 $datePreference = $wgUser->getDatePreference();
1966 } else {
1967 $datePreference = (string)User::getDefaultOption( 'date' );
1969 } else {
1970 $datePreference = (string)$usePrefs;
1973 // return int
1974 if ( $datePreference == '' ) {
1975 return 'default';
1978 return $datePreference;
1982 * Get a format string for a given type and preference
1983 * @param $type string May be date, time or both
1984 * @param $pref string The format name as it appears in Messages*.php
1986 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1988 * @return string
1990 function getDateFormatString( $type, $pref ) {
1991 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1992 if ( $pref == 'default' ) {
1993 $pref = $this->getDefaultDateFormat();
1994 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1995 } else {
1996 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1998 if ( $type === 'pretty' && $df === null ) {
1999 $df = $this->getDateFormatString( 'date', $pref );
2002 if ( $df === null ) {
2003 $pref = $this->getDefaultDateFormat();
2004 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2007 $this->dateFormatStrings[$type][$pref] = $df;
2009 return $this->dateFormatStrings[$type][$pref];
2013 * @param $ts Mixed: the time format which needs to be turned into a
2014 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2015 * @param $adj Bool: whether to adjust the time output according to the
2016 * user configured offset ($timecorrection)
2017 * @param $format Mixed: true to use user's date format preference
2018 * @param $timecorrection String|bool the time offset as returned by
2019 * validateTimeZone() in Special:Preferences
2020 * @return string
2022 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2023 $ts = wfTimestamp( TS_MW, $ts );
2024 if ( $adj ) {
2025 $ts = $this->userAdjust( $ts, $timecorrection );
2027 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2028 return $this->sprintfDate( $df, $ts );
2032 * @param $ts Mixed: the time format which needs to be turned into a
2033 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2034 * @param $adj Bool: whether to adjust the time output according to the
2035 * user configured offset ($timecorrection)
2036 * @param $format Mixed: true to use user's date format preference
2037 * @param $timecorrection String|bool the time offset as returned by
2038 * validateTimeZone() in Special:Preferences
2039 * @return string
2041 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2042 $ts = wfTimestamp( TS_MW, $ts );
2043 if ( $adj ) {
2044 $ts = $this->userAdjust( $ts, $timecorrection );
2046 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2047 return $this->sprintfDate( $df, $ts );
2051 * @param $ts Mixed: the time format which needs to be turned into a
2052 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2053 * @param $adj Bool: whether to adjust the time output according to the
2054 * user configured offset ($timecorrection)
2055 * @param $format Mixed: what format to return, if it's false output the
2056 * default one (default true)
2057 * @param $timecorrection String|bool the time offset as returned by
2058 * validateTimeZone() in Special:Preferences
2059 * @return string
2061 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2062 $ts = wfTimestamp( TS_MW, $ts );
2063 if ( $adj ) {
2064 $ts = $this->userAdjust( $ts, $timecorrection );
2066 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2067 return $this->sprintfDate( $df, $ts );
2071 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2073 * @since 1.20
2075 * @param integer $seconds The amount of seconds.
2076 * @param array $chosenIntervals The intervals to enable.
2078 * @return string
2080 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2081 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2083 $segments = array();
2085 foreach ( $intervals as $intervalName => $intervalValue ) {
2086 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2087 $segments[] = $message->inLanguage( $this )->escaped();
2090 return $this->listToText( $segments );
2094 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2095 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2097 * @since 1.20
2099 * @param integer $seconds The amount of seconds.
2100 * @param array $chosenIntervals The intervals to enable.
2102 * @return array
2104 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2105 if ( empty( $chosenIntervals ) ) {
2106 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2109 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2110 $sortedNames = array_keys( $intervals );
2111 $smallestInterval = array_pop( $sortedNames );
2113 $segments = array();
2115 foreach ( $intervals as $name => $length ) {
2116 $value = floor( $seconds / $length );
2118 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2119 $seconds -= $value * $length;
2120 $segments[$name] = $value;
2124 return $segments;
2128 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2130 * @param $type String: can be 'date', 'time' or 'both'
2131 * @param $ts Mixed: the time format which needs to be turned into a
2132 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2133 * @param $user User object used to get preferences for timezone and format
2134 * @param $options Array, can contain the following keys:
2135 * - 'timecorrection': time correction, can have the following values:
2136 * - true: use user's preference
2137 * - false: don't use time correction
2138 * - integer: value of time correction in minutes
2139 * - 'format': format to use, can have the following values:
2140 * - true: use user's preference
2141 * - false: use default preference
2142 * - string: format to use
2143 * @since 1.19
2144 * @return String
2146 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2147 $ts = wfTimestamp( TS_MW, $ts );
2148 $options += array( 'timecorrection' => true, 'format' => true );
2149 if ( $options['timecorrection'] !== false ) {
2150 if ( $options['timecorrection'] === true ) {
2151 $offset = $user->getOption( 'timecorrection' );
2152 } else {
2153 $offset = $options['timecorrection'];
2155 $ts = $this->userAdjust( $ts, $offset );
2157 if ( $options['format'] === true ) {
2158 $format = $user->getDatePreference();
2159 } else {
2160 $format = $options['format'];
2162 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2163 return $this->sprintfDate( $df, $ts );
2167 * Get the formatted date for the given timestamp and formatted for
2168 * the given user.
2170 * @param $ts Mixed: the time format which needs to be turned into a
2171 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2172 * @param $user User object used to get preferences for timezone and format
2173 * @param $options Array, can contain the following keys:
2174 * - 'timecorrection': time correction, can have the following values:
2175 * - true: use user's preference
2176 * - false: don't use time correction
2177 * - integer: value of time correction in minutes
2178 * - 'format': format to use, can have the following values:
2179 * - true: use user's preference
2180 * - false: use default preference
2181 * - string: format to use
2182 * @since 1.19
2183 * @return String
2185 public function userDate( $ts, User $user, array $options = array() ) {
2186 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2190 * Get the formatted time for the given timestamp and formatted for
2191 * the given user.
2193 * @param $ts Mixed: the time format which needs to be turned into a
2194 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2195 * @param $user User object used to get preferences for timezone and format
2196 * @param $options Array, can contain the following keys:
2197 * - 'timecorrection': time correction, can have the following values:
2198 * - true: use user's preference
2199 * - false: don't use time correction
2200 * - integer: value of time correction in minutes
2201 * - 'format': format to use, can have the following values:
2202 * - true: use user's preference
2203 * - false: use default preference
2204 * - string: format to use
2205 * @since 1.19
2206 * @return String
2208 public function userTime( $ts, User $user, array $options = array() ) {
2209 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2213 * Get the formatted date and time for the given timestamp and formatted for
2214 * the given user.
2216 * @param $ts Mixed: the time format which needs to be turned into a
2217 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2218 * @param $user User object used to get preferences for timezone and format
2219 * @param $options Array, can contain the following keys:
2220 * - 'timecorrection': time correction, can have the following values:
2221 * - true: use user's preference
2222 * - false: don't use time correction
2223 * - integer: value of time correction in minutes
2224 * - 'format': format to use, can have the following values:
2225 * - true: use user's preference
2226 * - false: use default preference
2227 * - string: format to use
2228 * @since 1.19
2229 * @return String
2231 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2232 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2236 * Convert an MWTimestamp into a pretty human-readable timestamp using
2237 * the given user preferences and relative base time.
2239 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2240 * on your timestamp object, which will then call this function. Calling
2241 * this function directly will cause hooks to be skipped over.
2243 * @see MWTimestamp::getHumanTimestamp
2244 * @param MWTimestamp $ts Timestamp to prettify
2245 * @param MWTimestamp $relativeTo Base timestamp
2246 * @param User $user User preferences to use
2247 * @return string Human timestamp
2248 * @since 1.21
2250 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2251 $diff = $ts->diff( $relativeTo );
2252 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) - (int)$relativeTo->timestamp->format( 'w' ) );
2253 $days = $diff->days ?: (int)$diffDay;
2254 if ( $diff->invert || $days > 5 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' ) ) {
2255 // Timestamps are in different years: use full timestamp
2256 // Also do full timestamp for future dates
2258 * @FIXME Add better handling of future timestamps.
2260 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2261 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2262 } elseif ( $days > 5 ) {
2263 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2264 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2265 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2266 } elseif ( $days > 1 ) {
2267 // Timestamp within the past week: show the day of the week and time
2268 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2269 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2270 $ts = wfMessage( "$weekday-at" )
2271 ->inLanguage( $this )
2272 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2273 ->text();
2274 } elseif ( $days == 1 ) {
2275 // Timestamp was yesterday: say 'yesterday' and the time.
2276 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2277 $ts = wfMessage( 'yesterday-at' )
2278 ->inLanguage( $this )
2279 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2280 ->text();
2281 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2282 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2283 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2284 $ts = wfMessage( 'today-at' )
2285 ->inLanguage( $this )
2286 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2287 ->text();
2289 // From here on in, the timestamp was soon enough ago so that we can simply say
2290 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2291 } elseif ( $diff->h == 1 ) {
2292 // Less than 90 minutes, but more than an hour ago.
2293 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2294 } elseif ( $diff->i >= 1 ) {
2295 // A few minutes ago.
2296 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2297 } elseif ( $diff->s >= 30 ) {
2298 // Less than a minute, but more than 30 sec ago.
2299 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2300 } else {
2301 // Less than 30 seconds ago.
2302 $ts = wfMessage( 'just-now' )->text();
2305 return $ts;
2309 * @param $key string
2310 * @return array|null
2312 function getMessage( $key ) {
2313 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2317 * @return array
2319 function getAllMessages() {
2320 return self::$dataCache->getItem( $this->mCode, 'messages' );
2324 * @param $in
2325 * @param $out
2326 * @param $string
2327 * @return string
2329 function iconv( $in, $out, $string ) {
2330 # This is a wrapper for iconv in all languages except esperanto,
2331 # which does some nasty x-conversions beforehand
2333 # Even with //IGNORE iconv can whine about illegal characters in
2334 # *input* string. We just ignore those too.
2335 # REF: http://bugs.php.net/bug.php?id=37166
2336 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2337 wfSuppressWarnings();
2338 $text = iconv( $in, $out . '//IGNORE', $string );
2339 wfRestoreWarnings();
2340 return $text;
2343 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2346 * @param $matches array
2347 * @return mixed|string
2349 function ucwordbreaksCallbackAscii( $matches ) {
2350 return $this->ucfirst( $matches[1] );
2354 * @param $matches array
2355 * @return string
2357 function ucwordbreaksCallbackMB( $matches ) {
2358 return mb_strtoupper( $matches[0] );
2362 * @param $matches array
2363 * @return string
2365 function ucCallback( $matches ) {
2366 list( $wikiUpperChars ) = self::getCaseMaps();
2367 return strtr( $matches[1], $wikiUpperChars );
2371 * @param $matches array
2372 * @return string
2374 function lcCallback( $matches ) {
2375 list( , $wikiLowerChars ) = self::getCaseMaps();
2376 return strtr( $matches[1], $wikiLowerChars );
2380 * @param $matches array
2381 * @return string
2383 function ucwordsCallbackMB( $matches ) {
2384 return mb_strtoupper( $matches[0] );
2388 * @param $matches array
2389 * @return string
2391 function ucwordsCallbackWiki( $matches ) {
2392 list( $wikiUpperChars ) = self::getCaseMaps();
2393 return strtr( $matches[0], $wikiUpperChars );
2397 * Make a string's first character uppercase
2399 * @param $str string
2401 * @return string
2403 function ucfirst( $str ) {
2404 $o = ord( $str );
2405 if ( $o < 96 ) { // if already uppercase...
2406 return $str;
2407 } elseif ( $o < 128 ) {
2408 return ucfirst( $str ); // use PHP's ucfirst()
2409 } else {
2410 // fall back to more complex logic in case of multibyte strings
2411 return $this->uc( $str, true );
2416 * Convert a string to uppercase
2418 * @param $str string
2419 * @param $first bool
2421 * @return string
2423 function uc( $str, $first = false ) {
2424 if ( function_exists( 'mb_strtoupper' ) ) {
2425 if ( $first ) {
2426 if ( $this->isMultibyte( $str ) ) {
2427 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2428 } else {
2429 return ucfirst( $str );
2431 } else {
2432 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2434 } else {
2435 if ( $this->isMultibyte( $str ) ) {
2436 $x = $first ? '^' : '';
2437 return preg_replace_callback(
2438 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2439 array( $this, 'ucCallback' ),
2440 $str
2442 } else {
2443 return $first ? ucfirst( $str ) : strtoupper( $str );
2449 * @param $str string
2450 * @return mixed|string
2452 function lcfirst( $str ) {
2453 $o = ord( $str );
2454 if ( !$o ) {
2455 return strval( $str );
2456 } elseif ( $o >= 128 ) {
2457 return $this->lc( $str, true );
2458 } elseif ( $o > 96 ) {
2459 return $str;
2460 } else {
2461 $str[0] = strtolower( $str[0] );
2462 return $str;
2467 * @param $str string
2468 * @param $first bool
2469 * @return mixed|string
2471 function lc( $str, $first = false ) {
2472 if ( function_exists( 'mb_strtolower' ) ) {
2473 if ( $first ) {
2474 if ( $this->isMultibyte( $str ) ) {
2475 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2476 } else {
2477 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2479 } else {
2480 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2482 } else {
2483 if ( $this->isMultibyte( $str ) ) {
2484 $x = $first ? '^' : '';
2485 return preg_replace_callback(
2486 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2487 array( $this, 'lcCallback' ),
2488 $str
2490 } else {
2491 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2497 * @param $str string
2498 * @return bool
2500 function isMultibyte( $str ) {
2501 return (bool)preg_match( '/[\x80-\xff]/', $str );
2505 * @param $str string
2506 * @return mixed|string
2508 function ucwords( $str ) {
2509 if ( $this->isMultibyte( $str ) ) {
2510 $str = $this->lc( $str );
2512 // regexp to find first letter in each word (i.e. after each space)
2513 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2515 // function to use to capitalize a single char
2516 if ( function_exists( 'mb_strtoupper' ) ) {
2517 return preg_replace_callback(
2518 $replaceRegexp,
2519 array( $this, 'ucwordsCallbackMB' ),
2520 $str
2522 } else {
2523 return preg_replace_callback(
2524 $replaceRegexp,
2525 array( $this, 'ucwordsCallbackWiki' ),
2526 $str
2529 } else {
2530 return ucwords( strtolower( $str ) );
2535 * capitalize words at word breaks
2537 * @param $str string
2538 * @return mixed
2540 function ucwordbreaks( $str ) {
2541 if ( $this->isMultibyte( $str ) ) {
2542 $str = $this->lc( $str );
2544 // since \b doesn't work for UTF-8, we explicitely define word break chars
2545 $breaks = "[ \-\(\)\}\{\.,\?!]";
2547 // find first letter after word break
2548 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2550 if ( function_exists( 'mb_strtoupper' ) ) {
2551 return preg_replace_callback(
2552 $replaceRegexp,
2553 array( $this, 'ucwordbreaksCallbackMB' ),
2554 $str
2556 } else {
2557 return preg_replace_callback(
2558 $replaceRegexp,
2559 array( $this, 'ucwordsCallbackWiki' ),
2560 $str
2563 } else {
2564 return preg_replace_callback(
2565 '/\b([\w\x80-\xff]+)\b/',
2566 array( $this, 'ucwordbreaksCallbackAscii' ),
2567 $str
2573 * Return a case-folded representation of $s
2575 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2576 * and $s2 are the same except for the case of their characters. It is not
2577 * necessary for the value returned to make sense when displayed.
2579 * Do *not* perform any other normalisation in this function. If a caller
2580 * uses this function when it should be using a more general normalisation
2581 * function, then fix the caller.
2583 * @param $s string
2585 * @return string
2587 function caseFold( $s ) {
2588 return $this->uc( $s );
2592 * @param $s string
2593 * @return string
2595 function checkTitleEncoding( $s ) {
2596 if ( is_array( $s ) ) {
2597 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2599 if ( StringUtils::isUtf8( $s ) ) {
2600 return $s;
2603 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2607 * @return array
2609 function fallback8bitEncoding() {
2610 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2614 * Most writing systems use whitespace to break up words.
2615 * Some languages such as Chinese don't conventionally do this,
2616 * which requires special handling when breaking up words for
2617 * searching etc.
2619 * @return bool
2621 function hasWordBreaks() {
2622 return true;
2626 * Some languages such as Chinese require word segmentation,
2627 * Specify such segmentation when overridden in derived class.
2629 * @param $string String
2630 * @return String
2632 function segmentByWord( $string ) {
2633 return $string;
2637 * Some languages have special punctuation need to be normalized.
2638 * Make such changes here.
2640 * @param $string String
2641 * @return String
2643 function normalizeForSearch( $string ) {
2644 return self::convertDoubleWidth( $string );
2648 * convert double-width roman characters to single-width.
2649 * range: ff00-ff5f ~= 0020-007f
2651 * @param $string string
2653 * @return string
2655 protected static function convertDoubleWidth( $string ) {
2656 static $full = null;
2657 static $half = null;
2659 if ( $full === null ) {
2660 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2661 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2662 $full = str_split( $fullWidth, 3 );
2663 $half = str_split( $halfWidth );
2666 $string = str_replace( $full, $half, $string );
2667 return $string;
2671 * @param $string string
2672 * @param $pattern string
2673 * @return string
2675 protected static function insertSpace( $string, $pattern ) {
2676 $string = preg_replace( $pattern, " $1 ", $string );
2677 $string = preg_replace( '/ +/', ' ', $string );
2678 return $string;
2682 * @param $termsArray array
2683 * @return array
2685 function convertForSearchResult( $termsArray ) {
2686 # some languages, e.g. Chinese, need to do a conversion
2687 # in order for search results to be displayed correctly
2688 return $termsArray;
2692 * Get the first character of a string.
2694 * @param $s string
2695 * @return string
2697 function firstChar( $s ) {
2698 $matches = array();
2699 preg_match(
2700 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2701 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2703 $matches
2706 if ( isset( $matches[1] ) ) {
2707 if ( strlen( $matches[1] ) != 3 ) {
2708 return $matches[1];
2711 // Break down Hangul syllables to grab the first jamo
2712 $code = utf8ToCodepoint( $matches[1] );
2713 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2714 return $matches[1];
2715 } elseif ( $code < 0xb098 ) {
2716 return "\xe3\x84\xb1";
2717 } elseif ( $code < 0xb2e4 ) {
2718 return "\xe3\x84\xb4";
2719 } elseif ( $code < 0xb77c ) {
2720 return "\xe3\x84\xb7";
2721 } elseif ( $code < 0xb9c8 ) {
2722 return "\xe3\x84\xb9";
2723 } elseif ( $code < 0xbc14 ) {
2724 return "\xe3\x85\x81";
2725 } elseif ( $code < 0xc0ac ) {
2726 return "\xe3\x85\x82";
2727 } elseif ( $code < 0xc544 ) {
2728 return "\xe3\x85\x85";
2729 } elseif ( $code < 0xc790 ) {
2730 return "\xe3\x85\x87";
2731 } elseif ( $code < 0xcc28 ) {
2732 return "\xe3\x85\x88";
2733 } elseif ( $code < 0xce74 ) {
2734 return "\xe3\x85\x8a";
2735 } elseif ( $code < 0xd0c0 ) {
2736 return "\xe3\x85\x8b";
2737 } elseif ( $code < 0xd30c ) {
2738 return "\xe3\x85\x8c";
2739 } elseif ( $code < 0xd558 ) {
2740 return "\xe3\x85\x8d";
2741 } else {
2742 return "\xe3\x85\x8e";
2744 } else {
2745 return '';
2749 function initEncoding() {
2750 # Some languages may have an alternate char encoding option
2751 # (Esperanto X-coding, Japanese furigana conversion, etc)
2752 # If this language is used as the primary content language,
2753 # an override to the defaults can be set here on startup.
2757 * @param $s string
2758 * @return string
2760 function recodeForEdit( $s ) {
2761 # For some languages we'll want to explicitly specify
2762 # which characters make it into the edit box raw
2763 # or are converted in some way or another.
2764 global $wgEditEncoding;
2765 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2766 return $s;
2767 } else {
2768 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2773 * @param $s string
2774 * @return string
2776 function recodeInput( $s ) {
2777 # Take the previous into account.
2778 global $wgEditEncoding;
2779 if ( $wgEditEncoding != '' ) {
2780 $enc = $wgEditEncoding;
2781 } else {
2782 $enc = 'UTF-8';
2784 if ( $enc == 'UTF-8' ) {
2785 return $s;
2786 } else {
2787 return $this->iconv( $enc, 'UTF-8', $s );
2792 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2793 * also cleans up certain backwards-compatible sequences, converting them
2794 * to the modern Unicode equivalent.
2796 * This is language-specific for performance reasons only.
2798 * @param $s string
2800 * @return string
2802 function normalize( $s ) {
2803 global $wgAllUnicodeFixes;
2804 $s = UtfNormal::cleanUp( $s );
2805 if ( $wgAllUnicodeFixes ) {
2806 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2807 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2810 return $s;
2814 * Transform a string using serialized data stored in the given file (which
2815 * must be in the serialized subdirectory of $IP). The file contains pairs
2816 * mapping source characters to destination characters.
2818 * The data is cached in process memory. This will go faster if you have the
2819 * FastStringSearch extension.
2821 * @param $file string
2822 * @param $string string
2824 * @throws MWException
2825 * @return string
2827 function transformUsingPairFile( $file, $string ) {
2828 if ( !isset( $this->transformData[$file] ) ) {
2829 $data = wfGetPrecompiledData( $file );
2830 if ( $data === false ) {
2831 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2833 $this->transformData[$file] = new ReplacementArray( $data );
2835 return $this->transformData[$file]->replace( $string );
2839 * For right-to-left language support
2841 * @return bool
2843 function isRTL() {
2844 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2848 * Return the correct HTML 'dir' attribute value for this language.
2849 * @return String
2851 function getDir() {
2852 return $this->isRTL() ? 'rtl' : 'ltr';
2856 * Return 'left' or 'right' as appropriate alignment for line-start
2857 * for this language's text direction.
2859 * Should be equivalent to CSS3 'start' text-align value....
2861 * @return String
2863 function alignStart() {
2864 return $this->isRTL() ? 'right' : 'left';
2868 * Return 'right' or 'left' as appropriate alignment for line-end
2869 * for this language's text direction.
2871 * Should be equivalent to CSS3 'end' text-align value....
2873 * @return String
2875 function alignEnd() {
2876 return $this->isRTL() ? 'left' : 'right';
2880 * A hidden direction mark (LRM or RLM), depending on the language direction.
2881 * Unlike getDirMark(), this function returns the character as an HTML entity.
2882 * This function should be used when the output is guaranteed to be HTML,
2883 * because it makes the output HTML source code more readable. When
2884 * the output is plain text or can be escaped, getDirMark() should be used.
2886 * @param $opposite Boolean Get the direction mark opposite to your language
2887 * @return string
2888 * @since 1.20
2890 function getDirMarkEntity( $opposite = false ) {
2891 if ( $opposite ) {
2892 return $this->isRTL() ? '&lrm;' : '&rlm;';
2894 return $this->isRTL() ? '&rlm;' : '&lrm;';
2898 * A hidden direction mark (LRM or RLM), depending on the language direction.
2899 * This function produces them as invisible Unicode characters and
2900 * the output may be hard to read and debug, so it should only be used
2901 * when the output is plain text or can be escaped. When the output is
2902 * HTML, use getDirMarkEntity() instead.
2904 * @param $opposite Boolean Get the direction mark opposite to your language
2905 * @return string
2907 function getDirMark( $opposite = false ) {
2908 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2909 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2910 if ( $opposite ) {
2911 return $this->isRTL() ? $lrm : $rlm;
2913 return $this->isRTL() ? $rlm : $lrm;
2917 * @return array
2919 function capitalizeAllNouns() {
2920 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2924 * An arrow, depending on the language direction.
2926 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2927 * @return string
2929 function getArrow( $direction = 'forwards' ) {
2930 switch ( $direction ) {
2931 case 'forwards':
2932 return $this->isRTL() ? '←' : '→';
2933 case 'backwards':
2934 return $this->isRTL() ? '→' : '←';
2935 case 'left':
2936 return '←';
2937 case 'right':
2938 return '→';
2939 case 'up':
2940 return '↑';
2941 case 'down':
2942 return '↓';
2947 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2949 * @return bool
2951 function linkPrefixExtension() {
2952 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2956 * @return array
2958 function getMagicWords() {
2959 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2962 protected function doMagicHook() {
2963 if ( $this->mMagicHookDone ) {
2964 return;
2966 $this->mMagicHookDone = true;
2967 wfProfileIn( 'LanguageGetMagic' );
2968 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2969 wfProfileOut( 'LanguageGetMagic' );
2973 * Fill a MagicWord object with data from here
2975 * @param $mw
2977 function getMagic( $mw ) {
2978 $this->doMagicHook();
2980 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2981 $rawEntry = $this->mMagicExtensions[$mw->mId];
2982 } else {
2983 $magicWords = $this->getMagicWords();
2984 if ( isset( $magicWords[$mw->mId] ) ) {
2985 $rawEntry = $magicWords[$mw->mId];
2986 } else {
2987 $rawEntry = false;
2991 if ( !is_array( $rawEntry ) ) {
2992 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2993 } else {
2994 $mw->mCaseSensitive = $rawEntry[0];
2995 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3000 * Add magic words to the extension array
3002 * @param $newWords array
3004 function addMagicWordsByLang( $newWords ) {
3005 $fallbackChain = $this->getFallbackLanguages();
3006 $fallbackChain = array_reverse( $fallbackChain );
3007 foreach ( $fallbackChain as $code ) {
3008 if ( isset( $newWords[$code] ) ) {
3009 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3015 * Get special page names, as an associative array
3016 * case folded alias => real name
3018 function getSpecialPageAliases() {
3019 // Cache aliases because it may be slow to load them
3020 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3021 // Initialise array
3022 $this->mExtendedSpecialPageAliases =
3023 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3024 wfRunHooks( 'LanguageGetSpecialPageAliases',
3025 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3028 return $this->mExtendedSpecialPageAliases;
3032 * Italic is unsuitable for some languages
3034 * @param $text String: the text to be emphasized.
3035 * @return string
3037 function emphasize( $text ) {
3038 return "<em>$text</em>";
3042 * Normally we output all numbers in plain en_US style, that is
3043 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3044 * point twohundredthirtyfive. However this is not suitable for all
3045 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3046 * Icelandic just want to use commas instead of dots, and dots instead
3047 * of commas like "293.291,235".
3049 * An example of this function being called:
3050 * <code>
3051 * wfMessage( 'message' )->numParams( $num )->text()
3052 * </code>
3054 * See LanguageGu.php for the Gujarati implementation and
3055 * $separatorTransformTable on MessageIs.php for
3056 * the , => . and . => , implementation.
3058 * @todo check if it's viable to use localeconv() for the decimal
3059 * separator thing.
3060 * @param $number Mixed: the string to be formatted, should be an integer
3061 * or a floating point number.
3062 * @param $nocommafy Bool: set to true for special numbers like dates
3063 * @return string
3065 public function formatNum( $number, $nocommafy = false ) {
3066 global $wgTranslateNumerals;
3067 if ( !$nocommafy ) {
3068 $number = $this->commafy( $number );
3069 $s = $this->separatorTransformTable();
3070 if ( $s ) {
3071 $number = strtr( $number, $s );
3075 if ( $wgTranslateNumerals ) {
3076 $s = $this->digitTransformTable();
3077 if ( $s ) {
3078 $number = strtr( $number, $s );
3082 return $number;
3086 * Front-end for non-commafied formatNum
3088 * @param mixed $number the string to be formatted, should be an integer
3089 * or a floating point number.
3090 * @since 1.21
3091 * @return string
3093 public function formatNumNoSeparators( $number ) {
3094 return $this->formatNum( $number, true );
3098 * @param $number string
3099 * @return string
3101 function parseFormattedNumber( $number ) {
3102 $s = $this->digitTransformTable();
3103 if ( $s ) {
3104 $number = strtr( $number, array_flip( $s ) );
3107 $s = $this->separatorTransformTable();
3108 if ( $s ) {
3109 $number = strtr( $number, array_flip( $s ) );
3112 $number = strtr( $number, array( ',' => '' ) );
3113 return $number;
3117 * Adds commas to a given number
3118 * @since 1.19
3119 * @param $number mixed
3120 * @return string
3122 function commafy( $number ) {
3123 $digitGroupingPattern = $this->digitGroupingPattern();
3124 if ( $number === null ) {
3125 return '';
3128 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3129 // default grouping is at thousands, use the same for ###,###,### pattern too.
3130 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3131 } else {
3132 // Ref: http://cldr.unicode.org/translation/number-patterns
3133 $sign = "";
3134 if ( intval( $number ) < 0 ) {
3135 // For negative numbers apply the algorithm like positive number and add sign.
3136 $sign = "-";
3137 $number = substr( $number, 1 );
3139 $integerPart = array();
3140 $decimalPart = array();
3141 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3142 preg_match( "/\d+/", $number, $integerPart );
3143 preg_match( "/\.\d*/", $number, $decimalPart );
3144 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3145 if ( $groupedNumber === $number ) {
3146 // the string does not have any number part. Eg: .12345
3147 return $sign . $groupedNumber;
3149 $start = $end = strlen( $integerPart[0] );
3150 while ( $start > 0 ) {
3151 $match = $matches[0][$numMatches - 1];
3152 $matchLen = strlen( $match );
3153 $start = $end - $matchLen;
3154 if ( $start < 0 ) {
3155 $start = 0;
3157 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3158 $end = $start;
3159 if ( $numMatches > 1 ) {
3160 // use the last pattern for the rest of the number
3161 $numMatches--;
3163 if ( $start > 0 ) {
3164 $groupedNumber = "," . $groupedNumber;
3167 return $sign . $groupedNumber;
3172 * @return String
3174 function digitGroupingPattern() {
3175 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3179 * @return array
3181 function digitTransformTable() {
3182 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3186 * @return array
3188 function separatorTransformTable() {
3189 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3193 * Take a list of strings and build a locale-friendly comma-separated
3194 * list, using the local comma-separator message.
3195 * The last two strings are chained with an "and".
3196 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3198 * @param $l Array
3199 * @return string
3201 function listToText( array $l ) {
3202 $m = count( $l ) - 1;
3203 if ( $m < 0 ) {
3204 return '';
3206 if ( $m > 0 ) {
3207 $and = $this->getMessageFromDB( 'and' );
3208 $space = $this->getMessageFromDB( 'word-separator' );
3209 if ( $m > 1 ) {
3210 $comma = $this->getMessageFromDB( 'comma-separator' );
3213 $s = $l[$m];
3214 for ( $i = $m - 1; $i >= 0; $i-- ) {
3215 if ( $i == $m - 1 ) {
3216 $s = $l[$i] . $and . $space . $s;
3217 } else {
3218 $s = $l[$i] . $comma . $s;
3221 return $s;
3225 * Take a list of strings and build a locale-friendly comma-separated
3226 * list, using the local comma-separator message.
3227 * @param $list array of strings to put in a comma list
3228 * @return string
3230 function commaList( array $list ) {
3231 return implode(
3232 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3233 $list
3238 * Take a list of strings and build a locale-friendly semicolon-separated
3239 * list, using the local semicolon-separator message.
3240 * @param $list array of strings to put in a semicolon list
3241 * @return string
3243 function semicolonList( array $list ) {
3244 return implode(
3245 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3246 $list
3251 * Same as commaList, but separate it with the pipe instead.
3252 * @param $list array of strings to put in a pipe list
3253 * @return string
3255 function pipeList( array $list ) {
3256 return implode(
3257 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3258 $list
3263 * Truncate a string to a specified length in bytes, appending an optional
3264 * string (e.g. for ellipses)
3266 * The database offers limited byte lengths for some columns in the database;
3267 * multi-byte character sets mean we need to ensure that only whole characters
3268 * are included, otherwise broken characters can be passed to the user
3270 * If $length is negative, the string will be truncated from the beginning
3272 * @param $string String to truncate
3273 * @param $length Int: maximum length (including ellipses)
3274 * @param $ellipsis String to append to the truncated text
3275 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3276 * $adjustLength was introduced in 1.18, before that behaved as if false.
3277 * @return string
3279 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3280 # Use the localized ellipsis character
3281 if ( $ellipsis == '...' ) {
3282 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3284 # Check if there is no need to truncate
3285 if ( $length == 0 ) {
3286 return $ellipsis; // convention
3287 } elseif ( strlen( $string ) <= abs( $length ) ) {
3288 return $string; // no need to truncate
3290 $stringOriginal = $string;
3291 # If ellipsis length is >= $length then we can't apply $adjustLength
3292 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3293 $string = $ellipsis; // this can be slightly unexpected
3294 # Otherwise, truncate and add ellipsis...
3295 } else {
3296 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3297 if ( $length > 0 ) {
3298 $length -= $eLength;
3299 $string = substr( $string, 0, $length ); // xyz...
3300 $string = $this->removeBadCharLast( $string );
3301 $string = $string . $ellipsis;
3302 } else {
3303 $length += $eLength;
3304 $string = substr( $string, $length ); // ...xyz
3305 $string = $this->removeBadCharFirst( $string );
3306 $string = $ellipsis . $string;
3309 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3310 # This check is *not* redundant if $adjustLength, due to the single case where
3311 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3312 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3313 return $string;
3314 } else {
3315 return $stringOriginal;
3320 * Remove bytes that represent an incomplete Unicode character
3321 * at the end of string (e.g. bytes of the char are missing)
3323 * @param $string String
3324 * @return string
3326 protected function removeBadCharLast( $string ) {
3327 if ( $string != '' ) {
3328 $char = ord( $string[strlen( $string ) - 1] );
3329 $m = array();
3330 if ( $char >= 0xc0 ) {
3331 # We got the first byte only of a multibyte char; remove it.
3332 $string = substr( $string, 0, -1 );
3333 } elseif ( $char >= 0x80 &&
3334 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3335 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3337 # We chopped in the middle of a character; remove it
3338 $string = $m[1];
3341 return $string;
3345 * Remove bytes that represent an incomplete Unicode character
3346 * at the start of string (e.g. bytes of the char are missing)
3348 * @param $string String
3349 * @return string
3351 protected function removeBadCharFirst( $string ) {
3352 if ( $string != '' ) {
3353 $char = ord( $string[0] );
3354 if ( $char >= 0x80 && $char < 0xc0 ) {
3355 # We chopped in the middle of a character; remove the whole thing
3356 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3359 return $string;
3363 * Truncate a string of valid HTML to a specified length in bytes,
3364 * appending an optional string (e.g. for ellipses), and return valid HTML
3366 * This is only intended for styled/linked text, such as HTML with
3367 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3368 * Also, this will not detect things like "display:none" CSS.
3370 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3372 * @param string $text HTML string to truncate
3373 * @param int $length (zero/positive) Maximum length (including ellipses)
3374 * @param string $ellipsis String to append to the truncated text
3375 * @return string
3377 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3378 # Use the localized ellipsis character
3379 if ( $ellipsis == '...' ) {
3380 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3382 # Check if there is clearly no need to truncate
3383 if ( $length <= 0 ) {
3384 return $ellipsis; // no text shown, nothing to format (convention)
3385 } elseif ( strlen( $text ) <= $length ) {
3386 return $text; // string short enough even *with* HTML (short-circuit)
3389 $dispLen = 0; // innerHTML legth so far
3390 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3391 $tagType = 0; // 0-open, 1-close
3392 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3393 $entityState = 0; // 0-not entity, 1-entity
3394 $tag = $ret = ''; // accumulated tag name, accumulated result string
3395 $openTags = array(); // open tag stack
3396 $maybeState = null; // possible truncation state
3398 $textLen = strlen( $text );
3399 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3400 for ( $pos = 0; true; ++$pos ) {
3401 # Consider truncation once the display length has reached the maximim.
3402 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3403 # Check that we're not in the middle of a bracket/entity...
3404 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3405 if ( !$testingEllipsis ) {
3406 $testingEllipsis = true;
3407 # Save where we are; we will truncate here unless there turn out to
3408 # be so few remaining characters that truncation is not necessary.
3409 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3410 $maybeState = array( $ret, $openTags ); // save state
3412 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3413 # String in fact does need truncation, the truncation point was OK.
3414 list( $ret, $openTags ) = $maybeState; // reload state
3415 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3416 $ret .= $ellipsis; // add ellipsis
3417 break;
3420 if ( $pos >= $textLen ) {
3421 break; // extra iteration just for above checks
3424 # Read the next char...
3425 $ch = $text[$pos];
3426 $lastCh = $pos ? $text[$pos - 1] : '';
3427 $ret .= $ch; // add to result string
3428 if ( $ch == '<' ) {
3429 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3430 $entityState = 0; // for bad HTML
3431 $bracketState = 1; // tag started (checking for backslash)
3432 } elseif ( $ch == '>' ) {
3433 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3434 $entityState = 0; // for bad HTML
3435 $bracketState = 0; // out of brackets
3436 } elseif ( $bracketState == 1 ) {
3437 if ( $ch == '/' ) {
3438 $tagType = 1; // close tag (e.g. "</span>")
3439 } else {
3440 $tagType = 0; // open tag (e.g. "<span>")
3441 $tag .= $ch;
3443 $bracketState = 2; // building tag name
3444 } elseif ( $bracketState == 2 ) {
3445 if ( $ch != ' ' ) {
3446 $tag .= $ch;
3447 } else {
3448 // Name found (e.g. "<a href=..."), add on tag attributes...
3449 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3451 } elseif ( $bracketState == 0 ) {
3452 if ( $entityState ) {
3453 if ( $ch == ';' ) {
3454 $entityState = 0;
3455 $dispLen++; // entity is one displayed char
3457 } else {
3458 if ( $neLength == 0 && !$maybeState ) {
3459 // Save state without $ch. We want to *hit* the first
3460 // display char (to get tags) but not *use* it if truncating.
3461 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3463 if ( $ch == '&' ) {
3464 $entityState = 1; // entity found, (e.g. "&#160;")
3465 } else {
3466 $dispLen++; // this char is displayed
3467 // Add the next $max display text chars after this in one swoop...
3468 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3469 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3470 $dispLen += $skipped;
3471 $pos += $skipped;
3476 // Close the last tag if left unclosed by bad HTML
3477 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3478 while ( count( $openTags ) > 0 ) {
3479 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3481 return $ret;
3485 * truncateHtml() helper function
3486 * like strcspn() but adds the skipped chars to $ret
3488 * @param $ret
3489 * @param $text
3490 * @param $search
3491 * @param $start
3492 * @param $len
3493 * @return int
3495 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3496 if ( $len === null ) {
3497 $len = -1; // -1 means "no limit" for strcspn
3498 } elseif ( $len < 0 ) {
3499 $len = 0; // sanity
3501 $skipCount = 0;
3502 if ( $start < strlen( $text ) ) {
3503 $skipCount = strcspn( $text, $search, $start, $len );
3504 $ret .= substr( $text, $start, $skipCount );
3506 return $skipCount;
3510 * truncateHtml() helper function
3511 * (a) push or pop $tag from $openTags as needed
3512 * (b) clear $tag value
3513 * @param &$tag string Current HTML tag name we are looking at
3514 * @param $tagType int (0-open tag, 1-close tag)
3515 * @param $lastCh string Character before the '>' that ended this tag
3516 * @param &$openTags array Open tag stack (not accounting for $tag)
3518 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3519 $tag = ltrim( $tag );
3520 if ( $tag != '' ) {
3521 if ( $tagType == 0 && $lastCh != '/' ) {
3522 $openTags[] = $tag; // tag opened (didn't close itself)
3523 } elseif ( $tagType == 1 ) {
3524 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3525 array_pop( $openTags ); // tag closed
3528 $tag = '';
3533 * Grammatical transformations, needed for inflected languages
3534 * Invoked by putting {{grammar:case|word}} in a message
3536 * @param $word string
3537 * @param $case string
3538 * @return string
3540 function convertGrammar( $word, $case ) {
3541 global $wgGrammarForms;
3542 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3543 return $wgGrammarForms[$this->getCode()][$case][$word];
3545 return $word;
3548 * Get the grammar forms for the content language
3549 * @return array of grammar forms
3550 * @since 1.20
3552 function getGrammarForms() {
3553 global $wgGrammarForms;
3554 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3555 return $wgGrammarForms[$this->getCode()];
3557 return array();
3560 * Provides an alternative text depending on specified gender.
3561 * Usage {{gender:username|masculine|feminine|neutral}}.
3562 * username is optional, in which case the gender of current user is used,
3563 * but only in (some) interface messages; otherwise default gender is used.
3565 * If no forms are given, an empty string is returned. If only one form is
3566 * given, it will be returned unconditionally. These details are implied by
3567 * the caller and cannot be overridden in subclasses.
3569 * If more than one form is given, the default is to use the neutral one
3570 * if it is specified, and to use the masculine one otherwise. These
3571 * details can be overridden in subclasses.
3573 * @param $gender string
3574 * @param $forms array
3576 * @return string
3578 function gender( $gender, $forms ) {
3579 if ( !count( $forms ) ) {
3580 return '';
3582 $forms = $this->preConvertPlural( $forms, 2 );
3583 if ( $gender === 'male' ) {
3584 return $forms[0];
3586 if ( $gender === 'female' ) {
3587 return $forms[1];
3589 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3593 * Plural form transformations, needed for some languages.
3594 * For example, there are 3 form of plural in Russian and Polish,
3595 * depending on "count mod 10". See [[w:Plural]]
3596 * For English it is pretty simple.
3598 * Invoked by putting {{plural:count|wordform1|wordform2}}
3599 * or {{plural:count|wordform1|wordform2|wordform3}}
3601 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3603 * @param $count Integer: non-localized number
3604 * @param $forms Array: different plural forms
3605 * @return string Correct form of plural for $count in this language
3607 function convertPlural( $count, $forms ) {
3608 // Handle explicit n=pluralform cases
3609 foreach ( $forms as $index => $form ) {
3610 if ( preg_match( '/\d+=/i', $form ) ) {
3611 $pos = strpos( $form, '=' );
3612 if ( substr( $form, 0, $pos ) === (string) $count ) {
3613 return substr( $form, $pos + 1 );
3615 unset( $forms[$index] );
3619 $forms = array_values( $forms );
3620 if ( !count( $forms ) ) {
3621 return '';
3624 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3625 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3626 return $forms[$pluralForm];
3630 * Checks that convertPlural was given an array and pads it to requested
3631 * amount of forms by copying the last one.
3633 * @param $count Integer: How many forms should there be at least
3634 * @param $forms Array of forms given to convertPlural
3635 * @return array Padded array of forms or an exception if not an array
3637 protected function preConvertPlural( /* Array */ $forms, $count ) {
3638 while ( count( $forms ) < $count ) {
3639 $forms[] = $forms[count( $forms ) - 1];
3641 return $forms;
3645 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3646 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3647 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3648 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3649 * match up with it.
3651 * @param $str String: the validated block duration in English
3652 * @return string Somehow translated block duration
3653 * @see LanguageFi.php for example implementation
3655 function translateBlockExpiry( $str ) {
3656 $duration = SpecialBlock::getSuggestedDurations( $this );
3657 foreach ( $duration as $show => $value ) {
3658 if ( strcmp( $str, $value ) == 0 ) {
3659 return htmlspecialchars( trim( $show ) );
3663 // Since usually only infinite or indefinite is only on list, so try
3664 // equivalents if still here.
3665 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3666 if ( in_array( $str, $indefs ) ) {
3667 foreach ( $indefs as $val ) {
3668 $show = array_search( $val, $duration, true );
3669 if ( $show !== false ) {
3670 return htmlspecialchars( trim( $show ) );
3675 // If all else fails, return a standard duration or timestamp description.
3676 $time = strtotime( $str, 0 );
3677 if ( $time === false ) { // Unknown format. Return it as-is in case.
3678 return $str;
3679 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3680 // $time is relative to 0 so it's a duration length.
3681 return $this->formatDuration( $time );
3682 } else { // It's an absolute timestamp.
3683 if ( $time === 0 ) {
3684 // wfTimestamp() handles 0 as current time instead of epoch.
3685 return $this->timeanddate( '19700101000000' );
3686 } else {
3687 return $this->timeanddate( $time );
3693 * languages like Chinese need to be segmented in order for the diff
3694 * to be of any use
3696 * @param $text String
3697 * @return String
3699 public function segmentForDiff( $text ) {
3700 return $text;
3704 * and unsegment to show the result
3706 * @param $text String
3707 * @return String
3709 public function unsegmentForDiff( $text ) {
3710 return $text;
3714 * Return the LanguageConverter used in the Language
3716 * @since 1.19
3717 * @return LanguageConverter
3719 public function getConverter() {
3720 return $this->mConverter;
3724 * convert text to all supported variants
3726 * @param $text string
3727 * @return array
3729 public function autoConvertToAllVariants( $text ) {
3730 return $this->mConverter->autoConvertToAllVariants( $text );
3734 * convert text to different variants of a language.
3736 * @param $text string
3737 * @return string
3739 public function convert( $text ) {
3740 return $this->mConverter->convert( $text );
3744 * Convert a Title object to a string in the preferred variant
3746 * @param $title Title
3747 * @return string
3749 public function convertTitle( $title ) {
3750 return $this->mConverter->convertTitle( $title );
3754 * Convert a namespace index to a string in the preferred variant
3756 * @param $ns int
3757 * @return string
3759 public function convertNamespace( $ns ) {
3760 return $this->mConverter->convertNamespace( $ns );
3764 * Check if this is a language with variants
3766 * @return bool
3768 public function hasVariants() {
3769 return count( $this->getVariants() ) > 1;
3773 * Check if the language has the specific variant
3775 * @since 1.19
3776 * @param $variant string
3777 * @return bool
3779 public function hasVariant( $variant ) {
3780 return (bool)$this->mConverter->validateVariant( $variant );
3784 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3786 * @param $text string
3787 * @return string
3789 public function armourMath( $text ) {
3790 return $this->mConverter->armourMath( $text );
3794 * Perform output conversion on a string, and encode for safe HTML output.
3795 * @param $text String text to be converted
3796 * @param $isTitle Bool whether this conversion is for the article title
3797 * @return string
3798 * @todo this should get integrated somewhere sane
3800 public function convertHtml( $text, $isTitle = false ) {
3801 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3805 * @param $key string
3806 * @return string
3808 public function convertCategoryKey( $key ) {
3809 return $this->mConverter->convertCategoryKey( $key );
3813 * Get the list of variants supported by this language
3814 * see sample implementation in LanguageZh.php
3816 * @return array an array of language codes
3818 public function getVariants() {
3819 return $this->mConverter->getVariants();
3823 * @return string
3825 public function getPreferredVariant() {
3826 return $this->mConverter->getPreferredVariant();
3830 * @return string
3832 public function getDefaultVariant() {
3833 return $this->mConverter->getDefaultVariant();
3837 * @return string
3839 public function getURLVariant() {
3840 return $this->mConverter->getURLVariant();
3844 * If a language supports multiple variants, it is
3845 * possible that non-existing link in one variant
3846 * actually exists in another variant. this function
3847 * tries to find it. See e.g. LanguageZh.php
3849 * @param $link String: the name of the link
3850 * @param $nt Mixed: the title object of the link
3851 * @param $ignoreOtherCond Boolean: to disable other conditions when
3852 * we need to transclude a template or update a category's link
3853 * @return null the input parameters may be modified upon return
3855 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3856 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3860 * If a language supports multiple variants, converts text
3861 * into an array of all possible variants of the text:
3862 * 'variant' => text in that variant
3864 * @deprecated since 1.17 Use autoConvertToAllVariants()
3866 * @param $text string
3868 * @return string
3870 public function convertLinkToAllVariants( $text ) {
3871 return $this->mConverter->convertLinkToAllVariants( $text );
3875 * returns language specific options used by User::getPageRenderHash()
3876 * for example, the preferred language variant
3878 * @return string
3880 function getExtraHashOptions() {
3881 return $this->mConverter->getExtraHashOptions();
3885 * For languages that support multiple variants, the title of an
3886 * article may be displayed differently in different variants. this
3887 * function returns the apporiate title defined in the body of the article.
3889 * @return string
3891 public function getParsedTitle() {
3892 return $this->mConverter->getParsedTitle();
3896 * Prepare external link text for conversion. When the text is
3897 * a URL, it shouldn't be converted, and it'll be wrapped in
3898 * the "raw" tag (-{R| }-) to prevent conversion.
3900 * This function is called "markNoConversion" for historical
3901 * reasons.
3903 * @param $text String: text to be used for external link
3904 * @param $noParse bool: wrap it without confirming it's a real URL first
3905 * @return string the tagged text
3907 public function markNoConversion( $text, $noParse = false ) {
3908 // Excluding protocal-relative URLs may avoid many false positives.
3909 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3910 return $this->mConverter->markNoConversion( $text );
3911 } else {
3912 return $text;
3917 * A regular expression to match legal word-trailing characters
3918 * which should be merged onto a link of the form [[foo]]bar.
3920 * @return string
3922 public function linkTrail() {
3923 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3927 * @return Language
3929 function getLangObj() {
3930 return $this;
3934 * Get the RFC 3066 code for this language object
3936 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3937 * htmlspecialchars() or similar
3939 * @return string
3941 public function getCode() {
3942 return $this->mCode;
3946 * Get the code in Bcp47 format which we can use
3947 * inside of html lang="" tags.
3949 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3950 * htmlspecialchars() or similar.
3952 * @since 1.19
3953 * @return string
3955 public function getHtmlCode() {
3956 if ( is_null( $this->mHtmlCode ) ) {
3957 $this->mHtmlCode = wfBCP47( $this->getCode() );
3959 return $this->mHtmlCode;
3963 * @param $code string
3965 public function setCode( $code ) {
3966 $this->mCode = $code;
3967 // Ensure we don't leave an incorrect html code lying around
3968 $this->mHtmlCode = null;
3972 * Get the name of a file for a certain language code
3973 * @param $prefix string Prepend this to the filename
3974 * @param $code string Language code
3975 * @param $suffix string Append this to the filename
3976 * @throws MWException
3977 * @return string $prefix . $mangledCode . $suffix
3979 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3980 // Protect against path traversal
3981 if ( !Language::isValidCode( $code )
3982 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3984 throw new MWException( "Invalid language code \"$code\"" );
3987 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3991 * Get the language code from a file name. Inverse of getFileName()
3992 * @param $filename string $prefix . $languageCode . $suffix
3993 * @param $prefix string Prefix before the language code
3994 * @param $suffix string Suffix after the language code
3995 * @return string Language code, or false if $prefix or $suffix isn't found
3997 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3998 $m = null;
3999 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4000 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4001 if ( !count( $m ) ) {
4002 return false;
4004 return str_replace( '_', '-', strtolower( $m[1] ) );
4008 * @param $code string
4009 * @return string
4011 public static function getMessagesFileName( $code ) {
4012 global $IP;
4013 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4014 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4015 return $file;
4019 * @param $code string
4020 * @return string
4022 public static function getClassFileName( $code ) {
4023 global $IP;
4024 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4028 * Get the first fallback for a given language.
4030 * @param $code string
4032 * @return bool|string
4034 public static function getFallbackFor( $code ) {
4035 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4036 return false;
4037 } else {
4038 $fallbacks = self::getFallbacksFor( $code );
4039 $first = array_shift( $fallbacks );
4040 return $first;
4045 * Get the ordered list of fallback languages.
4047 * @since 1.19
4048 * @param $code string Language code
4049 * @return array
4051 public static function getFallbacksFor( $code ) {
4052 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4053 return array();
4054 } else {
4055 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4056 $v = array_map( 'trim', explode( ',', $v ) );
4057 if ( $v[count( $v ) - 1] !== 'en' ) {
4058 $v[] = 'en';
4060 return $v;
4065 * Get the ordered list of fallback languages, ending with the fallback
4066 * language chain for the site language.
4068 * @since 1.22
4069 * @param string $code Language code
4070 * @return array array( fallbacks, site fallbacks )
4072 public static function getFallbacksIncludingSiteLanguage( $code ) {
4073 global $wgLanguageCode;
4075 // Usually, we will only store a tiny number of fallback chains, so we
4076 // keep them in static memory.
4077 $cacheKey = "{$code}-{$wgLanguageCode}";
4079 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4080 $fallbacks = self::getFallbacksFor( $code );
4082 // Append the site's fallback chain, including the site language itself
4083 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4084 array_unshift( $siteFallbacks, $wgLanguageCode );
4086 // Eliminate any languages already included in the chain
4087 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4089 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4091 return self::$fallbackLanguageCache[$cacheKey];
4095 * Get all messages for a given language
4096 * WARNING: this may take a long time. If you just need all message *keys*
4097 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4099 * @param $code string
4101 * @return array
4103 public static function getMessagesFor( $code ) {
4104 return self::getLocalisationCache()->getItem( $code, 'messages' );
4108 * Get a message for a given language
4110 * @param $key string
4111 * @param $code string
4113 * @return string
4115 public static function getMessageFor( $key, $code ) {
4116 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4120 * Get all message keys for a given language. This is a faster alternative to
4121 * array_keys( Language::getMessagesFor( $code ) )
4123 * @since 1.19
4124 * @param $code string Language code
4125 * @return array of message keys (strings)
4127 public static function getMessageKeysFor( $code ) {
4128 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4132 * @param $talk
4133 * @return mixed
4135 function fixVariableInNamespace( $talk ) {
4136 if ( strpos( $talk, '$1' ) === false ) {
4137 return $talk;
4140 global $wgMetaNamespace;
4141 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4143 # Allow grammar transformations
4144 # Allowing full message-style parsing would make simple requests
4145 # such as action=raw much more expensive than they need to be.
4146 # This will hopefully cover most cases.
4147 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4148 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4149 return str_replace( ' ', '_', $talk );
4153 * @param $m string
4154 * @return string
4156 function replaceGrammarInNamespace( $m ) {
4157 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4161 * @throws MWException
4162 * @return array
4164 static function getCaseMaps() {
4165 static $wikiUpperChars, $wikiLowerChars;
4166 if ( isset( $wikiUpperChars ) ) {
4167 return array( $wikiUpperChars, $wikiLowerChars );
4170 wfProfileIn( __METHOD__ );
4171 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4172 if ( $arr === false ) {
4173 throw new MWException(
4174 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4176 $wikiUpperChars = $arr['wikiUpperChars'];
4177 $wikiLowerChars = $arr['wikiLowerChars'];
4178 wfProfileOut( __METHOD__ );
4179 return array( $wikiUpperChars, $wikiLowerChars );
4183 * Decode an expiry (block, protection, etc) which has come from the DB
4185 * @todo FIXME: why are we returnings DBMS-dependent strings???
4187 * @param $expiry String: Database expiry String
4188 * @param $format Bool|Int true to process using language functions, or TS_ constant
4189 * to return the expiry in a given timestamp
4190 * @return String
4191 * @since 1.18
4193 public function formatExpiry( $expiry, $format = true ) {
4194 static $infinity;
4195 if ( $infinity === null ) {
4196 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4199 if ( $expiry == '' || $expiry == $infinity ) {
4200 return $format === true
4201 ? $this->getMessageFromDB( 'infiniteblock' )
4202 : $infinity;
4203 } else {
4204 return $format === true
4205 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4206 : wfTimestamp( $format, $expiry );
4211 * @todo Document
4212 * @param $seconds int|float
4213 * @param $format Array Optional
4214 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4215 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4216 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4217 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4218 * @return string
4220 function formatTimePeriod( $seconds, $format = array() ) {
4221 if ( !is_array( $format ) ) {
4222 $format = array( 'avoid' => $format ); // For backwards compatibility
4224 if ( !isset( $format['avoid'] ) ) {
4225 $format['avoid'] = false;
4227 if ( !isset( $format['noabbrevs' ] ) ) {
4228 $format['noabbrevs'] = false;
4230 $secondsMsg = wfMessage(
4231 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4232 $minutesMsg = wfMessage(
4233 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4234 $hoursMsg = wfMessage(
4235 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4236 $daysMsg = wfMessage(
4237 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4239 if ( round( $seconds * 10 ) < 100 ) {
4240 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4241 $s = $secondsMsg->params( $s )->text();
4242 } elseif ( round( $seconds ) < 60 ) {
4243 $s = $this->formatNum( round( $seconds ) );
4244 $s = $secondsMsg->params( $s )->text();
4245 } elseif ( round( $seconds ) < 3600 ) {
4246 $minutes = floor( $seconds / 60 );
4247 $secondsPart = round( fmod( $seconds, 60 ) );
4248 if ( $secondsPart == 60 ) {
4249 $secondsPart = 0;
4250 $minutes++;
4252 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4253 $s .= ' ';
4254 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4255 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4256 $hours = floor( $seconds / 3600 );
4257 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4258 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4259 if ( $secondsPart == 60 ) {
4260 $secondsPart = 0;
4261 $minutes++;
4263 if ( $minutes == 60 ) {
4264 $minutes = 0;
4265 $hours++;
4267 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4268 $s .= ' ';
4269 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4270 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4271 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4273 } else {
4274 $days = floor( $seconds / 86400 );
4275 if ( $format['avoid'] === 'avoidminutes' ) {
4276 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4277 if ( $hours == 24 ) {
4278 $hours = 0;
4279 $days++;
4281 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4282 $s .= ' ';
4283 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4284 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4285 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4286 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4287 if ( $minutes == 60 ) {
4288 $minutes = 0;
4289 $hours++;
4291 if ( $hours == 24 ) {
4292 $hours = 0;
4293 $days++;
4295 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4296 $s .= ' ';
4297 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4298 $s .= ' ';
4299 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4300 } else {
4301 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4302 $s .= ' ';
4303 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4306 return $s;
4310 * Format a bitrate for output, using an appropriate
4311 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4313 * This use base 1000. For base 1024 use formatSize(), for another base
4314 * see formatComputingNumbers()
4316 * @param $bps int
4317 * @return string
4319 function formatBitrate( $bps ) {
4320 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4324 * @param $size int Size of the unit
4325 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4326 * @param $messageKey string Message key to be uesd
4327 * @return string
4329 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4330 if ( $size <= 0 ) {
4331 return str_replace( '$1', $this->formatNum( $size ),
4332 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4335 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4336 $index = 0;
4338 $maxIndex = count( $sizes ) - 1;
4339 while ( $size >= $boundary && $index < $maxIndex ) {
4340 $index++;
4341 $size /= $boundary;
4344 // For small sizes no decimal places necessary
4345 $round = 0;
4346 if ( $index > 1 ) {
4347 // For MB and bigger two decimal places are smarter
4348 $round = 2;
4350 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4352 $size = round( $size, $round );
4353 $text = $this->getMessageFromDB( $msg );
4354 return str_replace( '$1', $this->formatNum( $size ), $text );
4358 * Format a size in bytes for output, using an appropriate
4359 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4361 * This method use base 1024. For base 1000 use formatBitrate(), for
4362 * another base see formatComputingNumbers()
4364 * @param $size int Size to format
4365 * @return string Plain text (not HTML)
4367 function formatSize( $size ) {
4368 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4372 * Make a list item, used by various special pages
4374 * @param $page String Page link
4375 * @param $details String Text between brackets
4376 * @param $oppositedm Boolean Add the direction mark opposite to your
4377 * language, to display text properly
4378 * @return String
4380 function specialList( $page, $details, $oppositedm = true ) {
4381 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4382 $this->getDirMark();
4383 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4384 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4385 return $page . $details;
4389 * Generate (prev x| next x) (20|50|100...) type links for paging
4391 * @param $title Title object to link
4392 * @param $offset Integer offset parameter
4393 * @param $limit Integer limit parameter
4394 * @param $query array|String optional URL query parameter string
4395 * @param $atend Bool optional param for specified if this is the last page
4396 * @return String
4398 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4399 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4401 # Make 'previous' link
4402 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4403 if ( $offset > 0 ) {
4404 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4405 $query, $prev, 'prevn-title', 'mw-prevlink' );
4406 } else {
4407 $plink = htmlspecialchars( $prev );
4410 # Make 'next' link
4411 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4412 if ( $atend ) {
4413 $nlink = htmlspecialchars( $next );
4414 } else {
4415 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4416 $query, $next, 'prevn-title', 'mw-nextlink' );
4419 # Make links to set number of items per page
4420 $numLinks = array();
4421 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4422 $numLinks[] = $this->numLink( $title, $offset, $num,
4423 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4426 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4427 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4431 * Helper function for viewPrevNext() that generates links
4433 * @param $title Title object to link
4434 * @param $offset Integer offset parameter
4435 * @param $limit Integer limit parameter
4436 * @param $query Array extra query parameters
4437 * @param $link String text to use for the link; will be escaped
4438 * @param $tooltipMsg String name of the message to use as tooltip
4439 * @param $class String value of the "class" attribute of the link
4440 * @return String HTML fragment
4442 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4443 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4444 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4445 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4446 'title' => $tooltip, 'class' => $class ), $link );
4450 * Get the conversion rule title, if any.
4452 * @return string
4454 public function getConvRuleTitle() {
4455 return $this->mConverter->getConvRuleTitle();
4459 * Get the compiled plural rules for the language
4460 * @since 1.20
4461 * @return array Associative array with plural form, and plural rule as key-value pairs
4463 public function getCompiledPluralRules() {
4464 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4465 $fallbacks = Language::getFallbacksFor( $this->mCode );
4466 if ( !$pluralRules ) {
4467 foreach ( $fallbacks as $fallbackCode ) {
4468 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4469 if ( $pluralRules ) {
4470 break;
4474 return $pluralRules;
4478 * Get the plural rules for the language
4479 * @since 1.20
4480 * @return array Associative array with plural form number and plural rule as key-value pairs
4482 public function getPluralRules() {
4483 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4484 $fallbacks = Language::getFallbacksFor( $this->mCode );
4485 if ( !$pluralRules ) {
4486 foreach ( $fallbacks as $fallbackCode ) {
4487 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4488 if ( $pluralRules ) {
4489 break;
4493 return $pluralRules;
4497 * Get the plural rule types for the language
4498 * @since 1.21
4499 * @return array Associative array with plural form number and plural rule type as key-value pairs
4501 public function getPluralRuleTypes() {
4502 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4503 $fallbacks = Language::getFallbacksFor( $this->mCode );
4504 if ( !$pluralRuleTypes ) {
4505 foreach ( $fallbacks as $fallbackCode ) {
4506 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4507 if ( $pluralRuleTypes ) {
4508 break;
4512 return $pluralRuleTypes;
4516 * Find the index number of the plural rule appropriate for the given number
4517 * @return int The index number of the plural rule
4519 public function getPluralRuleIndexNumber( $number ) {
4520 $pluralRules = $this->getCompiledPluralRules();
4521 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4522 return $form;
4526 * Find the plural rule type appropriate for the given number
4527 * For example, if the language is set to Arabic, getPluralType(5) should
4528 * return 'few'.
4529 * @since 1.21
4530 * @return string The name of the plural rule type, e.g. one, two, few, many
4532 public function getPluralRuleType( $number ) {
4533 $index = $this->getPluralRuleIndexNumber( $number );
4534 $pluralRuleTypes = $this->getPluralRuleTypes();
4535 if ( isset( $pluralRuleTypes[$index] ) ) {
4536 return $pluralRuleTypes[$index];
4537 } else {
4538 return 'other';