3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once( __DIR__
. '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
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; }
72 * Internationalisation code
78 * @var LanguageConverter
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;
92 * ReplacementArray object caches
94 public $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
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',
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',
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'
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
174 * Get a cached or new language object for a given language code
175 * @param $code String
178 static function factory( $code ) {
179 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
181 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
182 $code = $wgDummyLanguageCodes[$code];
185 // get the language object to process
186 $langObj = isset( self
::$mLangObjCache[$code] )
187 ? self
::$mLangObjCache[$code]
188 : self
::newFromCode( $code );
190 // merge the language object in to get it up front in the cache
191 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
192 // get rid of the oldest ones in case we have an overflow
193 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
199 * Create a language object for a given language code
200 * @param $code String
201 * @throws MWException
204 protected static function newFromCode( $code ) {
205 // Protect against path traversal below
206 if ( !Language
::isValidCode( $code )
207 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
209 throw new MWException( "Invalid language code \"$code\"" );
212 if ( !Language
::isValidBuiltInCode( $code ) ) {
213 // It's not possible to customise this code with class files, so
214 // just return a Language object. This is to support uselang= hacks.
215 $lang = new Language
;
216 $lang->setCode( $code );
220 // Check if there is a language class for the code
221 $class = self
::classFromCode( $code );
222 self
::preloadLanguageClass( $class );
223 if ( MWInit
::classExists( $class ) ) {
228 // Keep trying the fallback list until we find an existing class
229 $fallbacks = Language
::getFallbacksFor( $code );
230 foreach ( $fallbacks as $fallbackCode ) {
231 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
232 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
235 $class = self
::classFromCode( $fallbackCode );
236 self
::preloadLanguageClass( $class );
237 if ( MWInit
::classExists( $class ) ) {
238 $lang = Language
::newFromCode( $fallbackCode );
239 $lang->setCode( $code );
244 throw new MWException( "Invalid fallback sequence for language '$code'" );
248 * Checks whether any localisation is available for that language tag
249 * in MediaWiki (MessagesXx.php exists).
251 * @param string $code Language tag (in lower case)
252 * @return bool Whether language is supported
255 public static function isSupportedLanguage( $code ) {
256 return $code === strtolower( $code ) && is_readable( self
::getMessagesFileName( $code ) );
260 * Returns true if a language code string is a well-formed language tag
261 * according to RFC 5646.
262 * This function only checks well-formedness; it doesn't check that
263 * language, script or variant codes actually exist in the repositories.
265 * Based on regexes by Mark Davis of the Unicode Consortium:
266 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
268 * @param $code string
269 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
274 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
277 $alphanum = '[a-z0-9]';
278 $x = 'x' ; # private use singleton
279 $singleton = '[a-wy-z]'; # other singleton
280 $s = $lenient ?
'[-_]' : '-';
282 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
283 $script = "$alpha{4}"; # ISO 15924
284 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
285 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
286 $extension = "$singleton(?:$s$alphanum{2,8})+";
287 $privateUse = "$x(?:$s$alphanum{1,8})+";
289 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
290 # Since these are limited, this is safe even later changes to the registry --
291 # the only oddity is that it might change the type of the tag, and thus
292 # the results from the capturing groups.
293 # http://www.iana.org/assignments/language-subtag-registry
295 $grandfathered = "en{$s}GB{$s}oed"
296 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
297 . "|no{$s}(?:bok|nyn)"
298 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
299 . "|zh{$s}min{$s}nan";
301 $variantList = "$variant(?:$s$variant)*";
302 $extensionList = "$extension(?:$s$extension)*";
304 $langtag = "(?:($language)"
307 . "(?:$s$variantList)?"
308 . "(?:$s$extensionList)?"
309 . "(?:$s$privateUse)?)";
311 # The final breakdown, with capturing groups for each of these components
312 # The variants, extensions, grandfathered, and private-use may have interior '-'
314 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
316 return (bool)preg_match( "/$root/", strtolower( $code ) );
320 * Returns true if a language code string is of a valid form, whether or
321 * not it exists. This includes codes which are used solely for
322 * customisation via the MediaWiki namespace.
324 * @param $code string
328 public static function isValidCode( $code ) {
330 // People think language codes are html safe, so enforce it.
331 // Ideally we should only allow a-zA-Z0-9-
332 // but, .+ and other chars are often used for {{int:}} hacks
333 // see bugs 37564, 37587, 36938
334 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
335 && !preg_match( Title
::getTitleInvalidRegex(), $code );
339 * Returns true if a language code is of a valid form for the purposes of
340 * internal customisation of MediaWiki, via Messages*.php.
342 * @param $code string
344 * @throws MWException
348 public static function isValidBuiltInCode( $code ) {
350 if ( !is_string( $code ) ) {
351 if ( is_object( $code ) ) {
352 $addmsg = " of class " . get_class( $code );
356 $type = gettype( $code );
357 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
360 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
364 * Returns true if a language code is an IETF tag known to MediaWiki.
366 * @param $code string
371 public static function isKnownLanguageTag( $tag ) {
372 static $coreLanguageNames;
374 if ( $coreLanguageNames === null ) {
375 include( MWInit
::compiledPath( 'languages/Names.php' ) );
378 if ( isset( $coreLanguageNames[$tag] )
379 || self
::fetchLanguageName( $tag, $tag ) !== ''
389 * @return String Name of the language class
391 public static function classFromCode( $code ) {
392 if ( $code == 'en' ) {
395 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
400 * Includes language class files
402 * @param $class string Name of the language class
404 public static function preloadLanguageClass( $class ) {
407 if ( $class === 'Language' ) {
411 if ( !defined( 'MW_COMPILED' ) ) {
412 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
413 include_once( "$IP/languages/classes/$class.php" );
419 * Get the LocalisationCache instance
421 * @return LocalisationCache
423 public static function getLocalisationCache() {
424 if ( is_null( self
::$dataCache ) ) {
425 global $wgLocalisationCacheConf;
426 $class = $wgLocalisationCacheConf['class'];
427 self
::$dataCache = new $class( $wgLocalisationCacheConf );
429 return self
::$dataCache;
432 function __construct() {
433 $this->mConverter
= new FakeConverter( $this );
434 // Set the code to the name of the descendant
435 if ( get_class( $this ) == 'Language' ) {
438 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
440 self
::getLocalisationCache();
444 * Reduce memory usage
446 function __destruct() {
447 foreach ( $this as $name => $value ) {
448 unset( $this->$name );
453 * Hook which will be called if this is the content language.
454 * Descendants can use this to register hook functions or modify globals
456 function initContLang() { }
459 * Same as getFallbacksFor for current language.
461 * @deprecated in 1.19
463 function getFallbackLanguageCode() {
464 wfDeprecated( __METHOD__
, '1.19' );
465 return self
::getFallbackFor( $this->mCode
);
472 function getFallbackLanguages() {
473 return self
::getFallbacksFor( $this->mCode
);
477 * Exports $wgBookstoreListEn
480 function getBookstoreList() {
481 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
487 public function getNamespaces() {
488 if ( is_null( $this->namespaceNames
) ) {
489 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
491 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
492 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
494 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
496 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
497 if ( $wgMetaNamespaceTalk ) {
498 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
500 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
501 $this->namespaceNames
[NS_PROJECT_TALK
] =
502 $this->fixVariableInNamespace( $talk );
505 # Sometimes a language will be localised but not actually exist on this wiki.
506 foreach ( $this->namespaceNames
as $key => $text ) {
507 if ( !isset( $validNamespaces[$key] ) ) {
508 unset( $this->namespaceNames
[$key] );
512 # The above mixing may leave namespaces out of canonical order.
513 # Re-order by namespace ID number...
514 ksort( $this->namespaceNames
);
516 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
518 return $this->namespaceNames
;
522 * Arbitrarily set all of the namespace names at once. Mainly used for testing
523 * @param $namespaces Array of namespaces (id => name)
525 public function setNamespaces( array $namespaces ) {
526 $this->namespaceNames
= $namespaces;
527 $this->mNamespaceIds
= null;
531 * Resets all of the namespace caches. Mainly used for testing
533 public function resetNamespaces() {
534 $this->namespaceNames
= null;
535 $this->mNamespaceIds
= null;
536 $this->namespaceAliases
= null;
540 * A convenience function that returns the same thing as
541 * getNamespaces() except with the array values changed to ' '
542 * where it found '_', useful for producing output to be displayed
543 * e.g. in <select> forms.
547 function getFormattedNamespaces() {
548 $ns = $this->getNamespaces();
549 foreach ( $ns as $k => $v ) {
550 $ns[$k] = strtr( $v, '_', ' ' );
556 * Get a namespace value by key
558 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
559 * echo $mw_ns; // prints 'MediaWiki'
562 * @param $index Int: the array key of the namespace to return
563 * @return mixed, string if the namespace value exists, otherwise false
565 function getNsText( $index ) {
566 $ns = $this->getNamespaces();
567 return isset( $ns[$index] ) ?
$ns[$index] : false;
571 * A convenience function that returns the same thing as
572 * getNsText() except with '_' changed to ' ', useful for
576 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
577 * echo $mw_ns; // prints 'MediaWiki talk'
580 * @param int $index The array key of the namespace to return
581 * @return string Namespace name without underscores (empty string if namespace does not exist)
583 function getFormattedNsText( $index ) {
584 $ns = $this->getNsText( $index );
585 return strtr( $ns, '_', ' ' );
589 * Returns gender-dependent namespace alias if available.
590 * @param $index Int: namespace index
591 * @param $gender String: gender key (male, female... )
595 function getGenderNsText( $index, $gender ) {
596 global $wgExtraGenderNamespaces;
598 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
599 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
603 * Whether this language makes distinguishes genders for example in
608 function needsGenderDistinction() {
609 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
610 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
611 // $wgExtraGenderNamespaces overrides everything
613 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
614 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
615 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
618 // Check what is in i18n files
619 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
620 return count( $aliases ) > 0;
625 * Get a namespace key by value, case insensitive.
626 * Only matches namespace names for the current language, not the
627 * canonical ones defined in Namespace.php.
629 * @param $text String
630 * @return mixed An integer if $text is a valid value otherwise false
632 function getLocalNsIndex( $text ) {
633 $lctext = $this->lc( $text );
634 $ids = $this->getNamespaceIds();
635 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
641 function getNamespaceAliases() {
642 if ( is_null( $this->namespaceAliases
) ) {
643 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
647 foreach ( $aliases as $name => $index ) {
648 if ( $index === NS_PROJECT_TALK
) {
649 unset( $aliases[$name] );
650 $name = $this->fixVariableInNamespace( $name );
651 $aliases[$name] = $index;
656 global $wgExtraGenderNamespaces;
657 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
658 foreach ( $genders as $index => $forms ) {
659 foreach ( $forms as $alias ) {
660 $aliases[$alias] = $index;
664 $this->namespaceAliases
= $aliases;
666 return $this->namespaceAliases
;
672 function getNamespaceIds() {
673 if ( is_null( $this->mNamespaceIds
) ) {
674 global $wgNamespaceAliases;
675 # Put namespace names and aliases into a hashtable.
676 # If this is too slow, then we should arrange it so that it is done
677 # before caching. The catch is that at pre-cache time, the above
678 # class-specific fixup hasn't been done.
679 $this->mNamespaceIds
= array();
680 foreach ( $this->getNamespaces() as $index => $name ) {
681 $this->mNamespaceIds
[$this->lc( $name )] = $index;
683 foreach ( $this->getNamespaceAliases() as $name => $index ) {
684 $this->mNamespaceIds
[$this->lc( $name )] = $index;
686 if ( $wgNamespaceAliases ) {
687 foreach ( $wgNamespaceAliases as $name => $index ) {
688 $this->mNamespaceIds
[$this->lc( $name )] = $index;
692 return $this->mNamespaceIds
;
696 * Get a namespace key by value, case insensitive. Canonical namespace
697 * names override custom ones defined for the current language.
699 * @param $text String
700 * @return mixed An integer if $text is a valid value otherwise false
702 function getNsIndex( $text ) {
703 $lctext = $this->lc( $text );
704 $ns = MWNamespace
::getCanonicalIndex( $lctext );
705 if ( $ns !== null ) {
708 $ids = $this->getNamespaceIds();
709 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
713 * short names for language variants used for language conversion links.
715 * @param $code String
716 * @param $usemsg bool Use the "variantname-xyz" message if it exists
719 function getVariantname( $code, $usemsg = true ) {
720 $msg = "variantname-$code";
721 if ( $usemsg && wfMessage( $msg )->exists() ) {
722 return $this->getMessageFromDB( $msg );
724 $name = self
::fetchLanguageName( $code );
726 return $name; # if it's defined as a language name, show that
728 # otherwise, output the language code
734 * @param $name string
737 function specialPage( $name ) {
738 $aliases = $this->getSpecialPageAliases();
739 if ( isset( $aliases[$name][0] ) ) {
740 $name = $aliases[$name][0];
742 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
748 function getDatePreferences() {
749 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
755 function getDateFormats() {
756 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
760 * @return array|string
762 function getDefaultDateFormat() {
763 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
764 if ( $df === 'dmy or mdy' ) {
765 global $wgAmericanDates;
766 return $wgAmericanDates ?
'mdy' : 'dmy';
775 function getDatePreferenceMigrationMap() {
776 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
783 function getImageFile( $image ) {
784 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
790 function getExtraUserToggles() {
791 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
798 function getUserToggle( $tog ) {
799 return $this->getMessageFromDB( "tog-$tog" );
803 * Get native language names, indexed by code.
804 * Only those defined in MediaWiki, no other data like CLDR.
805 * If $customisedOnly is true, only returns codes with a messages file
807 * @param $customisedOnly bool
810 * @deprecated in 1.20, use fetchLanguageNames()
812 public static function getLanguageNames( $customisedOnly = false ) {
813 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
817 * Get translated language names. This is done on best effort and
818 * by default this is exactly the same as Language::getLanguageNames.
819 * The CLDR extension provides translated names.
820 * @param $code String Language code.
821 * @return Array language code => language name
823 * @deprecated in 1.20, use fetchLanguageNames()
825 public static function getTranslatedLanguageNames( $code ) {
826 return self
::fetchLanguageNames( $code, 'all' );
830 * Get an array of language names, indexed by code.
831 * @param $inLanguage null|string: Code of language in which to return the names
832 * Use null for autonyms (native names)
833 * @param $include string:
834 * 'all' all available languages
835 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
836 * 'mwfile' only if the language is in 'mw' *and* has a message file
837 * @return array: language code => language name
840 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
841 global $wgExtraLanguageNames;
842 static $coreLanguageNames;
844 if ( $coreLanguageNames === null ) {
845 include( MWInit
::compiledPath( 'languages/Names.php' ) );
851 # TODO: also include when $inLanguage is null, when this code is more efficient
852 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
855 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
856 foreach ( $mwNames as $mwCode => $mwName ) {
857 # - Prefer own MediaWiki native name when not using the hook
858 # - For other names just add if not added through the hook
859 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
860 $names[$mwCode] = $mwName;
864 if ( $include === 'all' ) {
869 $coreCodes = array_keys( $mwNames );
870 foreach ( $coreCodes as $coreCode ) {
871 $returnMw[$coreCode] = $names[$coreCode];
874 if ( $include === 'mwfile' ) {
875 $namesMwFile = array();
876 # We do this using a foreach over the codes instead of a directory
877 # loop so that messages files in extensions will work correctly.
878 foreach ( $returnMw as $code => $value ) {
879 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
880 $namesMwFile[$code] = $names[$code];
885 # 'mw' option; default if it's not one of the other two options (all/mwfile)
890 * @param $code string: The code of the language for which to get the name
891 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
892 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
893 * @return string: Language name or empty
896 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
897 $array = self
::fetchLanguageNames( $inLanguage, $include );
898 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
902 * Get a message from the MediaWiki namespace.
904 * @param $msg String: message name
907 function getMessageFromDB( $msg ) {
908 return wfMessage( $msg )->inLanguage( $this )->text();
912 * Get the native language name of $code.
913 * Only if defined in MediaWiki, no other data like CLDR.
914 * @param $code string
916 * @deprecated in 1.20, use fetchLanguageName()
918 function getLanguageName( $code ) {
919 return self
::fetchLanguageName( $code );
926 function getMonthName( $key ) {
927 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
933 function getMonthNamesArray() {
934 $monthNames = array( '' );
935 for ( $i = 1; $i < 13; $i++
) {
936 $monthNames[] = $this->getMonthName( $i );
945 function getMonthNameGen( $key ) {
946 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
953 function getMonthAbbreviation( $key ) {
954 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
960 function getMonthAbbreviationsArray() {
961 $monthNames = array( '' );
962 for ( $i = 1; $i < 13; $i++
) {
963 $monthNames[] = $this->getMonthAbbreviation( $i );
972 function getWeekdayName( $key ) {
973 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
980 function getWeekdayAbbreviation( $key ) {
981 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
988 function getIranianCalendarMonthName( $key ) {
989 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
996 function getHebrewCalendarMonthName( $key ) {
997 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1001 * @param $key string
1004 function getHebrewCalendarMonthNameGen( $key ) {
1005 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1009 * @param $key string
1012 function getHijriCalendarMonthName( $key ) {
1013 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1017 * This is a workalike of PHP's date() function, but with better
1018 * internationalisation, a reduced set of format characters, and a better
1021 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
1022 * PHP manual for definitions. There are a number of extensions, which
1025 * xn Do not translate digits of the next numeric format character
1026 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1027 * xr Use roman numerals for the next numeric format character
1028 * xh Use hebrew numerals for the next numeric format character
1030 * xg Genitive month name
1032 * xij j (day number) in Iranian calendar
1033 * xiF F (month name) in Iranian calendar
1034 * xin n (month number) in Iranian calendar
1035 * xiy y (two digit year) in Iranian calendar
1036 * xiY Y (full year) in Iranian calendar
1038 * xjj j (day number) in Hebrew calendar
1039 * xjF F (month name) in Hebrew calendar
1040 * xjt t (days in month) in Hebrew calendar
1041 * xjx xg (genitive month name) in Hebrew calendar
1042 * xjn n (month number) in Hebrew calendar
1043 * xjY Y (full year) in Hebrew calendar
1045 * xmj j (day number) in Hijri calendar
1046 * xmF F (month name) in Hijri calendar
1047 * xmn n (month number) in Hijri calendar
1048 * xmY Y (full year) in Hijri calendar
1050 * xkY Y (full year) in Thai solar calendar. Months and days are
1051 * identical to the Gregorian calendar
1052 * xoY Y (full year) in Minguo calendar or Juche year.
1053 * Months and days are identical to the
1054 * Gregorian calendar
1055 * xtY Y (full year) in Japanese nengo. Months and days are
1056 * identical to the Gregorian calendar
1058 * Characters enclosed in double quotes will be considered literal (with
1059 * the quotes themselves removed). Unmatched quotes will be considered
1060 * literal quotes. Example:
1062 * "The month is" F => The month is January
1065 * Backslash escaping is also supported.
1067 * Input timestamp is assumed to be pre-normalized to the desired local
1068 * time zone, if any.
1070 * @param $format String
1071 * @param $ts String: 14-character timestamp
1074 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1078 function sprintfDate( $format, $ts ) {
1091 for ( $p = 0; $p < strlen( $format ); $p++
) {
1093 $code = $format[$p];
1094 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1095 $code .= $format[++
$p];
1098 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1099 $code .= $format[++
$p];
1110 $rawToggle = !$rawToggle;
1119 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1122 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1123 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1126 $num = substr( $ts, 6, 2 );
1129 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1130 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1133 $num = intval( substr( $ts, 6, 2 ) );
1137 $iranian = self
::tsToIranian( $ts );
1143 $hijri = self
::tsToHijri( $ts );
1149 $hebrew = self
::tsToHebrew( $ts );
1155 $unix = wfTimestamp( TS_UNIX
, $ts );
1157 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1161 $unix = wfTimestamp( TS_UNIX
, $ts );
1163 $w = gmdate( 'w', $unix );
1168 $unix = wfTimestamp( TS_UNIX
, $ts );
1170 $num = gmdate( 'w', $unix );
1174 $unix = wfTimestamp( TS_UNIX
, $ts );
1176 $num = gmdate( 'z', $unix );
1180 $unix = wfTimestamp( TS_UNIX
, $ts );
1182 $num = gmdate( 'W', $unix );
1185 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1189 $iranian = self
::tsToIranian( $ts );
1191 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1195 $hijri = self
::tsToHijri( $ts );
1197 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1201 $hebrew = self
::tsToHebrew( $ts );
1203 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1206 $num = substr( $ts, 4, 2 );
1209 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1212 $num = intval( substr( $ts, 4, 2 ) );
1216 $iranian = self
::tsToIranian( $ts );
1222 $hijri = self
::tsToHijri ( $ts );
1228 $hebrew = self
::tsToHebrew( $ts );
1234 $unix = wfTimestamp( TS_UNIX
, $ts );
1236 $num = gmdate( 't', $unix );
1240 $hebrew = self
::tsToHebrew( $ts );
1246 $unix = wfTimestamp( TS_UNIX
, $ts );
1248 $num = gmdate( 'L', $unix );
1252 $unix = wfTimestamp( TS_UNIX
, $ts );
1254 $num = gmdate( 'o', $unix );
1257 $num = substr( $ts, 0, 4 );
1261 $iranian = self
::tsToIranian( $ts );
1267 $hijri = self
::tsToHijri( $ts );
1273 $hebrew = self
::tsToHebrew( $ts );
1279 $thai = self
::tsToYear( $ts, 'thai' );
1285 $minguo = self
::tsToYear( $ts, 'minguo' );
1291 $tenno = self
::tsToYear( $ts, 'tenno' );
1296 $num = substr( $ts, 2, 2 );
1300 $iranian = self
::tsToIranian( $ts );
1302 $num = substr( $iranian[0], -2 );
1305 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1308 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1311 $h = substr( $ts, 8, 2 );
1312 $num = $h %
12 ?
$h %
12 : 12;
1315 $num = intval( substr( $ts, 8, 2 ) );
1318 $h = substr( $ts, 8, 2 );
1319 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1322 $num = substr( $ts, 8, 2 );
1325 $num = substr( $ts, 10, 2 );
1328 $num = substr( $ts, 12, 2 );
1332 $unix = wfTimestamp( TS_UNIX
, $ts );
1334 $s .= gmdate( 'c', $unix );
1338 $unix = wfTimestamp( TS_UNIX
, $ts );
1340 $s .= gmdate( 'r', $unix );
1344 $unix = wfTimestamp( TS_UNIX
, $ts );
1349 # Backslash escaping
1350 if ( $p < strlen( $format ) - 1 ) {
1351 $s .= $format[++
$p];
1358 if ( $p < strlen( $format ) - 1 ) {
1359 $endQuote = strpos( $format, '"', $p +
1 );
1360 if ( $endQuote === false ) {
1361 # No terminating quote, assume literal "
1364 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1368 # Quote at end of string, assume literal "
1375 if ( $num !== false ) {
1376 if ( $rawToggle ||
$raw ) {
1379 } elseif ( $roman ) {
1380 $s .= Language
::romanNumeral( $num );
1382 } elseif ( $hebrewNum ) {
1383 $s .= self
::hebrewNumeral( $num );
1386 $s .= $this->formatNum( $num, true );
1393 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1394 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1397 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1398 * Gregorian dates to Iranian dates. Originally written in C, it
1399 * is released under the terms of GNU Lesser General Public
1400 * License. Conversion to PHP was performed by Niklas Laxström.
1402 * Link: http://www.farsiweb.info/jalali/jalali.c
1408 private static function tsToIranian( $ts ) {
1409 $gy = substr( $ts, 0, 4 ) -1600;
1410 $gm = substr( $ts, 4, 2 ) -1;
1411 $gd = substr( $ts, 6, 2 ) -1;
1413 # Days passed from the beginning (including leap years)
1415 +
floor( ( $gy +
3 ) / 4 )
1416 - floor( ( $gy +
99 ) / 100 )
1417 +
floor( ( $gy +
399 ) / 400 );
1419 // Add days of the past months of this year
1420 for ( $i = 0; $i < $gm; $i++
) {
1421 $gDayNo +
= self
::$GREG_DAYS[$i];
1425 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1429 // Days passed in current month
1430 $gDayNo +
= (int)$gd;
1432 $jDayNo = $gDayNo - 79;
1434 $jNp = floor( $jDayNo / 12053 );
1437 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1440 if ( $jDayNo >= 366 ) {
1441 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1442 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1445 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1446 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1452 return array( $jy, $jm, $jd );
1456 * Converting Gregorian dates to Hijri dates.
1458 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1460 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1466 private static function tsToHijri( $ts ) {
1467 $year = substr( $ts, 0, 4 );
1468 $month = substr( $ts, 4, 2 );
1469 $day = substr( $ts, 6, 2 );
1477 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1478 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1481 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1482 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1483 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1486 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1487 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1490 $zl = $zjd -1948440 +
10632;
1491 $zn = (int)( ( $zl - 1 ) / 10631 );
1492 $zl = $zl - 10631 * $zn +
354;
1493 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1494 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1495 $zm = (int)( ( 24 * $zl ) / 709 );
1496 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1497 $zy = 30 * $zn +
$zj - 30;
1499 return array( $zy, $zm, $zd );
1503 * Converting Gregorian dates to Hebrew dates.
1505 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1506 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1507 * to translate the relevant functions into PHP and release them under
1510 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1511 * and Adar II is 14. In a non-leap year, Adar is 6.
1517 private static function tsToHebrew( $ts ) {
1519 $year = substr( $ts, 0, 4 );
1520 $month = substr( $ts, 4, 2 );
1521 $day = substr( $ts, 6, 2 );
1523 # Calculate Hebrew year
1524 $hebrewYear = $year +
3760;
1526 # Month number when September = 1, August = 12
1528 if ( $month > 12 ) {
1535 # Calculate day of year from 1 September
1537 for ( $i = 1; $i < $month; $i++
) {
1541 # Check if the year is leap
1542 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1545 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1552 # Calculate the start of the Hebrew year
1553 $start = self
::hebrewYearStart( $hebrewYear );
1555 # Calculate next year's start
1556 if ( $dayOfYear <= $start ) {
1557 # Day is before the start of the year - it is the previous year
1559 $nextStart = $start;
1563 # Add days since previous year's 1 September
1565 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1569 # Start of the new (previous) year
1570 $start = self
::hebrewYearStart( $hebrewYear );
1573 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1576 # Calculate Hebrew day of year
1577 $hebrewDayOfYear = $dayOfYear - $start;
1579 # Difference between year's days
1580 $diff = $nextStart - $start;
1581 # Add 12 (or 13 for leap years) days to ignore the difference between
1582 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1583 # difference is only about the year type
1584 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1590 # Check the year pattern, and is leap year
1591 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1592 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1593 # and non-leap years
1594 $yearPattern = $diff %
30;
1595 # Check if leap year
1596 $isLeap = $diff >= 30;
1598 # Calculate day in the month from number of day in the Hebrew year
1599 # Don't check Adar - if the day is not in Adar, we will stop before;
1600 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1601 $hebrewDay = $hebrewDayOfYear;
1604 while ( $hebrewMonth <= 12 ) {
1605 # Calculate days in this month
1606 if ( $isLeap && $hebrewMonth == 6 ) {
1607 # Adar in a leap year
1609 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1611 if ( $hebrewDay <= $days ) {
1615 # Subtract the days of Adar I
1616 $hebrewDay -= $days;
1619 if ( $hebrewDay <= $days ) {
1625 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1626 # Cheshvan in a complete year (otherwise as the rule below)
1628 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1629 # Kislev in an incomplete year (otherwise as the rule below)
1632 # Odd months have 30 days, even have 29
1633 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1635 if ( $hebrewDay <= $days ) {
1636 # In the current month
1639 # Subtract the days of the current month
1640 $hebrewDay -= $days;
1641 # Try in the next month
1646 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1650 * This calculates the Hebrew year start, as days since 1 September.
1651 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1652 * Used for Hebrew date.
1658 private static function hebrewYearStart( $year ) {
1659 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1660 $b = intval( ( $year - 1 ) %
4 );
1661 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1665 $Mar = intval( $m );
1671 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1672 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1674 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1676 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1680 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1685 * Algorithm to convert Gregorian dates to Thai solar dates,
1686 * Minguo dates or Minguo dates.
1688 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1689 * http://en.wikipedia.org/wiki/Minguo_calendar
1690 * http://en.wikipedia.org/wiki/Japanese_era_name
1692 * @param $ts String: 14-character timestamp
1693 * @param $cName String: calender name
1694 * @return Array: converted year, month, day
1696 private static function tsToYear( $ts, $cName ) {
1697 $gy = substr( $ts, 0, 4 );
1698 $gm = substr( $ts, 4, 2 );
1699 $gd = substr( $ts, 6, 2 );
1701 if ( !strcmp( $cName, 'thai' ) ) {
1703 # Add 543 years to the Gregorian calendar
1704 # Months and days are identical
1705 $gy_offset = $gy +
543;
1706 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1708 # Deduct 1911 years from the Gregorian calendar
1709 # Months and days are identical
1710 $gy_offset = $gy - 1911;
1711 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1712 # Nengō dates up to Meiji period
1713 # Deduct years from the Gregorian calendar
1714 # depending on the nengo periods
1715 # Months and days are identical
1716 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1718 $gy_gannen = $gy - 1868 +
1;
1719 $gy_offset = $gy_gannen;
1720 if ( $gy_gannen == 1 ) {
1723 $gy_offset = '明治' . $gy_offset;
1725 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1726 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1727 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1728 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1729 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1733 $gy_gannen = $gy - 1912 +
1;
1734 $gy_offset = $gy_gannen;
1735 if ( $gy_gannen == 1 ) {
1738 $gy_offset = '大正' . $gy_offset;
1740 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1741 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1742 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1746 $gy_gannen = $gy - 1926 +
1;
1747 $gy_offset = $gy_gannen;
1748 if ( $gy_gannen == 1 ) {
1751 $gy_offset = '昭和' . $gy_offset;
1754 $gy_gannen = $gy - 1989 +
1;
1755 $gy_offset = $gy_gannen;
1756 if ( $gy_gannen == 1 ) {
1759 $gy_offset = '平成' . $gy_offset;
1765 return array( $gy_offset, $gm, $gd );
1769 * Roman number formatting up to 10000
1775 static function romanNumeral( $num ) {
1776 static $table = array(
1777 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1778 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1779 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1780 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1783 $num = intval( $num );
1784 if ( $num > 10000 ||
$num <= 0 ) {
1789 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1790 if ( $num >= $pow10 ) {
1791 $s .= $table[$i][(int)floor( $num / $pow10 )];
1793 $num = $num %
$pow10;
1799 * Hebrew Gematria number formatting up to 9999
1805 static function hebrewNumeral( $num ) {
1806 static $table = array(
1807 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1808 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1809 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1810 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1813 $num = intval( $num );
1814 if ( $num > 9999 ||
$num <= 0 ) {
1819 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1820 if ( $num >= $pow10 ) {
1821 if ( $num == 15 ||
$num == 16 ) {
1822 $s .= $table[0][9] . $table[0][$num - 9];
1825 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1826 if ( $pow10 == 1000 ) {
1831 $num = $num %
$pow10;
1833 if ( strlen( $s ) == 2 ) {
1836 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1837 $str .= substr( $s, strlen( $s ) - 2, 2 );
1839 $start = substr( $str, 0, strlen( $str ) - 2 );
1840 $end = substr( $str, strlen( $str ) - 2 );
1843 $str = $start . 'ך';
1846 $str = $start . 'ם';
1849 $str = $start . 'ן';
1852 $str = $start . 'ף';
1855 $str = $start . 'ץ';
1862 * Used by date() and time() to adjust the time output.
1864 * @param $ts Int the time in date('YmdHis') format
1865 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1866 * get user timecorrection setting)
1869 function userAdjust( $ts, $tz = false ) {
1870 global $wgUser, $wgLocalTZoffset;
1872 if ( $tz === false ) {
1873 $tz = $wgUser->getOption( 'timecorrection' );
1876 $data = explode( '|', $tz, 3 );
1878 if ( $data[0] == 'ZoneInfo' ) {
1879 wfSuppressWarnings();
1880 $userTZ = timezone_open( $data[2] );
1881 wfRestoreWarnings();
1882 if ( $userTZ !== false ) {
1883 $date = date_create( $ts, timezone_open( 'UTC' ) );
1884 date_timezone_set( $date, $userTZ );
1885 $date = date_format( $date, 'YmdHis' );
1888 # Unrecognized timezone, default to 'Offset' with the stored offset.
1889 $data[0] = 'Offset';
1893 if ( $data[0] == 'System' ||
$tz == '' ) {
1894 # Global offset in minutes.
1895 if ( isset( $wgLocalTZoffset ) ) {
1896 $minDiff = $wgLocalTZoffset;
1898 } elseif ( $data[0] == 'Offset' ) {
1899 $minDiff = intval( $data[1] );
1901 $data = explode( ':', $tz );
1902 if ( count( $data ) == 2 ) {
1903 $data[0] = intval( $data[0] );
1904 $data[1] = intval( $data[1] );
1905 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1906 if ( $data[0] < 0 ) {
1907 $minDiff = -$minDiff;
1910 $minDiff = intval( $data[0] ) * 60;
1914 # No difference ? Return time unchanged
1915 if ( 0 == $minDiff ) {
1919 wfSuppressWarnings(); // E_STRICT system time bitching
1920 # Generate an adjusted date; take advantage of the fact that mktime
1921 # will normalize out-of-range values so we don't have to split $minDiff
1922 # into hours and minutes.
1924 (int)substr( $ts, 8, 2 ) ), # Hours
1925 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1926 (int)substr( $ts, 12, 2 ), # Seconds
1927 (int)substr( $ts, 4, 2 ), # Month
1928 (int)substr( $ts, 6, 2 ), # Day
1929 (int)substr( $ts, 0, 4 ) ); # Year
1931 $date = date( 'YmdHis', $t );
1932 wfRestoreWarnings();
1938 * This is meant to be used by time(), date(), and timeanddate() to get
1939 * the date preference they're supposed to use, it should be used in
1943 * function timeanddate([...], $format = true) {
1944 * $datePreference = $this->dateFormat($format);
1949 * @param $usePrefs Mixed: if true, the user's preference is used
1950 * if false, the site/language default is used
1951 * if int/string, assumed to be a format.
1954 function dateFormat( $usePrefs = true ) {
1957 if ( is_bool( $usePrefs ) ) {
1959 $datePreference = $wgUser->getDatePreference();
1961 $datePreference = (string)User
::getDefaultOption( 'date' );
1964 $datePreference = (string)$usePrefs;
1968 if ( $datePreference == '' ) {
1972 return $datePreference;
1976 * Get a format string for a given type and preference
1977 * @param $type string May be date, time or both
1978 * @param $pref string The format name as it appears in Messages*.php
1982 function getDateFormatString( $type, $pref ) {
1983 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1984 if ( $pref == 'default' ) {
1985 $pref = $this->getDefaultDateFormat();
1986 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1988 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1989 if ( is_null( $df ) ) {
1990 $pref = $this->getDefaultDateFormat();
1991 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1994 $this->dateFormatStrings
[$type][$pref] = $df;
1996 return $this->dateFormatStrings
[$type][$pref];
2000 * @param $ts Mixed: the time format which needs to be turned into a
2001 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2002 * @param $adj Bool: whether to adjust the time output according to the
2003 * user configured offset ($timecorrection)
2004 * @param $format Mixed: true to use user's date format preference
2005 * @param $timecorrection String|bool the time offset as returned by
2006 * validateTimeZone() in Special:Preferences
2009 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2010 $ts = wfTimestamp( TS_MW
, $ts );
2012 $ts = $this->userAdjust( $ts, $timecorrection );
2014 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2015 return $this->sprintfDate( $df, $ts );
2019 * @param $ts Mixed: the time format which needs to be turned into a
2020 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2021 * @param $adj Bool: whether to adjust the time output according to the
2022 * user configured offset ($timecorrection)
2023 * @param $format Mixed: true to use user's date format preference
2024 * @param $timecorrection String|bool the time offset as returned by
2025 * validateTimeZone() in Special:Preferences
2028 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2029 $ts = wfTimestamp( TS_MW
, $ts );
2031 $ts = $this->userAdjust( $ts, $timecorrection );
2033 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2034 return $this->sprintfDate( $df, $ts );
2038 * @param $ts Mixed: the time format which needs to be turned into a
2039 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2040 * @param $adj Bool: whether to adjust the time output according to the
2041 * user configured offset ($timecorrection)
2042 * @param $format Mixed: what format to return, if it's false output the
2043 * default one (default true)
2044 * @param $timecorrection String|bool the time offset as returned by
2045 * validateTimeZone() in Special:Preferences
2048 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2049 $ts = wfTimestamp( TS_MW
, $ts );
2051 $ts = $this->userAdjust( $ts, $timecorrection );
2053 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2054 return $this->sprintfDate( $df, $ts );
2058 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2062 * @param integer $seconds The amount of seconds.
2063 * @param array $chosenIntervals The intervals to enable.
2067 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2068 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2070 $segments = array();
2072 foreach ( $intervals as $intervalName => $intervalValue ) {
2073 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2074 $segments[] = $message->inLanguage( $this )->escaped();
2077 return $this->listToText( $segments );
2081 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2082 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2086 * @param integer $seconds The amount of seconds.
2087 * @param array $chosenIntervals The intervals to enable.
2091 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2092 if ( empty( $chosenIntervals ) ) {
2093 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2096 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2097 $sortedNames = array_keys( $intervals );
2098 $smallestInterval = array_pop( $sortedNames );
2100 $segments = array();
2102 foreach ( $intervals as $name => $length ) {
2103 $value = floor( $seconds / $length );
2105 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2106 $seconds -= $value * $length;
2107 $segments[$name] = $value;
2115 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2117 * @param $type String: can be 'date', 'time' or 'both'
2118 * @param $ts Mixed: the time format which needs to be turned into a
2119 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2120 * @param $user User object used to get preferences for timezone and format
2121 * @param $options Array, can contain the following keys:
2122 * - 'timecorrection': time correction, can have the following values:
2123 * - true: use user's preference
2124 * - false: don't use time correction
2125 * - integer: value of time correction in minutes
2126 * - 'format': format to use, can have the following values:
2127 * - true: use user's preference
2128 * - false: use default preference
2129 * - string: format to use
2133 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2134 $ts = wfTimestamp( TS_MW
, $ts );
2135 $options +
= array( 'timecorrection' => true, 'format' => true );
2136 if ( $options['timecorrection'] !== false ) {
2137 if ( $options['timecorrection'] === true ) {
2138 $offset = $user->getOption( 'timecorrection' );
2140 $offset = $options['timecorrection'];
2142 $ts = $this->userAdjust( $ts, $offset );
2144 if ( $options['format'] === true ) {
2145 $format = $user->getDatePreference();
2147 $format = $options['format'];
2149 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2150 return $this->sprintfDate( $df, $ts );
2154 * Get the formatted date for the given timestamp and formatted for
2157 * @param $ts Mixed: the time format which needs to be turned into a
2158 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2159 * @param $user User object used to get preferences for timezone and format
2160 * @param $options Array, can contain the following keys:
2161 * - 'timecorrection': time correction, can have the following values:
2162 * - true: use user's preference
2163 * - false: don't use time correction
2164 * - integer: value of time correction in minutes
2165 * - 'format': format to use, can have the following values:
2166 * - true: use user's preference
2167 * - false: use default preference
2168 * - string: format to use
2172 public function userDate( $ts, User
$user, array $options = array() ) {
2173 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2177 * Get the formatted time for the given timestamp and formatted for
2180 * @param $ts Mixed: the time format which needs to be turned into a
2181 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2182 * @param $user User object used to get preferences for timezone and format
2183 * @param $options Array, can contain the following keys:
2184 * - 'timecorrection': time correction, can have the following values:
2185 * - true: use user's preference
2186 * - false: don't use time correction
2187 * - integer: value of time correction in minutes
2188 * - 'format': format to use, can have the following values:
2189 * - true: use user's preference
2190 * - false: use default preference
2191 * - string: format to use
2195 public function userTime( $ts, User
$user, array $options = array() ) {
2196 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2200 * Get the formatted date and time for the given timestamp and formatted for
2203 * @param $ts Mixed: the time format which needs to be turned into a
2204 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2205 * @param $user User object used to get preferences for timezone and format
2206 * @param $options Array, can contain the following keys:
2207 * - 'timecorrection': time correction, can have the following values:
2208 * - true: use user's preference
2209 * - false: don't use time correction
2210 * - integer: value of time correction in minutes
2211 * - 'format': format to use, can have the following values:
2212 * - true: use user's preference
2213 * - false: use default preference
2214 * - string: format to use
2218 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2219 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2223 * @param $key string
2224 * @return array|null
2226 function getMessage( $key ) {
2227 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2233 function getAllMessages() {
2234 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2243 function iconv( $in, $out, $string ) {
2244 # This is a wrapper for iconv in all languages except esperanto,
2245 # which does some nasty x-conversions beforehand
2247 # Even with //IGNORE iconv can whine about illegal characters in
2248 # *input* string. We just ignore those too.
2249 # REF: http://bugs.php.net/bug.php?id=37166
2250 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2251 wfSuppressWarnings();
2252 $text = iconv( $in, $out . '//IGNORE', $string );
2253 wfRestoreWarnings();
2257 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2260 * @param $matches array
2261 * @return mixed|string
2263 function ucwordbreaksCallbackAscii( $matches ) {
2264 return $this->ucfirst( $matches[1] );
2268 * @param $matches array
2271 function ucwordbreaksCallbackMB( $matches ) {
2272 return mb_strtoupper( $matches[0] );
2276 * @param $matches array
2279 function ucCallback( $matches ) {
2280 list( $wikiUpperChars ) = self
::getCaseMaps();
2281 return strtr( $matches[1], $wikiUpperChars );
2285 * @param $matches array
2288 function lcCallback( $matches ) {
2289 list( , $wikiLowerChars ) = self
::getCaseMaps();
2290 return strtr( $matches[1], $wikiLowerChars );
2294 * @param $matches array
2297 function ucwordsCallbackMB( $matches ) {
2298 return mb_strtoupper( $matches[0] );
2302 * @param $matches array
2305 function ucwordsCallbackWiki( $matches ) {
2306 list( $wikiUpperChars ) = self
::getCaseMaps();
2307 return strtr( $matches[0], $wikiUpperChars );
2311 * Make a string's first character uppercase
2313 * @param $str string
2317 function ucfirst( $str ) {
2319 if ( $o < 96 ) { // if already uppercase...
2321 } elseif ( $o < 128 ) {
2322 return ucfirst( $str ); // use PHP's ucfirst()
2324 // fall back to more complex logic in case of multibyte strings
2325 return $this->uc( $str, true );
2330 * Convert a string to uppercase
2332 * @param $str string
2333 * @param $first bool
2337 function uc( $str, $first = false ) {
2338 if ( function_exists( 'mb_strtoupper' ) ) {
2340 if ( $this->isMultibyte( $str ) ) {
2341 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2343 return ucfirst( $str );
2346 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2349 if ( $this->isMultibyte( $str ) ) {
2350 $x = $first ?
'^' : '';
2351 return preg_replace_callback(
2352 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2353 array( $this, 'ucCallback' ),
2357 return $first ?
ucfirst( $str ) : strtoupper( $str );
2363 * @param $str string
2364 * @return mixed|string
2366 function lcfirst( $str ) {
2369 return strval( $str );
2370 } elseif ( $o >= 128 ) {
2371 return $this->lc( $str, true );
2372 } elseif ( $o > 96 ) {
2375 $str[0] = strtolower( $str[0] );
2381 * @param $str string
2382 * @param $first bool
2383 * @return mixed|string
2385 function lc( $str, $first = false ) {
2386 if ( function_exists( 'mb_strtolower' ) ) {
2388 if ( $this->isMultibyte( $str ) ) {
2389 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2391 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2394 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2397 if ( $this->isMultibyte( $str ) ) {
2398 $x = $first ?
'^' : '';
2399 return preg_replace_callback(
2400 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2401 array( $this, 'lcCallback' ),
2405 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2411 * @param $str string
2414 function isMultibyte( $str ) {
2415 return (bool)preg_match( '/[\x80-\xff]/', $str );
2419 * @param $str string
2420 * @return mixed|string
2422 function ucwords( $str ) {
2423 if ( $this->isMultibyte( $str ) ) {
2424 $str = $this->lc( $str );
2426 // regexp to find first letter in each word (i.e. after each space)
2427 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2429 // function to use to capitalize a single char
2430 if ( function_exists( 'mb_strtoupper' ) ) {
2431 return preg_replace_callback(
2433 array( $this, 'ucwordsCallbackMB' ),
2437 return preg_replace_callback(
2439 array( $this, 'ucwordsCallbackWiki' ),
2444 return ucwords( strtolower( $str ) );
2449 * capitalize words at word breaks
2451 * @param $str string
2454 function ucwordbreaks( $str ) {
2455 if ( $this->isMultibyte( $str ) ) {
2456 $str = $this->lc( $str );
2458 // since \b doesn't work for UTF-8, we explicitely define word break chars
2459 $breaks = "[ \-\(\)\}\{\.,\?!]";
2461 // find first letter after word break
2462 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2464 if ( function_exists( 'mb_strtoupper' ) ) {
2465 return preg_replace_callback(
2467 array( $this, 'ucwordbreaksCallbackMB' ),
2471 return preg_replace_callback(
2473 array( $this, 'ucwordsCallbackWiki' ),
2478 return preg_replace_callback(
2479 '/\b([\w\x80-\xff]+)\b/',
2480 array( $this, 'ucwordbreaksCallbackAscii' ),
2487 * Return a case-folded representation of $s
2489 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2490 * and $s2 are the same except for the case of their characters. It is not
2491 * necessary for the value returned to make sense when displayed.
2493 * Do *not* perform any other normalisation in this function. If a caller
2494 * uses this function when it should be using a more general normalisation
2495 * function, then fix the caller.
2501 function caseFold( $s ) {
2502 return $this->uc( $s );
2509 function checkTitleEncoding( $s ) {
2510 if ( is_array( $s ) ) {
2511 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2513 if ( StringUtils
::isUtf8( $s ) ) {
2517 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2523 function fallback8bitEncoding() {
2524 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2528 * Most writing systems use whitespace to break up words.
2529 * Some languages such as Chinese don't conventionally do this,
2530 * which requires special handling when breaking up words for
2535 function hasWordBreaks() {
2540 * Some languages such as Chinese require word segmentation,
2541 * Specify such segmentation when overridden in derived class.
2543 * @param $string String
2546 function segmentByWord( $string ) {
2551 * Some languages have special punctuation need to be normalized.
2552 * Make such changes here.
2554 * @param $string String
2557 function normalizeForSearch( $string ) {
2558 return self
::convertDoubleWidth( $string );
2562 * convert double-width roman characters to single-width.
2563 * range: ff00-ff5f ~= 0020-007f
2565 * @param $string string
2569 protected static function convertDoubleWidth( $string ) {
2570 static $full = null;
2571 static $half = null;
2573 if ( $full === null ) {
2574 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2575 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2576 $full = str_split( $fullWidth, 3 );
2577 $half = str_split( $halfWidth );
2580 $string = str_replace( $full, $half, $string );
2585 * @param $string string
2586 * @param $pattern string
2589 protected static function insertSpace( $string, $pattern ) {
2590 $string = preg_replace( $pattern, " $1 ", $string );
2591 $string = preg_replace( '/ +/', ' ', $string );
2596 * @param $termsArray array
2599 function convertForSearchResult( $termsArray ) {
2600 # some languages, e.g. Chinese, need to do a conversion
2601 # in order for search results to be displayed correctly
2606 * Get the first character of a string.
2611 function firstChar( $s ) {
2614 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2615 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2620 if ( isset( $matches[1] ) ) {
2621 if ( strlen( $matches[1] ) != 3 ) {
2625 // Break down Hangul syllables to grab the first jamo
2626 $code = utf8ToCodepoint( $matches[1] );
2627 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2629 } elseif ( $code < 0xb098 ) {
2630 return "\xe3\x84\xb1";
2631 } elseif ( $code < 0xb2e4 ) {
2632 return "\xe3\x84\xb4";
2633 } elseif ( $code < 0xb77c ) {
2634 return "\xe3\x84\xb7";
2635 } elseif ( $code < 0xb9c8 ) {
2636 return "\xe3\x84\xb9";
2637 } elseif ( $code < 0xbc14 ) {
2638 return "\xe3\x85\x81";
2639 } elseif ( $code < 0xc0ac ) {
2640 return "\xe3\x85\x82";
2641 } elseif ( $code < 0xc544 ) {
2642 return "\xe3\x85\x85";
2643 } elseif ( $code < 0xc790 ) {
2644 return "\xe3\x85\x87";
2645 } elseif ( $code < 0xcc28 ) {
2646 return "\xe3\x85\x88";
2647 } elseif ( $code < 0xce74 ) {
2648 return "\xe3\x85\x8a";
2649 } elseif ( $code < 0xd0c0 ) {
2650 return "\xe3\x85\x8b";
2651 } elseif ( $code < 0xd30c ) {
2652 return "\xe3\x85\x8c";
2653 } elseif ( $code < 0xd558 ) {
2654 return "\xe3\x85\x8d";
2656 return "\xe3\x85\x8e";
2663 function initEncoding() {
2664 # Some languages may have an alternate char encoding option
2665 # (Esperanto X-coding, Japanese furigana conversion, etc)
2666 # If this language is used as the primary content language,
2667 # an override to the defaults can be set here on startup.
2674 function recodeForEdit( $s ) {
2675 # For some languages we'll want to explicitly specify
2676 # which characters make it into the edit box raw
2677 # or are converted in some way or another.
2678 global $wgEditEncoding;
2679 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2682 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2690 function recodeInput( $s ) {
2691 # Take the previous into account.
2692 global $wgEditEncoding;
2693 if ( $wgEditEncoding != '' ) {
2694 $enc = $wgEditEncoding;
2698 if ( $enc == 'UTF-8' ) {
2701 return $this->iconv( $enc, 'UTF-8', $s );
2706 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2707 * also cleans up certain backwards-compatible sequences, converting them
2708 * to the modern Unicode equivalent.
2710 * This is language-specific for performance reasons only.
2716 function normalize( $s ) {
2717 global $wgAllUnicodeFixes;
2718 $s = UtfNormal
::cleanUp( $s );
2719 if ( $wgAllUnicodeFixes ) {
2720 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2721 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2728 * Transform a string using serialized data stored in the given file (which
2729 * must be in the serialized subdirectory of $IP). The file contains pairs
2730 * mapping source characters to destination characters.
2732 * The data is cached in process memory. This will go faster if you have the
2733 * FastStringSearch extension.
2735 * @param $file string
2736 * @param $string string
2738 * @throws MWException
2741 function transformUsingPairFile( $file, $string ) {
2742 if ( !isset( $this->transformData
[$file] ) ) {
2743 $data = wfGetPrecompiledData( $file );
2744 if ( $data === false ) {
2745 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2747 $this->transformData
[$file] = new ReplacementArray( $data );
2749 return $this->transformData
[$file]->replace( $string );
2753 * For right-to-left language support
2758 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2762 * Return the correct HTML 'dir' attribute value for this language.
2766 return $this->isRTL() ?
'rtl' : 'ltr';
2770 * Return 'left' or 'right' as appropriate alignment for line-start
2771 * for this language's text direction.
2773 * Should be equivalent to CSS3 'start' text-align value....
2777 function alignStart() {
2778 return $this->isRTL() ?
'right' : 'left';
2782 * Return 'right' or 'left' as appropriate alignment for line-end
2783 * for this language's text direction.
2785 * Should be equivalent to CSS3 'end' text-align value....
2789 function alignEnd() {
2790 return $this->isRTL() ?
'left' : 'right';
2794 * A hidden direction mark (LRM or RLM), depending on the language direction.
2795 * Unlike getDirMark(), this function returns the character as an HTML entity.
2796 * This function should be used when the output is guaranteed to be HTML,
2797 * because it makes the output HTML source code more readable. When
2798 * the output is plain text or can be escaped, getDirMark() should be used.
2800 * @param $opposite Boolean Get the direction mark opposite to your language
2804 function getDirMarkEntity( $opposite = false ) {
2805 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2806 return $this->isRTL() ?
'‏' : '‎';
2810 * A hidden direction mark (LRM or RLM), depending on the language direction.
2811 * This function produces them as invisible Unicode characters and
2812 * the output may be hard to read and debug, so it should only be used
2813 * when the output is plain text or can be escaped. When the output is
2814 * HTML, use getDirMarkEntity() instead.
2816 * @param $opposite Boolean Get the direction mark opposite to your language
2819 function getDirMark( $opposite = false ) {
2820 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2821 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2822 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2823 return $this->isRTL() ?
$rlm : $lrm;
2829 function capitalizeAllNouns() {
2830 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2834 * An arrow, depending on the language direction.
2836 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2839 function getArrow( $direction = 'forwards' ) {
2840 switch ( $direction ) {
2842 return $this->isRTL() ?
'←' : '→';
2844 return $this->isRTL() ?
'→' : '←';
2857 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2861 function linkPrefixExtension() {
2862 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2868 function getMagicWords() {
2869 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2872 protected function doMagicHook() {
2873 if ( $this->mMagicHookDone
) {
2876 $this->mMagicHookDone
= true;
2877 wfProfileIn( 'LanguageGetMagic' );
2878 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2879 wfProfileOut( 'LanguageGetMagic' );
2883 * Fill a MagicWord object with data from here
2887 function getMagic( $mw ) {
2888 $this->doMagicHook();
2890 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2891 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2893 $magicWords = $this->getMagicWords();
2894 if ( isset( $magicWords[$mw->mId
] ) ) {
2895 $rawEntry = $magicWords[$mw->mId
];
2901 if ( !is_array( $rawEntry ) ) {
2902 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2904 $mw->mCaseSensitive
= $rawEntry[0];
2905 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2910 * Add magic words to the extension array
2912 * @param $newWords array
2914 function addMagicWordsByLang( $newWords ) {
2915 $fallbackChain = $this->getFallbackLanguages();
2916 $fallbackChain = array_reverse( $fallbackChain );
2917 foreach ( $fallbackChain as $code ) {
2918 if ( isset( $newWords[$code] ) ) {
2919 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2925 * Get special page names, as an associative array
2926 * case folded alias => real name
2928 function getSpecialPageAliases() {
2929 // Cache aliases because it may be slow to load them
2930 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2932 $this->mExtendedSpecialPageAliases
=
2933 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2934 wfRunHooks( 'LanguageGetSpecialPageAliases',
2935 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2938 return $this->mExtendedSpecialPageAliases
;
2942 * Italic is unsuitable for some languages
2944 * @param $text String: the text to be emphasized.
2947 function emphasize( $text ) {
2948 return "<em>$text</em>";
2952 * Normally we output all numbers in plain en_US style, that is
2953 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2954 * point twohundredthirtyfive. However this is not suitable for all
2955 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2956 * Icelandic just want to use commas instead of dots, and dots instead
2957 * of commas like "293.291,235".
2959 * An example of this function being called:
2961 * wfMessage( 'message' )->numParams( $num )->text()
2964 * See LanguageGu.php for the Gujarati implementation and
2965 * $separatorTransformTable on MessageIs.php for
2966 * the , => . and . => , implementation.
2968 * @todo check if it's viable to use localeconv() for the decimal
2970 * @param $number Mixed: the string to be formatted, should be an integer
2971 * or a floating point number.
2972 * @param $nocommafy Bool: set to true for special numbers like dates
2975 public function formatNum( $number, $nocommafy = false ) {
2976 global $wgTranslateNumerals;
2977 if ( !$nocommafy ) {
2978 $number = $this->commafy( $number );
2979 $s = $this->separatorTransformTable();
2981 $number = strtr( $number, $s );
2985 if ( $wgTranslateNumerals ) {
2986 $s = $this->digitTransformTable();
2988 $number = strtr( $number, $s );
2996 * Front-end for non-commafied formatNum
2998 * @param mixed $number the string to be formatted, should be an integer
2999 * or a floating point number.
3003 public function formatNumNoSeparators( $number ) {
3004 return $this->formatNum( $number, true );
3008 * @param $number string
3011 function parseFormattedNumber( $number ) {
3012 $s = $this->digitTransformTable();
3014 $number = strtr( $number, array_flip( $s ) );
3017 $s = $this->separatorTransformTable();
3019 $number = strtr( $number, array_flip( $s ) );
3022 $number = strtr( $number, array( ',' => '' ) );
3027 * Adds commas to a given number
3029 * @param $number mixed
3032 function commafy( $number ) {
3033 $digitGroupingPattern = $this->digitGroupingPattern();
3034 if ( $number === null ) {
3038 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3039 // default grouping is at thousands, use the same for ###,###,### pattern too.
3040 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3042 // Ref: http://cldr.unicode.org/translation/number-patterns
3044 if ( intval( $number ) < 0 ) {
3045 // For negative numbers apply the algorithm like positive number and add sign.
3047 $number = substr( $number, 1 );
3049 $integerPart = array();
3050 $decimalPart = array();
3051 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3052 preg_match( "/\d+/", $number, $integerPart );
3053 preg_match( "/\.\d*/", $number, $decimalPart );
3054 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0]:"";
3055 if ( $groupedNumber === $number ) {
3056 // the string does not have any number part. Eg: .12345
3057 return $sign . $groupedNumber;
3059 $start = $end = strlen( $integerPart[0] );
3060 while ( $start > 0 ) {
3061 $match = $matches[0][$numMatches -1] ;
3062 $matchLen = strlen( $match );
3063 $start = $end - $matchLen;
3067 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber ;
3069 if ( $numMatches > 1 ) {
3070 // use the last pattern for the rest of the number
3074 $groupedNumber = "," . $groupedNumber;
3077 return $sign . $groupedNumber;
3084 function digitGroupingPattern() {
3085 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3091 function digitTransformTable() {
3092 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3098 function separatorTransformTable() {
3099 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3103 * Take a list of strings and build a locale-friendly comma-separated
3104 * list, using the local comma-separator message.
3105 * The last two strings are chained with an "and".
3106 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3111 function listToText( array $l ) {
3112 $m = count( $l ) - 1;
3117 $and = $this->getMessageFromDB( 'and' );
3118 $space = $this->getMessageFromDB( 'word-separator' );
3120 $comma = $this->getMessageFromDB( 'comma-separator' );
3124 for ( $i = $m - 1; $i >= 0; $i-- ) {
3125 if ( $i == $m - 1 ) {
3126 $s = $l[$i] . $and . $space . $s;
3128 $s = $l[$i] . $comma . $s;
3135 * Take a list of strings and build a locale-friendly comma-separated
3136 * list, using the local comma-separator message.
3137 * @param $list array of strings to put in a comma list
3140 function commaList( array $list ) {
3142 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3148 * Take a list of strings and build a locale-friendly semicolon-separated
3149 * list, using the local semicolon-separator message.
3150 * @param $list array of strings to put in a semicolon list
3153 function semicolonList( array $list ) {
3155 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3161 * Same as commaList, but separate it with the pipe instead.
3162 * @param $list array of strings to put in a pipe list
3165 function pipeList( array $list ) {
3167 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3173 * Truncate a string to a specified length in bytes, appending an optional
3174 * string (e.g. for ellipses)
3176 * The database offers limited byte lengths for some columns in the database;
3177 * multi-byte character sets mean we need to ensure that only whole characters
3178 * are included, otherwise broken characters can be passed to the user
3180 * If $length is negative, the string will be truncated from the beginning
3182 * @param $string String to truncate
3183 * @param $length Int: maximum length (including ellipses)
3184 * @param $ellipsis String to append to the truncated text
3185 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3186 * $adjustLength was introduced in 1.18, before that behaved as if false.
3189 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3190 # Use the localized ellipsis character
3191 if ( $ellipsis == '...' ) {
3192 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3194 # Check if there is no need to truncate
3195 if ( $length == 0 ) {
3196 return $ellipsis; // convention
3197 } elseif ( strlen( $string ) <= abs( $length ) ) {
3198 return $string; // no need to truncate
3200 $stringOriginal = $string;
3201 # If ellipsis length is >= $length then we can't apply $adjustLength
3202 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3203 $string = $ellipsis; // this can be slightly unexpected
3204 # Otherwise, truncate and add ellipsis...
3206 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3207 if ( $length > 0 ) {
3208 $length -= $eLength;
3209 $string = substr( $string, 0, $length ); // xyz...
3210 $string = $this->removeBadCharLast( $string );
3211 $string = $string . $ellipsis;
3213 $length +
= $eLength;
3214 $string = substr( $string, $length ); // ...xyz
3215 $string = $this->removeBadCharFirst( $string );
3216 $string = $ellipsis . $string;
3219 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3220 # This check is *not* redundant if $adjustLength, due to the single case where
3221 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3222 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3225 return $stringOriginal;
3230 * Remove bytes that represent an incomplete Unicode character
3231 * at the end of string (e.g. bytes of the char are missing)
3233 * @param $string String
3236 protected function removeBadCharLast( $string ) {
3237 if ( $string != '' ) {
3238 $char = ord( $string[strlen( $string ) - 1] );
3240 if ( $char >= 0xc0 ) {
3241 # We got the first byte only of a multibyte char; remove it.
3242 $string = substr( $string, 0, -1 );
3243 } elseif ( $char >= 0x80 &&
3244 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3245 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3247 # We chopped in the middle of a character; remove it
3255 * Remove bytes that represent an incomplete Unicode character
3256 * at the start of string (e.g. bytes of the char are missing)
3258 * @param $string String
3261 protected function removeBadCharFirst( $string ) {
3262 if ( $string != '' ) {
3263 $char = ord( $string[0] );
3264 if ( $char >= 0x80 && $char < 0xc0 ) {
3265 # We chopped in the middle of a character; remove the whole thing
3266 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3273 * Truncate a string of valid HTML to a specified length in bytes,
3274 * appending an optional string (e.g. for ellipses), and return valid HTML
3276 * This is only intended for styled/linked text, such as HTML with
3277 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3278 * Also, this will not detect things like "display:none" CSS.
3280 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3282 * @param string $text HTML string to truncate
3283 * @param int $length (zero/positive) Maximum length (including ellipses)
3284 * @param string $ellipsis String to append to the truncated text
3287 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3288 # Use the localized ellipsis character
3289 if ( $ellipsis == '...' ) {
3290 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3292 # Check if there is clearly no need to truncate
3293 if ( $length <= 0 ) {
3294 return $ellipsis; // no text shown, nothing to format (convention)
3295 } elseif ( strlen( $text ) <= $length ) {
3296 return $text; // string short enough even *with* HTML (short-circuit)
3299 $dispLen = 0; // innerHTML legth so far
3300 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3301 $tagType = 0; // 0-open, 1-close
3302 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3303 $entityState = 0; // 0-not entity, 1-entity
3304 $tag = $ret = ''; // accumulated tag name, accumulated result string
3305 $openTags = array(); // open tag stack
3306 $maybeState = null; // possible truncation state
3308 $textLen = strlen( $text );
3309 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3310 for ( $pos = 0; true; ++
$pos ) {
3311 # Consider truncation once the display length has reached the maximim.
3312 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3313 # Check that we're not in the middle of a bracket/entity...
3314 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3315 if ( !$testingEllipsis ) {
3316 $testingEllipsis = true;
3317 # Save where we are; we will truncate here unless there turn out to
3318 # be so few remaining characters that truncation is not necessary.
3319 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3320 $maybeState = array( $ret, $openTags ); // save state
3322 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3323 # String in fact does need truncation, the truncation point was OK.
3324 list( $ret, $openTags ) = $maybeState; // reload state
3325 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3326 $ret .= $ellipsis; // add ellipsis
3330 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3332 # Read the next char...
3334 $lastCh = $pos ?
$text[$pos - 1] : '';
3335 $ret .= $ch; // add to result string
3337 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3338 $entityState = 0; // for bad HTML
3339 $bracketState = 1; // tag started (checking for backslash)
3340 } elseif ( $ch == '>' ) {
3341 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3342 $entityState = 0; // for bad HTML
3343 $bracketState = 0; // out of brackets
3344 } elseif ( $bracketState == 1 ) {
3346 $tagType = 1; // close tag (e.g. "</span>")
3348 $tagType = 0; // open tag (e.g. "<span>")
3351 $bracketState = 2; // building tag name
3352 } elseif ( $bracketState == 2 ) {
3356 // Name found (e.g. "<a href=..."), add on tag attributes...
3357 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3359 } elseif ( $bracketState == 0 ) {
3360 if ( $entityState ) {
3363 $dispLen++
; // entity is one displayed char
3366 if ( $neLength == 0 && !$maybeState ) {
3367 // Save state without $ch. We want to *hit* the first
3368 // display char (to get tags) but not *use* it if truncating.
3369 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3372 $entityState = 1; // entity found, (e.g. " ")
3374 $dispLen++
; // this char is displayed
3375 // Add the next $max display text chars after this in one swoop...
3376 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3377 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3378 $dispLen +
= $skipped;
3384 // Close the last tag if left unclosed by bad HTML
3385 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3386 while ( count( $openTags ) > 0 ) {
3387 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3393 * truncateHtml() helper function
3394 * like strcspn() but adds the skipped chars to $ret
3403 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3404 if ( $len === null ) {
3405 $len = -1; // -1 means "no limit" for strcspn
3406 } elseif ( $len < 0 ) {
3410 if ( $start < strlen( $text ) ) {
3411 $skipCount = strcspn( $text, $search, $start, $len );
3412 $ret .= substr( $text, $start, $skipCount );
3418 * truncateHtml() helper function
3419 * (a) push or pop $tag from $openTags as needed
3420 * (b) clear $tag value
3421 * @param &$tag string Current HTML tag name we are looking at
3422 * @param $tagType int (0-open tag, 1-close tag)
3423 * @param $lastCh string Character before the '>' that ended this tag
3424 * @param &$openTags array Open tag stack (not accounting for $tag)
3426 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3427 $tag = ltrim( $tag );
3429 if ( $tagType == 0 && $lastCh != '/' ) {
3430 $openTags[] = $tag; // tag opened (didn't close itself)
3431 } elseif ( $tagType == 1 ) {
3432 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3433 array_pop( $openTags ); // tag closed
3441 * Grammatical transformations, needed for inflected languages
3442 * Invoked by putting {{grammar:case|word}} in a message
3444 * @param $word string
3445 * @param $case string
3448 function convertGrammar( $word, $case ) {
3449 global $wgGrammarForms;
3450 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3451 return $wgGrammarForms[$this->getCode()][$case][$word];
3456 * Get the grammar forms for the content language
3457 * @return array of grammar forms
3460 function getGrammarForms() {
3461 global $wgGrammarForms;
3462 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3463 return $wgGrammarForms[$this->getCode()];
3468 * Provides an alternative text depending on specified gender.
3469 * Usage {{gender:username|masculine|feminine|neutral}}.
3470 * username is optional, in which case the gender of current user is used,
3471 * but only in (some) interface messages; otherwise default gender is used.
3473 * If no forms are given, an empty string is returned. If only one form is
3474 * given, it will be returned unconditionally. These details are implied by
3475 * the caller and cannot be overridden in subclasses.
3477 * If more than one form is given, the default is to use the neutral one
3478 * if it is specified, and to use the masculine one otherwise. These
3479 * details can be overridden in subclasses.
3481 * @param $gender string
3482 * @param $forms array
3486 function gender( $gender, $forms ) {
3487 if ( !count( $forms ) ) {
3490 $forms = $this->preConvertPlural( $forms, 2 );
3491 if ( $gender === 'male' ) {
3494 if ( $gender === 'female' ) {
3497 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3501 * Plural form transformations, needed for some languages.
3502 * For example, there are 3 form of plural in Russian and Polish,
3503 * depending on "count mod 10". See [[w:Plural]]
3504 * For English it is pretty simple.
3506 * Invoked by putting {{plural:count|wordform1|wordform2}}
3507 * or {{plural:count|wordform1|wordform2|wordform3}}
3509 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3511 * @param $count Integer: non-localized number
3512 * @param $forms Array: different plural forms
3513 * @return string Correct form of plural for $count in this language
3515 function convertPlural( $count, $forms ) {
3516 if ( !count( $forms ) ) {
3520 // Handle explicit n=pluralform cases
3521 foreach ( $forms as $index => $form ) {
3522 if ( preg_match( '/\d+=/i', $form ) ) {
3523 $pos = strpos( $form, '=' );
3524 if ( substr( $form, 0, $pos ) === (string) $count ) {
3525 return substr( $form, $pos +
1 );
3527 unset( $forms[$index] );
3530 $forms = array_values( $forms );
3532 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3533 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3534 return $forms[$pluralForm];
3538 * Checks that convertPlural was given an array and pads it to requested
3539 * amount of forms by copying the last one.
3541 * @param $count Integer: How many forms should there be at least
3542 * @param $forms Array of forms given to convertPlural
3543 * @return array Padded array of forms or an exception if not an array
3545 protected function preConvertPlural( /* Array */ $forms, $count ) {
3546 while ( count( $forms ) < $count ) {
3547 $forms[] = $forms[count( $forms ) - 1];
3553 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3554 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3555 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3556 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3559 * @param $str String: the validated block duration in English
3560 * @return string Somehow translated block duration
3561 * @see LanguageFi.php for example implementation
3563 function translateBlockExpiry( $str ) {
3564 $duration = SpecialBlock
::getSuggestedDurations( $this );
3565 foreach ( $duration as $show => $value ) {
3566 if ( strcmp( $str, $value ) == 0 ) {
3567 return htmlspecialchars( trim( $show ) );
3571 // Since usually only infinite or indefinite is only on list, so try
3572 // equivalents if still here.
3573 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3574 if ( in_array( $str, $indefs ) ) {
3575 foreach ( $indefs as $val ) {
3576 $show = array_search( $val, $duration, true );
3577 if ( $show !== false ) {
3578 return htmlspecialchars( trim( $show ) );
3583 // If all else fails, return a standard duration or timestamp description.
3584 $time = strtotime( $str, 0 );
3585 if ( $time === false ) { // Unknown format. Return it as-is in case.
3587 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3588 // $time is relative to 0 so it's a duration length.
3589 return $this->formatDuration( $time );
3590 } else { // It's an absolute timestamp.
3591 if ( $time === 0 ) {
3592 // wfTimestamp() handles 0 as current time instead of epoch.
3593 return $this->timeanddate( '19700101000000' );
3595 return $this->timeanddate( $time );
3601 * languages like Chinese need to be segmented in order for the diff
3604 * @param $text String
3607 public function segmentForDiff( $text ) {
3612 * and unsegment to show the result
3614 * @param $text String
3617 public function unsegmentForDiff( $text ) {
3622 * Return the LanguageConverter used in the Language
3625 * @return LanguageConverter
3627 public function getConverter() {
3628 return $this->mConverter
;
3632 * convert text to all supported variants
3634 * @param $text string
3637 public function autoConvertToAllVariants( $text ) {
3638 return $this->mConverter
->autoConvertToAllVariants( $text );
3642 * convert text to different variants of a language.
3644 * @param $text string
3647 public function convert( $text ) {
3648 return $this->mConverter
->convert( $text );
3652 * Convert a Title object to a string in the preferred variant
3654 * @param $title Title
3657 public function convertTitle( $title ) {
3658 return $this->mConverter
->convertTitle( $title );
3662 * Convert a namespace index to a string in the preferred variant
3667 public function convertNamespace( $ns ) {
3668 return $this->mConverter
->convertNamespace( $ns );
3672 * Check if this is a language with variants
3676 public function hasVariants() {
3677 return count( $this->getVariants() ) > 1;
3681 * Check if the language has the specific variant
3684 * @param $variant string
3687 public function hasVariant( $variant ) {
3688 return (bool)$this->mConverter
->validateVariant( $variant );
3692 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3694 * @param $text string
3697 public function armourMath( $text ) {
3698 return $this->mConverter
->armourMath( $text );
3702 * Perform output conversion on a string, and encode for safe HTML output.
3703 * @param $text String text to be converted
3704 * @param $isTitle Bool whether this conversion is for the article title
3706 * @todo this should get integrated somewhere sane
3708 public function convertHtml( $text, $isTitle = false ) {
3709 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3713 * @param $key string
3716 public function convertCategoryKey( $key ) {
3717 return $this->mConverter
->convertCategoryKey( $key );
3721 * Get the list of variants supported by this language
3722 * see sample implementation in LanguageZh.php
3724 * @return array an array of language codes
3726 public function getVariants() {
3727 return $this->mConverter
->getVariants();
3733 public function getPreferredVariant() {
3734 return $this->mConverter
->getPreferredVariant();
3740 public function getDefaultVariant() {
3741 return $this->mConverter
->getDefaultVariant();
3747 public function getURLVariant() {
3748 return $this->mConverter
->getURLVariant();
3752 * If a language supports multiple variants, it is
3753 * possible that non-existing link in one variant
3754 * actually exists in another variant. this function
3755 * tries to find it. See e.g. LanguageZh.php
3757 * @param $link String: the name of the link
3758 * @param $nt Mixed: the title object of the link
3759 * @param $ignoreOtherCond Boolean: to disable other conditions when
3760 * we need to transclude a template or update a category's link
3761 * @return null the input parameters may be modified upon return
3763 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3764 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3768 * If a language supports multiple variants, converts text
3769 * into an array of all possible variants of the text:
3770 * 'variant' => text in that variant
3772 * @deprecated since 1.17 Use autoConvertToAllVariants()
3774 * @param $text string
3778 public function convertLinkToAllVariants( $text ) {
3779 return $this->mConverter
->convertLinkToAllVariants( $text );
3783 * returns language specific options used by User::getPageRenderHash()
3784 * for example, the preferred language variant
3788 function getExtraHashOptions() {
3789 return $this->mConverter
->getExtraHashOptions();
3793 * For languages that support multiple variants, the title of an
3794 * article may be displayed differently in different variants. this
3795 * function returns the apporiate title defined in the body of the article.
3799 public function getParsedTitle() {
3800 return $this->mConverter
->getParsedTitle();
3804 * Prepare external link text for conversion. When the text is
3805 * a URL, it shouldn't be converted, and it'll be wrapped in
3806 * the "raw" tag (-{R| }-) to prevent conversion.
3808 * This function is called "markNoConversion" for historical
3811 * @param $text String: text to be used for external link
3812 * @param $noParse bool: wrap it without confirming it's a real URL first
3813 * @return string the tagged text
3815 public function markNoConversion( $text, $noParse = false ) {
3816 // Excluding protocal-relative URLs may avoid many false positives.
3817 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3818 return $this->mConverter
->markNoConversion( $text );
3825 * A regular expression to match legal word-trailing characters
3826 * which should be merged onto a link of the form [[foo]]bar.
3830 public function linkTrail() {
3831 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3837 function getLangObj() {
3842 * Get the RFC 3066 code for this language object
3844 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3845 * htmlspecialchars() or similar
3849 public function getCode() {
3850 return $this->mCode
;
3854 * Get the code in Bcp47 format which we can use
3855 * inside of html lang="" tags.
3857 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3858 * htmlspecialchars() or similar.
3863 public function getHtmlCode() {
3864 if ( is_null( $this->mHtmlCode
) ) {
3865 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3867 return $this->mHtmlCode
;
3871 * @param $code string
3873 public function setCode( $code ) {
3874 $this->mCode
= $code;
3875 // Ensure we don't leave an incorrect html code lying around
3876 $this->mHtmlCode
= null;
3880 * Get the name of a file for a certain language code
3881 * @param $prefix string Prepend this to the filename
3882 * @param $code string Language code
3883 * @param $suffix string Append this to the filename
3884 * @throws MWException
3885 * @return string $prefix . $mangledCode . $suffix
3887 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3888 // Protect against path traversal
3889 if ( !Language
::isValidCode( $code )
3890 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3892 throw new MWException( "Invalid language code \"$code\"" );
3895 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3899 * Get the language code from a file name. Inverse of getFileName()
3900 * @param $filename string $prefix . $languageCode . $suffix
3901 * @param $prefix string Prefix before the language code
3902 * @param $suffix string Suffix after the language code
3903 * @return string Language code, or false if $prefix or $suffix isn't found
3905 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3907 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3908 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3909 if ( !count( $m ) ) {
3912 return str_replace( '_', '-', strtolower( $m[1] ) );
3916 * @param $code string
3919 public static function getMessagesFileName( $code ) {
3921 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3922 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3927 * @param $code string
3930 public static function getClassFileName( $code ) {
3932 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3936 * Get the first fallback for a given language.
3938 * @param $code string
3940 * @return bool|string
3942 public static function getFallbackFor( $code ) {
3943 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3946 $fallbacks = self
::getFallbacksFor( $code );
3947 $first = array_shift( $fallbacks );
3953 * Get the ordered list of fallback languages.
3956 * @param $code string Language code
3959 public static function getFallbacksFor( $code ) {
3960 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3963 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3964 $v = array_map( 'trim', explode( ',', $v ) );
3965 if ( $v[count( $v ) - 1] !== 'en' ) {
3973 * Get all messages for a given language
3974 * WARNING: this may take a long time. If you just need all message *keys*
3975 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3977 * @param $code string
3981 public static function getMessagesFor( $code ) {
3982 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3986 * Get a message for a given language
3988 * @param $key string
3989 * @param $code string
3993 public static function getMessageFor( $key, $code ) {
3994 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3998 * Get all message keys for a given language. This is a faster alternative to
3999 * array_keys( Language::getMessagesFor( $code ) )
4002 * @param $code string Language code
4003 * @return array of message keys (strings)
4005 public static function getMessageKeysFor( $code ) {
4006 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4013 function fixVariableInNamespace( $talk ) {
4014 if ( strpos( $talk, '$1' ) === false ) {
4018 global $wgMetaNamespace;
4019 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4021 # Allow grammar transformations
4022 # Allowing full message-style parsing would make simple requests
4023 # such as action=raw much more expensive than they need to be.
4024 # This will hopefully cover most cases.
4025 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4026 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4027 return str_replace( ' ', '_', $talk );
4034 function replaceGrammarInNamespace( $m ) {
4035 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4039 * @throws MWException
4042 static function getCaseMaps() {
4043 static $wikiUpperChars, $wikiLowerChars;
4044 if ( isset( $wikiUpperChars ) ) {
4045 return array( $wikiUpperChars, $wikiLowerChars );
4048 wfProfileIn( __METHOD__
);
4049 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4050 if ( $arr === false ) {
4051 throw new MWException(
4052 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4054 $wikiUpperChars = $arr['wikiUpperChars'];
4055 $wikiLowerChars = $arr['wikiLowerChars'];
4056 wfProfileOut( __METHOD__
);
4057 return array( $wikiUpperChars, $wikiLowerChars );
4061 * Decode an expiry (block, protection, etc) which has come from the DB
4063 * @todo FIXME: why are we returnings DBMS-dependent strings???
4065 * @param $expiry String: Database expiry String
4066 * @param $format Bool|Int true to process using language functions, or TS_ constant
4067 * to return the expiry in a given timestamp
4071 public function formatExpiry( $expiry, $format = true ) {
4072 static $infinity, $infinityMsg;
4073 if ( $infinity === null ) {
4074 $infinityMsg = wfMessage( 'infiniteblock' );
4075 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4078 if ( $expiry == '' ||
$expiry == $infinity ) {
4079 return $format === true
4083 return $format === true
4084 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4085 : wfTimestamp( $format, $expiry );
4091 * @param $seconds int|float
4092 * @param $format Array Optional
4093 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4094 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4095 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4096 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4099 function formatTimePeriod( $seconds, $format = array() ) {
4100 if ( !is_array( $format ) ) {
4101 $format = array( 'avoid' => $format ); // For backwards compatibility
4103 if ( !isset( $format['avoid'] ) ) {
4104 $format['avoid'] = false;
4106 if ( !isset( $format['noabbrevs' ] ) ) {
4107 $format['noabbrevs'] = false;
4109 $secondsMsg = wfMessage(
4110 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4111 $minutesMsg = wfMessage(
4112 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4113 $hoursMsg = wfMessage(
4114 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4115 $daysMsg = wfMessage(
4116 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4118 if ( round( $seconds * 10 ) < 100 ) {
4119 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4120 $s = $secondsMsg->params( $s )->text();
4121 } elseif ( round( $seconds ) < 60 ) {
4122 $s = $this->formatNum( round( $seconds ) );
4123 $s = $secondsMsg->params( $s )->text();
4124 } elseif ( round( $seconds ) < 3600 ) {
4125 $minutes = floor( $seconds / 60 );
4126 $secondsPart = round( fmod( $seconds, 60 ) );
4127 if ( $secondsPart == 60 ) {
4131 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4133 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4134 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4135 $hours = floor( $seconds / 3600 );
4136 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4137 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4138 if ( $secondsPart == 60 ) {
4142 if ( $minutes == 60 ) {
4146 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4148 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4149 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4150 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4153 $days = floor( $seconds / 86400 );
4154 if ( $format['avoid'] === 'avoidminutes' ) {
4155 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4156 if ( $hours == 24 ) {
4160 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4162 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4163 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4164 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4165 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4166 if ( $minutes == 60 ) {
4170 if ( $hours == 24 ) {
4174 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4176 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4178 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4180 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4182 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4189 * Format a bitrate for output, using an appropriate
4190 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4192 * This use base 1000. For base 1024 use formatSize(), for another base
4193 * see formatComputingNumbers()
4198 function formatBitrate( $bps ) {
4199 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4203 * @param $size int Size of the unit
4204 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4205 * @param $messageKey string Message key to be uesd
4208 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4210 return str_replace( '$1', $this->formatNum( $size ),
4211 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4214 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4217 $maxIndex = count( $sizes ) - 1;
4218 while ( $size >= $boundary && $index < $maxIndex ) {
4223 // For small sizes no decimal places necessary
4226 // For MB and bigger two decimal places are smarter
4229 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4231 $size = round( $size, $round );
4232 $text = $this->getMessageFromDB( $msg );
4233 return str_replace( '$1', $this->formatNum( $size ), $text );
4237 * Format a size in bytes for output, using an appropriate
4238 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4240 * This method use base 1024. For base 1000 use formatBitrate(), for
4241 * another base see formatComputingNumbers()
4243 * @param $size int Size to format
4244 * @return string Plain text (not HTML)
4246 function formatSize( $size ) {
4247 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4251 * Make a list item, used by various special pages
4253 * @param $page String Page link
4254 * @param $details String Text between brackets
4255 * @param $oppositedm Boolean Add the direction mark opposite to your
4256 * language, to display text properly
4259 function specialList( $page, $details, $oppositedm = true ) {
4260 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4261 $this->getDirMark();
4262 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4263 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4264 return $page . $details;
4268 * Generate (prev x| next x) (20|50|100...) type links for paging
4270 * @param $title Title object to link
4271 * @param $offset Integer offset parameter
4272 * @param $limit Integer limit parameter
4273 * @param $query array|String optional URL query parameter string
4274 * @param $atend Bool optional param for specified if this is the last page
4277 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4278 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4280 # Make 'previous' link
4281 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4282 if ( $offset > 0 ) {
4283 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4284 $query, $prev, 'prevn-title', 'mw-prevlink' );
4286 $plink = htmlspecialchars( $prev );
4290 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4292 $nlink = htmlspecialchars( $next );
4294 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4295 $query, $next, 'prevn-title', 'mw-nextlink' );
4298 # Make links to set number of items per page
4299 $numLinks = array();
4300 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4301 $numLinks[] = $this->numLink( $title, $offset, $num,
4302 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4305 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4306 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4310 * Helper function for viewPrevNext() that generates links
4312 * @param $title Title object to link
4313 * @param $offset Integer offset parameter
4314 * @param $limit Integer limit parameter
4315 * @param $query Array extra query parameters
4316 * @param $link String text to use for the link; will be escaped
4317 * @param $tooltipMsg String name of the message to use as tooltip
4318 * @param $class String value of the "class" attribute of the link
4319 * @return String HTML fragment
4321 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4322 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4323 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4324 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4325 'title' => $tooltip, 'class' => $class ), $link );
4329 * Get the conversion rule title, if any.
4333 public function getConvRuleTitle() {
4334 return $this->mConverter
->getConvRuleTitle();
4338 * Get the compiled plural rules for the language
4340 * @return array Associative array with plural form, and plural rule as key-value pairs
4342 public function getCompiledPluralRules() {
4343 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4344 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4345 if ( !$pluralRules ) {
4346 foreach ( $fallbacks as $fallbackCode ) {
4347 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4348 if ( $pluralRules ) {
4353 return $pluralRules;
4357 * Get the plural rules for the language
4359 * @return array Associative array with plural form number and plural rule as key-value pairs
4361 public function getPluralRules() {
4362 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4363 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4364 if ( !$pluralRules ) {
4365 foreach ( $fallbacks as $fallbackCode ) {
4366 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4367 if ( $pluralRules ) {
4372 return $pluralRules;
4376 * Get the plural rule types for the language
4378 * @return array Associative array with plural form number and plural rule type as key-value pairs
4380 public function getPluralRuleTypes() {
4381 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4382 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4383 if ( !$pluralRuleTypes ) {
4384 foreach ( $fallbacks as $fallbackCode ) {
4385 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4386 if ( $pluralRuleTypes ) {
4391 return $pluralRuleTypes;
4395 * Find the index number of the plural rule appropriate for the given number
4396 * @return int The index number of the plural rule
4398 public function getPluralRuleIndexNumber( $number ) {
4399 $pluralRules = $this->getCompiledPluralRules();
4400 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4405 * Find the plural rule type appropriate for the given number
4406 * For example, if the language is set to Arabic, getPluralType(5) should
4409 * @return string The name of the plural rule type, e.g. one, two, few, many
4411 public function getPluralRuleType( $number ) {
4412 $index = $this->getPluralRuleIndexNumber( $number );
4413 $pluralRuleTypes = $this->getPluralRuleTypes();
4414 if ( isset( $pluralRuleTypes[$index] ) ) {
4415 return $pluralRuleTypes[$index];