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 dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1022 * the 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. Note that the format characters crUeIOPTZ will assume
1069 * $ts is UTC if $zone is not given.
1071 * @param $format String
1072 * @param $ts String: 14-character timestamp
1075 * @param $zone DateTimeZone: Timezone of $ts
1076 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1080 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1085 $dateTimeObj = false;
1093 for ( $p = 0; $p < strlen( $format ); $p++
) {
1095 $code = $format[$p];
1096 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1097 $code .= $format[++
$p];
1100 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1101 $code .= $format[++
$p];
1112 $rawToggle = !$rawToggle;
1121 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1124 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1125 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1128 $num = substr( $ts, 6, 2 );
1131 if ( !$dateTimeObj ) {
1132 $dateTimeObj = DateTime
::createFromFormat(
1133 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1136 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1139 $num = intval( substr( $ts, 6, 2 ) );
1143 $iranian = self
::tsToIranian( $ts );
1149 $hijri = self
::tsToHijri( $ts );
1155 $hebrew = self
::tsToHebrew( $ts );
1160 if ( !$dateTimeObj ) {
1161 $dateTimeObj = DateTime
::createFromFormat(
1162 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1165 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1168 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1172 $iranian = self
::tsToIranian( $ts );
1174 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1178 $hijri = self
::tsToHijri( $ts );
1180 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1184 $hebrew = self
::tsToHebrew( $ts );
1186 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1189 $num = substr( $ts, 4, 2 );
1192 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1195 $num = intval( substr( $ts, 4, 2 ) );
1199 $iranian = self
::tsToIranian( $ts );
1205 $hijri = self
::tsToHijri ( $ts );
1211 $hebrew = self
::tsToHebrew( $ts );
1217 $hebrew = self
::tsToHebrew( $ts );
1222 $num = substr( $ts, 0, 4 );
1226 $iranian = self
::tsToIranian( $ts );
1232 $hijri = self
::tsToHijri( $ts );
1238 $hebrew = self
::tsToHebrew( $ts );
1244 $thai = self
::tsToYear( $ts, 'thai' );
1250 $minguo = self
::tsToYear( $ts, 'minguo' );
1256 $tenno = self
::tsToYear( $ts, 'tenno' );
1261 $num = substr( $ts, 2, 2 );
1265 $iranian = self
::tsToIranian( $ts );
1267 $num = substr( $iranian[0], -2 );
1270 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1273 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1276 $h = substr( $ts, 8, 2 );
1277 $num = $h %
12 ?
$h %
12 : 12;
1280 $num = intval( substr( $ts, 8, 2 ) );
1283 $h = substr( $ts, 8, 2 );
1284 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1287 $num = substr( $ts, 8, 2 );
1290 $num = substr( $ts, 10, 2 );
1293 $num = substr( $ts, 12, 2 );
1301 // Pass through string from $dateTimeObj->format()
1302 if ( !$dateTimeObj ) {
1303 $dateTimeObj = DateTime
::createFromFormat(
1304 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1307 $s .= $dateTimeObj->format( $code );
1319 // Pass through number from $dateTimeObj->format()
1320 if ( !$dateTimeObj ) {
1321 $dateTimeObj = DateTime
::createFromFormat(
1322 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1325 $num = $dateTimeObj->format( $code );
1328 # Backslash escaping
1329 if ( $p < strlen( $format ) - 1 ) {
1330 $s .= $format[++
$p];
1337 if ( $p < strlen( $format ) - 1 ) {
1338 $endQuote = strpos( $format, '"', $p +
1 );
1339 if ( $endQuote === false ) {
1340 # No terminating quote, assume literal "
1343 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1347 # Quote at end of string, assume literal "
1354 if ( $num !== false ) {
1355 if ( $rawToggle ||
$raw ) {
1358 } elseif ( $roman ) {
1359 $s .= Language
::romanNumeral( $num );
1361 } elseif ( $hebrewNum ) {
1362 $s .= self
::hebrewNumeral( $num );
1365 $s .= $this->formatNum( $num, true );
1372 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1373 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1376 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1377 * Gregorian dates to Iranian dates. Originally written in C, it
1378 * is released under the terms of GNU Lesser General Public
1379 * License. Conversion to PHP was performed by Niklas Laxström.
1381 * Link: http://www.farsiweb.info/jalali/jalali.c
1387 private static function tsToIranian( $ts ) {
1388 $gy = substr( $ts, 0, 4 ) -1600;
1389 $gm = substr( $ts, 4, 2 ) -1;
1390 $gd = substr( $ts, 6, 2 ) -1;
1392 # Days passed from the beginning (including leap years)
1394 +
floor( ( $gy +
3 ) / 4 )
1395 - floor( ( $gy +
99 ) / 100 )
1396 +
floor( ( $gy +
399 ) / 400 );
1398 // Add days of the past months of this year
1399 for ( $i = 0; $i < $gm; $i++
) {
1400 $gDayNo +
= self
::$GREG_DAYS[$i];
1404 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1408 // Days passed in current month
1409 $gDayNo +
= (int)$gd;
1411 $jDayNo = $gDayNo - 79;
1413 $jNp = floor( $jDayNo / 12053 );
1416 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1419 if ( $jDayNo >= 366 ) {
1420 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1421 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1424 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1425 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1431 return array( $jy, $jm, $jd );
1435 * Converting Gregorian dates to Hijri dates.
1437 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1439 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1445 private static function tsToHijri( $ts ) {
1446 $year = substr( $ts, 0, 4 );
1447 $month = substr( $ts, 4, 2 );
1448 $day = substr( $ts, 6, 2 );
1456 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1457 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1460 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1461 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1462 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1465 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1466 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1469 $zl = $zjd -1948440 +
10632;
1470 $zn = (int)( ( $zl - 1 ) / 10631 );
1471 $zl = $zl - 10631 * $zn +
354;
1472 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1473 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1474 $zm = (int)( ( 24 * $zl ) / 709 );
1475 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1476 $zy = 30 * $zn +
$zj - 30;
1478 return array( $zy, $zm, $zd );
1482 * Converting Gregorian dates to Hebrew dates.
1484 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1485 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1486 * to translate the relevant functions into PHP and release them under
1489 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1490 * and Adar II is 14. In a non-leap year, Adar is 6.
1496 private static function tsToHebrew( $ts ) {
1498 $year = substr( $ts, 0, 4 );
1499 $month = substr( $ts, 4, 2 );
1500 $day = substr( $ts, 6, 2 );
1502 # Calculate Hebrew year
1503 $hebrewYear = $year +
3760;
1505 # Month number when September = 1, August = 12
1507 if ( $month > 12 ) {
1514 # Calculate day of year from 1 September
1516 for ( $i = 1; $i < $month; $i++
) {
1520 # Check if the year is leap
1521 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1524 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1531 # Calculate the start of the Hebrew year
1532 $start = self
::hebrewYearStart( $hebrewYear );
1534 # Calculate next year's start
1535 if ( $dayOfYear <= $start ) {
1536 # Day is before the start of the year - it is the previous year
1538 $nextStart = $start;
1542 # Add days since previous year's 1 September
1544 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1548 # Start of the new (previous) year
1549 $start = self
::hebrewYearStart( $hebrewYear );
1552 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1555 # Calculate Hebrew day of year
1556 $hebrewDayOfYear = $dayOfYear - $start;
1558 # Difference between year's days
1559 $diff = $nextStart - $start;
1560 # Add 12 (or 13 for leap years) days to ignore the difference between
1561 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1562 # difference is only about the year type
1563 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1569 # Check the year pattern, and is leap year
1570 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1571 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1572 # and non-leap years
1573 $yearPattern = $diff %
30;
1574 # Check if leap year
1575 $isLeap = $diff >= 30;
1577 # Calculate day in the month from number of day in the Hebrew year
1578 # Don't check Adar - if the day is not in Adar, we will stop before;
1579 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1580 $hebrewDay = $hebrewDayOfYear;
1583 while ( $hebrewMonth <= 12 ) {
1584 # Calculate days in this month
1585 if ( $isLeap && $hebrewMonth == 6 ) {
1586 # Adar in a leap year
1588 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1590 if ( $hebrewDay <= $days ) {
1594 # Subtract the days of Adar I
1595 $hebrewDay -= $days;
1598 if ( $hebrewDay <= $days ) {
1604 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1605 # Cheshvan in a complete year (otherwise as the rule below)
1607 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1608 # Kislev in an incomplete year (otherwise as the rule below)
1611 # Odd months have 30 days, even have 29
1612 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1614 if ( $hebrewDay <= $days ) {
1615 # In the current month
1618 # Subtract the days of the current month
1619 $hebrewDay -= $days;
1620 # Try in the next month
1625 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1629 * This calculates the Hebrew year start, as days since 1 September.
1630 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1631 * Used for Hebrew date.
1637 private static function hebrewYearStart( $year ) {
1638 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1639 $b = intval( ( $year - 1 ) %
4 );
1640 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1644 $Mar = intval( $m );
1650 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1651 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1653 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1655 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1659 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1664 * Algorithm to convert Gregorian dates to Thai solar dates,
1665 * Minguo dates or Minguo dates.
1667 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1668 * http://en.wikipedia.org/wiki/Minguo_calendar
1669 * http://en.wikipedia.org/wiki/Japanese_era_name
1671 * @param $ts String: 14-character timestamp
1672 * @param $cName String: calender name
1673 * @return Array: converted year, month, day
1675 private static function tsToYear( $ts, $cName ) {
1676 $gy = substr( $ts, 0, 4 );
1677 $gm = substr( $ts, 4, 2 );
1678 $gd = substr( $ts, 6, 2 );
1680 if ( !strcmp( $cName, 'thai' ) ) {
1682 # Add 543 years to the Gregorian calendar
1683 # Months and days are identical
1684 $gy_offset = $gy +
543;
1685 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1687 # Deduct 1911 years from the Gregorian calendar
1688 # Months and days are identical
1689 $gy_offset = $gy - 1911;
1690 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1691 # Nengō dates up to Meiji period
1692 # Deduct years from the Gregorian calendar
1693 # depending on the nengo periods
1694 # Months and days are identical
1695 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1697 $gy_gannen = $gy - 1868 +
1;
1698 $gy_offset = $gy_gannen;
1699 if ( $gy_gannen == 1 ) {
1702 $gy_offset = '明治' . $gy_offset;
1704 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1705 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1706 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1707 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1708 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1712 $gy_gannen = $gy - 1912 +
1;
1713 $gy_offset = $gy_gannen;
1714 if ( $gy_gannen == 1 ) {
1717 $gy_offset = '大正' . $gy_offset;
1719 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1720 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1721 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1725 $gy_gannen = $gy - 1926 +
1;
1726 $gy_offset = $gy_gannen;
1727 if ( $gy_gannen == 1 ) {
1730 $gy_offset = '昭和' . $gy_offset;
1733 $gy_gannen = $gy - 1989 +
1;
1734 $gy_offset = $gy_gannen;
1735 if ( $gy_gannen == 1 ) {
1738 $gy_offset = '平成' . $gy_offset;
1744 return array( $gy_offset, $gm, $gd );
1748 * Roman number formatting up to 10000
1754 static function romanNumeral( $num ) {
1755 static $table = array(
1756 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1757 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1758 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1759 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1762 $num = intval( $num );
1763 if ( $num > 10000 ||
$num <= 0 ) {
1768 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1769 if ( $num >= $pow10 ) {
1770 $s .= $table[$i][(int)floor( $num / $pow10 )];
1772 $num = $num %
$pow10;
1778 * Hebrew Gematria number formatting up to 9999
1784 static function hebrewNumeral( $num ) {
1785 static $table = array(
1786 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1787 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1788 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1789 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1792 $num = intval( $num );
1793 if ( $num > 9999 ||
$num <= 0 ) {
1798 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1799 if ( $num >= $pow10 ) {
1800 if ( $num == 15 ||
$num == 16 ) {
1801 $s .= $table[0][9] . $table[0][$num - 9];
1804 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1805 if ( $pow10 == 1000 ) {
1810 $num = $num %
$pow10;
1812 if ( strlen( $s ) == 2 ) {
1815 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1816 $str .= substr( $s, strlen( $s ) - 2, 2 );
1818 $start = substr( $str, 0, strlen( $str ) - 2 );
1819 $end = substr( $str, strlen( $str ) - 2 );
1822 $str = $start . 'ך';
1825 $str = $start . 'ם';
1828 $str = $start . 'ן';
1831 $str = $start . 'ף';
1834 $str = $start . 'ץ';
1841 * Used by date() and time() to adjust the time output.
1843 * @param $ts Int the time in date('YmdHis') format
1844 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1845 * get user timecorrection setting)
1848 function userAdjust( $ts, $tz = false ) {
1849 global $wgUser, $wgLocalTZoffset;
1851 if ( $tz === false ) {
1852 $tz = $wgUser->getOption( 'timecorrection' );
1855 $data = explode( '|', $tz, 3 );
1857 if ( $data[0] == 'ZoneInfo' ) {
1858 wfSuppressWarnings();
1859 $userTZ = timezone_open( $data[2] );
1860 wfRestoreWarnings();
1861 if ( $userTZ !== false ) {
1862 $date = date_create( $ts, timezone_open( 'UTC' ) );
1863 date_timezone_set( $date, $userTZ );
1864 $date = date_format( $date, 'YmdHis' );
1867 # Unrecognized timezone, default to 'Offset' with the stored offset.
1868 $data[0] = 'Offset';
1872 if ( $data[0] == 'System' ||
$tz == '' ) {
1873 # Global offset in minutes.
1874 if ( isset( $wgLocalTZoffset ) ) {
1875 $minDiff = $wgLocalTZoffset;
1877 } elseif ( $data[0] == 'Offset' ) {
1878 $minDiff = intval( $data[1] );
1880 $data = explode( ':', $tz );
1881 if ( count( $data ) == 2 ) {
1882 $data[0] = intval( $data[0] );
1883 $data[1] = intval( $data[1] );
1884 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1885 if ( $data[0] < 0 ) {
1886 $minDiff = -$minDiff;
1889 $minDiff = intval( $data[0] ) * 60;
1893 # No difference ? Return time unchanged
1894 if ( 0 == $minDiff ) {
1898 wfSuppressWarnings(); // E_STRICT system time bitching
1899 # Generate an adjusted date; take advantage of the fact that mktime
1900 # will normalize out-of-range values so we don't have to split $minDiff
1901 # into hours and minutes.
1903 (int)substr( $ts, 8, 2 ) ), # Hours
1904 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1905 (int)substr( $ts, 12, 2 ), # Seconds
1906 (int)substr( $ts, 4, 2 ), # Month
1907 (int)substr( $ts, 6, 2 ), # Day
1908 (int)substr( $ts, 0, 4 ) ); # Year
1910 $date = date( 'YmdHis', $t );
1911 wfRestoreWarnings();
1917 * This is meant to be used by time(), date(), and timeanddate() to get
1918 * the date preference they're supposed to use, it should be used in
1922 * function timeanddate([...], $format = true) {
1923 * $datePreference = $this->dateFormat($format);
1928 * @param $usePrefs Mixed: if true, the user's preference is used
1929 * if false, the site/language default is used
1930 * if int/string, assumed to be a format.
1933 function dateFormat( $usePrefs = true ) {
1936 if ( is_bool( $usePrefs ) ) {
1938 $datePreference = $wgUser->getDatePreference();
1940 $datePreference = (string)User
::getDefaultOption( 'date' );
1943 $datePreference = (string)$usePrefs;
1947 if ( $datePreference == '' ) {
1951 return $datePreference;
1955 * Get a format string for a given type and preference
1956 * @param $type string May be date, time or both
1957 * @param $pref string The format name as it appears in Messages*.php
1961 function getDateFormatString( $type, $pref ) {
1962 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1963 if ( $pref == 'default' ) {
1964 $pref = $this->getDefaultDateFormat();
1965 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1967 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1968 if ( is_null( $df ) ) {
1969 $pref = $this->getDefaultDateFormat();
1970 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1973 $this->dateFormatStrings
[$type][$pref] = $df;
1975 return $this->dateFormatStrings
[$type][$pref];
1979 * @param $ts Mixed: the time format which needs to be turned into a
1980 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1981 * @param $adj Bool: whether to adjust the time output according to the
1982 * user configured offset ($timecorrection)
1983 * @param $format Mixed: true to use user's date format preference
1984 * @param $timecorrection String|bool the time offset as returned by
1985 * validateTimeZone() in Special:Preferences
1988 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1989 $ts = wfTimestamp( TS_MW
, $ts );
1991 $ts = $this->userAdjust( $ts, $timecorrection );
1993 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1994 return $this->sprintfDate( $df, $ts );
1998 * @param $ts Mixed: the time format which needs to be turned into a
1999 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2000 * @param $adj Bool: whether to adjust the time output according to the
2001 * user configured offset ($timecorrection)
2002 * @param $format Mixed: true to use user's date format preference
2003 * @param $timecorrection String|bool the time offset as returned by
2004 * validateTimeZone() in Special:Preferences
2007 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2008 $ts = wfTimestamp( TS_MW
, $ts );
2010 $ts = $this->userAdjust( $ts, $timecorrection );
2012 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2013 return $this->sprintfDate( $df, $ts );
2017 * @param $ts Mixed: the time format which needs to be turned into a
2018 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2019 * @param $adj Bool: whether to adjust the time output according to the
2020 * user configured offset ($timecorrection)
2021 * @param $format Mixed: what format to return, if it's false output the
2022 * default one (default true)
2023 * @param $timecorrection String|bool the time offset as returned by
2024 * validateTimeZone() in Special:Preferences
2027 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2028 $ts = wfTimestamp( TS_MW
, $ts );
2030 $ts = $this->userAdjust( $ts, $timecorrection );
2032 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2033 return $this->sprintfDate( $df, $ts );
2037 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2041 * @param integer $seconds The amount of seconds.
2042 * @param array $chosenIntervals The intervals to enable.
2046 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2047 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2049 $segments = array();
2051 foreach ( $intervals as $intervalName => $intervalValue ) {
2052 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2053 $segments[] = $message->inLanguage( $this )->escaped();
2056 return $this->listToText( $segments );
2060 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2061 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2065 * @param integer $seconds The amount of seconds.
2066 * @param array $chosenIntervals The intervals to enable.
2070 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2071 if ( empty( $chosenIntervals ) ) {
2072 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2075 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2076 $sortedNames = array_keys( $intervals );
2077 $smallestInterval = array_pop( $sortedNames );
2079 $segments = array();
2081 foreach ( $intervals as $name => $length ) {
2082 $value = floor( $seconds / $length );
2084 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2085 $seconds -= $value * $length;
2086 $segments[$name] = $value;
2094 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2096 * @param $type String: can be 'date', 'time' or 'both'
2097 * @param $ts Mixed: the time format which needs to be turned into a
2098 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2099 * @param $user User object used to get preferences for timezone and format
2100 * @param $options Array, can contain the following keys:
2101 * - 'timecorrection': time correction, can have the following values:
2102 * - true: use user's preference
2103 * - false: don't use time correction
2104 * - integer: value of time correction in minutes
2105 * - 'format': format to use, can have the following values:
2106 * - true: use user's preference
2107 * - false: use default preference
2108 * - string: format to use
2112 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2113 $ts = wfTimestamp( TS_MW
, $ts );
2114 $options +
= array( 'timecorrection' => true, 'format' => true );
2115 if ( $options['timecorrection'] !== false ) {
2116 if ( $options['timecorrection'] === true ) {
2117 $offset = $user->getOption( 'timecorrection' );
2119 $offset = $options['timecorrection'];
2121 $ts = $this->userAdjust( $ts, $offset );
2123 if ( $options['format'] === true ) {
2124 $format = $user->getDatePreference();
2126 $format = $options['format'];
2128 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2129 return $this->sprintfDate( $df, $ts );
2133 * Get the formatted date for the given timestamp and formatted for
2136 * @param $ts Mixed: the time format which needs to be turned into a
2137 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2138 * @param $user User object used to get preferences for timezone and format
2139 * @param $options Array, can contain the following keys:
2140 * - 'timecorrection': time correction, can have the following values:
2141 * - true: use user's preference
2142 * - false: don't use time correction
2143 * - integer: value of time correction in minutes
2144 * - 'format': format to use, can have the following values:
2145 * - true: use user's preference
2146 * - false: use default preference
2147 * - string: format to use
2151 public function userDate( $ts, User
$user, array $options = array() ) {
2152 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2156 * Get the formatted time for the given timestamp and formatted for
2159 * @param $ts Mixed: the time format which needs to be turned into a
2160 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2161 * @param $user User object used to get preferences for timezone and format
2162 * @param $options Array, can contain the following keys:
2163 * - 'timecorrection': time correction, can have the following values:
2164 * - true: use user's preference
2165 * - false: don't use time correction
2166 * - integer: value of time correction in minutes
2167 * - 'format': format to use, can have the following values:
2168 * - true: use user's preference
2169 * - false: use default preference
2170 * - string: format to use
2174 public function userTime( $ts, User
$user, array $options = array() ) {
2175 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2179 * Get the formatted date and time for the given timestamp and formatted for
2182 * @param $ts Mixed: the time format which needs to be turned into a
2183 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2184 * @param $user User object used to get preferences for timezone and format
2185 * @param $options Array, can contain the following keys:
2186 * - 'timecorrection': time correction, can have the following values:
2187 * - true: use user's preference
2188 * - false: don't use time correction
2189 * - integer: value of time correction in minutes
2190 * - 'format': format to use, can have the following values:
2191 * - true: use user's preference
2192 * - false: use default preference
2193 * - string: format to use
2197 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2198 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2202 * @param $key string
2203 * @return array|null
2205 function getMessage( $key ) {
2206 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2212 function getAllMessages() {
2213 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2222 function iconv( $in, $out, $string ) {
2223 # This is a wrapper for iconv in all languages except esperanto,
2224 # which does some nasty x-conversions beforehand
2226 # Even with //IGNORE iconv can whine about illegal characters in
2227 # *input* string. We just ignore those too.
2228 # REF: http://bugs.php.net/bug.php?id=37166
2229 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2230 wfSuppressWarnings();
2231 $text = iconv( $in, $out . '//IGNORE', $string );
2232 wfRestoreWarnings();
2236 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2239 * @param $matches array
2240 * @return mixed|string
2242 function ucwordbreaksCallbackAscii( $matches ) {
2243 return $this->ucfirst( $matches[1] );
2247 * @param $matches array
2250 function ucwordbreaksCallbackMB( $matches ) {
2251 return mb_strtoupper( $matches[0] );
2255 * @param $matches array
2258 function ucCallback( $matches ) {
2259 list( $wikiUpperChars ) = self
::getCaseMaps();
2260 return strtr( $matches[1], $wikiUpperChars );
2264 * @param $matches array
2267 function lcCallback( $matches ) {
2268 list( , $wikiLowerChars ) = self
::getCaseMaps();
2269 return strtr( $matches[1], $wikiLowerChars );
2273 * @param $matches array
2276 function ucwordsCallbackMB( $matches ) {
2277 return mb_strtoupper( $matches[0] );
2281 * @param $matches array
2284 function ucwordsCallbackWiki( $matches ) {
2285 list( $wikiUpperChars ) = self
::getCaseMaps();
2286 return strtr( $matches[0], $wikiUpperChars );
2290 * Make a string's first character uppercase
2292 * @param $str string
2296 function ucfirst( $str ) {
2298 if ( $o < 96 ) { // if already uppercase...
2300 } elseif ( $o < 128 ) {
2301 return ucfirst( $str ); // use PHP's ucfirst()
2303 // fall back to more complex logic in case of multibyte strings
2304 return $this->uc( $str, true );
2309 * Convert a string to uppercase
2311 * @param $str string
2312 * @param $first bool
2316 function uc( $str, $first = false ) {
2317 if ( function_exists( 'mb_strtoupper' ) ) {
2319 if ( $this->isMultibyte( $str ) ) {
2320 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2322 return ucfirst( $str );
2325 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2328 if ( $this->isMultibyte( $str ) ) {
2329 $x = $first ?
'^' : '';
2330 return preg_replace_callback(
2331 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2332 array( $this, 'ucCallback' ),
2336 return $first ?
ucfirst( $str ) : strtoupper( $str );
2342 * @param $str string
2343 * @return mixed|string
2345 function lcfirst( $str ) {
2348 return strval( $str );
2349 } elseif ( $o >= 128 ) {
2350 return $this->lc( $str, true );
2351 } elseif ( $o > 96 ) {
2354 $str[0] = strtolower( $str[0] );
2360 * @param $str string
2361 * @param $first bool
2362 * @return mixed|string
2364 function lc( $str, $first = false ) {
2365 if ( function_exists( 'mb_strtolower' ) ) {
2367 if ( $this->isMultibyte( $str ) ) {
2368 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2370 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2373 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2376 if ( $this->isMultibyte( $str ) ) {
2377 $x = $first ?
'^' : '';
2378 return preg_replace_callback(
2379 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2380 array( $this, 'lcCallback' ),
2384 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2390 * @param $str string
2393 function isMultibyte( $str ) {
2394 return (bool)preg_match( '/[\x80-\xff]/', $str );
2398 * @param $str string
2399 * @return mixed|string
2401 function ucwords( $str ) {
2402 if ( $this->isMultibyte( $str ) ) {
2403 $str = $this->lc( $str );
2405 // regexp to find first letter in each word (i.e. after each space)
2406 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2408 // function to use to capitalize a single char
2409 if ( function_exists( 'mb_strtoupper' ) ) {
2410 return preg_replace_callback(
2412 array( $this, 'ucwordsCallbackMB' ),
2416 return preg_replace_callback(
2418 array( $this, 'ucwordsCallbackWiki' ),
2423 return ucwords( strtolower( $str ) );
2428 * capitalize words at word breaks
2430 * @param $str string
2433 function ucwordbreaks( $str ) {
2434 if ( $this->isMultibyte( $str ) ) {
2435 $str = $this->lc( $str );
2437 // since \b doesn't work for UTF-8, we explicitely define word break chars
2438 $breaks = "[ \-\(\)\}\{\.,\?!]";
2440 // find first letter after word break
2441 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2443 if ( function_exists( 'mb_strtoupper' ) ) {
2444 return preg_replace_callback(
2446 array( $this, 'ucwordbreaksCallbackMB' ),
2450 return preg_replace_callback(
2452 array( $this, 'ucwordsCallbackWiki' ),
2457 return preg_replace_callback(
2458 '/\b([\w\x80-\xff]+)\b/',
2459 array( $this, 'ucwordbreaksCallbackAscii' ),
2466 * Return a case-folded representation of $s
2468 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2469 * and $s2 are the same except for the case of their characters. It is not
2470 * necessary for the value returned to make sense when displayed.
2472 * Do *not* perform any other normalisation in this function. If a caller
2473 * uses this function when it should be using a more general normalisation
2474 * function, then fix the caller.
2480 function caseFold( $s ) {
2481 return $this->uc( $s );
2488 function checkTitleEncoding( $s ) {
2489 if ( is_array( $s ) ) {
2490 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2492 if ( StringUtils
::isUtf8( $s ) ) {
2496 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2502 function fallback8bitEncoding() {
2503 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2507 * Most writing systems use whitespace to break up words.
2508 * Some languages such as Chinese don't conventionally do this,
2509 * which requires special handling when breaking up words for
2514 function hasWordBreaks() {
2519 * Some languages such as Chinese require word segmentation,
2520 * Specify such segmentation when overridden in derived class.
2522 * @param $string String
2525 function segmentByWord( $string ) {
2530 * Some languages have special punctuation need to be normalized.
2531 * Make such changes here.
2533 * @param $string String
2536 function normalizeForSearch( $string ) {
2537 return self
::convertDoubleWidth( $string );
2541 * convert double-width roman characters to single-width.
2542 * range: ff00-ff5f ~= 0020-007f
2544 * @param $string string
2548 protected static function convertDoubleWidth( $string ) {
2549 static $full = null;
2550 static $half = null;
2552 if ( $full === null ) {
2553 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2554 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2555 $full = str_split( $fullWidth, 3 );
2556 $half = str_split( $halfWidth );
2559 $string = str_replace( $full, $half, $string );
2564 * @param $string string
2565 * @param $pattern string
2568 protected static function insertSpace( $string, $pattern ) {
2569 $string = preg_replace( $pattern, " $1 ", $string );
2570 $string = preg_replace( '/ +/', ' ', $string );
2575 * @param $termsArray array
2578 function convertForSearchResult( $termsArray ) {
2579 # some languages, e.g. Chinese, need to do a conversion
2580 # in order for search results to be displayed correctly
2585 * Get the first character of a string.
2590 function firstChar( $s ) {
2593 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2594 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2599 if ( isset( $matches[1] ) ) {
2600 if ( strlen( $matches[1] ) != 3 ) {
2604 // Break down Hangul syllables to grab the first jamo
2605 $code = utf8ToCodepoint( $matches[1] );
2606 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2608 } elseif ( $code < 0xb098 ) {
2609 return "\xe3\x84\xb1";
2610 } elseif ( $code < 0xb2e4 ) {
2611 return "\xe3\x84\xb4";
2612 } elseif ( $code < 0xb77c ) {
2613 return "\xe3\x84\xb7";
2614 } elseif ( $code < 0xb9c8 ) {
2615 return "\xe3\x84\xb9";
2616 } elseif ( $code < 0xbc14 ) {
2617 return "\xe3\x85\x81";
2618 } elseif ( $code < 0xc0ac ) {
2619 return "\xe3\x85\x82";
2620 } elseif ( $code < 0xc544 ) {
2621 return "\xe3\x85\x85";
2622 } elseif ( $code < 0xc790 ) {
2623 return "\xe3\x85\x87";
2624 } elseif ( $code < 0xcc28 ) {
2625 return "\xe3\x85\x88";
2626 } elseif ( $code < 0xce74 ) {
2627 return "\xe3\x85\x8a";
2628 } elseif ( $code < 0xd0c0 ) {
2629 return "\xe3\x85\x8b";
2630 } elseif ( $code < 0xd30c ) {
2631 return "\xe3\x85\x8c";
2632 } elseif ( $code < 0xd558 ) {
2633 return "\xe3\x85\x8d";
2635 return "\xe3\x85\x8e";
2642 function initEncoding() {
2643 # Some languages may have an alternate char encoding option
2644 # (Esperanto X-coding, Japanese furigana conversion, etc)
2645 # If this language is used as the primary content language,
2646 # an override to the defaults can be set here on startup.
2653 function recodeForEdit( $s ) {
2654 # For some languages we'll want to explicitly specify
2655 # which characters make it into the edit box raw
2656 # or are converted in some way or another.
2657 global $wgEditEncoding;
2658 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2661 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2669 function recodeInput( $s ) {
2670 # Take the previous into account.
2671 global $wgEditEncoding;
2672 if ( $wgEditEncoding != '' ) {
2673 $enc = $wgEditEncoding;
2677 if ( $enc == 'UTF-8' ) {
2680 return $this->iconv( $enc, 'UTF-8', $s );
2685 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2686 * also cleans up certain backwards-compatible sequences, converting them
2687 * to the modern Unicode equivalent.
2689 * This is language-specific for performance reasons only.
2695 function normalize( $s ) {
2696 global $wgAllUnicodeFixes;
2697 $s = UtfNormal
::cleanUp( $s );
2698 if ( $wgAllUnicodeFixes ) {
2699 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2700 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2707 * Transform a string using serialized data stored in the given file (which
2708 * must be in the serialized subdirectory of $IP). The file contains pairs
2709 * mapping source characters to destination characters.
2711 * The data is cached in process memory. This will go faster if you have the
2712 * FastStringSearch extension.
2714 * @param $file string
2715 * @param $string string
2717 * @throws MWException
2720 function transformUsingPairFile( $file, $string ) {
2721 if ( !isset( $this->transformData
[$file] ) ) {
2722 $data = wfGetPrecompiledData( $file );
2723 if ( $data === false ) {
2724 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2726 $this->transformData
[$file] = new ReplacementArray( $data );
2728 return $this->transformData
[$file]->replace( $string );
2732 * For right-to-left language support
2737 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2741 * Return the correct HTML 'dir' attribute value for this language.
2745 return $this->isRTL() ?
'rtl' : 'ltr';
2749 * Return 'left' or 'right' as appropriate alignment for line-start
2750 * for this language's text direction.
2752 * Should be equivalent to CSS3 'start' text-align value....
2756 function alignStart() {
2757 return $this->isRTL() ?
'right' : 'left';
2761 * Return 'right' or 'left' as appropriate alignment for line-end
2762 * for this language's text direction.
2764 * Should be equivalent to CSS3 'end' text-align value....
2768 function alignEnd() {
2769 return $this->isRTL() ?
'left' : 'right';
2773 * A hidden direction mark (LRM or RLM), depending on the language direction.
2774 * Unlike getDirMark(), this function returns the character as an HTML entity.
2775 * This function should be used when the output is guaranteed to be HTML,
2776 * because it makes the output HTML source code more readable. When
2777 * the output is plain text or can be escaped, getDirMark() should be used.
2779 * @param $opposite Boolean Get the direction mark opposite to your language
2783 function getDirMarkEntity( $opposite = false ) {
2784 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2785 return $this->isRTL() ?
'‏' : '‎';
2789 * A hidden direction mark (LRM or RLM), depending on the language direction.
2790 * This function produces them as invisible Unicode characters and
2791 * the output may be hard to read and debug, so it should only be used
2792 * when the output is plain text or can be escaped. When the output is
2793 * HTML, use getDirMarkEntity() instead.
2795 * @param $opposite Boolean Get the direction mark opposite to your language
2798 function getDirMark( $opposite = false ) {
2799 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2800 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2801 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2802 return $this->isRTL() ?
$rlm : $lrm;
2808 function capitalizeAllNouns() {
2809 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2813 * An arrow, depending on the language direction.
2815 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2818 function getArrow( $direction = 'forwards' ) {
2819 switch ( $direction ) {
2821 return $this->isRTL() ?
'←' : '→';
2823 return $this->isRTL() ?
'→' : '←';
2836 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2840 function linkPrefixExtension() {
2841 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2847 function getMagicWords() {
2848 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2851 protected function doMagicHook() {
2852 if ( $this->mMagicHookDone
) {
2855 $this->mMagicHookDone
= true;
2856 wfProfileIn( 'LanguageGetMagic' );
2857 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2858 wfProfileOut( 'LanguageGetMagic' );
2862 * Fill a MagicWord object with data from here
2866 function getMagic( $mw ) {
2867 $this->doMagicHook();
2869 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2870 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2872 $magicWords = $this->getMagicWords();
2873 if ( isset( $magicWords[$mw->mId
] ) ) {
2874 $rawEntry = $magicWords[$mw->mId
];
2880 if ( !is_array( $rawEntry ) ) {
2881 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2883 $mw->mCaseSensitive
= $rawEntry[0];
2884 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2889 * Add magic words to the extension array
2891 * @param $newWords array
2893 function addMagicWordsByLang( $newWords ) {
2894 $fallbackChain = $this->getFallbackLanguages();
2895 $fallbackChain = array_reverse( $fallbackChain );
2896 foreach ( $fallbackChain as $code ) {
2897 if ( isset( $newWords[$code] ) ) {
2898 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2904 * Get special page names, as an associative array
2905 * case folded alias => real name
2907 function getSpecialPageAliases() {
2908 // Cache aliases because it may be slow to load them
2909 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2911 $this->mExtendedSpecialPageAliases
=
2912 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2913 wfRunHooks( 'LanguageGetSpecialPageAliases',
2914 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2917 return $this->mExtendedSpecialPageAliases
;
2921 * Italic is unsuitable for some languages
2923 * @param $text String: the text to be emphasized.
2926 function emphasize( $text ) {
2927 return "<em>$text</em>";
2931 * Normally we output all numbers in plain en_US style, that is
2932 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2933 * point twohundredthirtyfive. However this is not suitable for all
2934 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2935 * Icelandic just want to use commas instead of dots, and dots instead
2936 * of commas like "293.291,235".
2938 * An example of this function being called:
2940 * wfMessage( 'message' )->numParams( $num )->text()
2943 * See LanguageGu.php for the Gujarati implementation and
2944 * $separatorTransformTable on MessageIs.php for
2945 * the , => . and . => , implementation.
2947 * @todo check if it's viable to use localeconv() for the decimal
2949 * @param $number Mixed: the string to be formatted, should be an integer
2950 * or a floating point number.
2951 * @param $nocommafy Bool: set to true for special numbers like dates
2954 public function formatNum( $number, $nocommafy = false ) {
2955 global $wgTranslateNumerals;
2956 if ( !$nocommafy ) {
2957 $number = $this->commafy( $number );
2958 $s = $this->separatorTransformTable();
2960 $number = strtr( $number, $s );
2964 if ( $wgTranslateNumerals ) {
2965 $s = $this->digitTransformTable();
2967 $number = strtr( $number, $s );
2975 * Front-end for non-commafied formatNum
2977 * @param mixed $number the string to be formatted, should be an integer
2978 * or a floating point number.
2982 public function formatNumNoSeparators( $number ) {
2983 return $this->formatNum( $number, true );
2987 * @param $number string
2990 function parseFormattedNumber( $number ) {
2991 $s = $this->digitTransformTable();
2993 $number = strtr( $number, array_flip( $s ) );
2996 $s = $this->separatorTransformTable();
2998 $number = strtr( $number, array_flip( $s ) );
3001 $number = strtr( $number, array( ',' => '' ) );
3006 * Adds commas to a given number
3008 * @param $number mixed
3011 function commafy( $number ) {
3012 $digitGroupingPattern = $this->digitGroupingPattern();
3013 if ( $number === null ) {
3017 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3018 // default grouping is at thousands, use the same for ###,###,### pattern too.
3019 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3021 // Ref: http://cldr.unicode.org/translation/number-patterns
3023 if ( intval( $number ) < 0 ) {
3024 // For negative numbers apply the algorithm like positive number and add sign.
3026 $number = substr( $number, 1 );
3028 $integerPart = array();
3029 $decimalPart = array();
3030 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3031 preg_match( "/\d+/", $number, $integerPart );
3032 preg_match( "/\.\d*/", $number, $decimalPart );
3033 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0]:"";
3034 if ( $groupedNumber === $number ) {
3035 // the string does not have any number part. Eg: .12345
3036 return $sign . $groupedNumber;
3038 $start = $end = strlen( $integerPart[0] );
3039 while ( $start > 0 ) {
3040 $match = $matches[0][$numMatches -1] ;
3041 $matchLen = strlen( $match );
3042 $start = $end - $matchLen;
3046 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber ;
3048 if ( $numMatches > 1 ) {
3049 // use the last pattern for the rest of the number
3053 $groupedNumber = "," . $groupedNumber;
3056 return $sign . $groupedNumber;
3063 function digitGroupingPattern() {
3064 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3070 function digitTransformTable() {
3071 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3077 function separatorTransformTable() {
3078 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3082 * Take a list of strings and build a locale-friendly comma-separated
3083 * list, using the local comma-separator message.
3084 * The last two strings are chained with an "and".
3085 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3090 function listToText( array $l ) {
3091 $m = count( $l ) - 1;
3096 $and = $this->getMessageFromDB( 'and' );
3097 $space = $this->getMessageFromDB( 'word-separator' );
3099 $comma = $this->getMessageFromDB( 'comma-separator' );
3103 for ( $i = $m - 1; $i >= 0; $i-- ) {
3104 if ( $i == $m - 1 ) {
3105 $s = $l[$i] . $and . $space . $s;
3107 $s = $l[$i] . $comma . $s;
3114 * Take a list of strings and build a locale-friendly comma-separated
3115 * list, using the local comma-separator message.
3116 * @param $list array of strings to put in a comma list
3119 function commaList( array $list ) {
3121 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3127 * Take a list of strings and build a locale-friendly semicolon-separated
3128 * list, using the local semicolon-separator message.
3129 * @param $list array of strings to put in a semicolon list
3132 function semicolonList( array $list ) {
3134 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3140 * Same as commaList, but separate it with the pipe instead.
3141 * @param $list array of strings to put in a pipe list
3144 function pipeList( array $list ) {
3146 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3152 * Truncate a string to a specified length in bytes, appending an optional
3153 * string (e.g. for ellipses)
3155 * The database offers limited byte lengths for some columns in the database;
3156 * multi-byte character sets mean we need to ensure that only whole characters
3157 * are included, otherwise broken characters can be passed to the user
3159 * If $length is negative, the string will be truncated from the beginning
3161 * @param $string String to truncate
3162 * @param $length Int: maximum length (including ellipses)
3163 * @param $ellipsis String to append to the truncated text
3164 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3165 * $adjustLength was introduced in 1.18, before that behaved as if false.
3168 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3169 # Use the localized ellipsis character
3170 if ( $ellipsis == '...' ) {
3171 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3173 # Check if there is no need to truncate
3174 if ( $length == 0 ) {
3175 return $ellipsis; // convention
3176 } elseif ( strlen( $string ) <= abs( $length ) ) {
3177 return $string; // no need to truncate
3179 $stringOriginal = $string;
3180 # If ellipsis length is >= $length then we can't apply $adjustLength
3181 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3182 $string = $ellipsis; // this can be slightly unexpected
3183 # Otherwise, truncate and add ellipsis...
3185 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3186 if ( $length > 0 ) {
3187 $length -= $eLength;
3188 $string = substr( $string, 0, $length ); // xyz...
3189 $string = $this->removeBadCharLast( $string );
3190 $string = $string . $ellipsis;
3192 $length +
= $eLength;
3193 $string = substr( $string, $length ); // ...xyz
3194 $string = $this->removeBadCharFirst( $string );
3195 $string = $ellipsis . $string;
3198 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3199 # This check is *not* redundant if $adjustLength, due to the single case where
3200 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3201 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3204 return $stringOriginal;
3209 * Remove bytes that represent an incomplete Unicode character
3210 * at the end of string (e.g. bytes of the char are missing)
3212 * @param $string String
3215 protected function removeBadCharLast( $string ) {
3216 if ( $string != '' ) {
3217 $char = ord( $string[strlen( $string ) - 1] );
3219 if ( $char >= 0xc0 ) {
3220 # We got the first byte only of a multibyte char; remove it.
3221 $string = substr( $string, 0, -1 );
3222 } elseif ( $char >= 0x80 &&
3223 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3224 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3226 # We chopped in the middle of a character; remove it
3234 * Remove bytes that represent an incomplete Unicode character
3235 * at the start of string (e.g. bytes of the char are missing)
3237 * @param $string String
3240 protected function removeBadCharFirst( $string ) {
3241 if ( $string != '' ) {
3242 $char = ord( $string[0] );
3243 if ( $char >= 0x80 && $char < 0xc0 ) {
3244 # We chopped in the middle of a character; remove the whole thing
3245 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3252 * Truncate a string of valid HTML to a specified length in bytes,
3253 * appending an optional string (e.g. for ellipses), and return valid HTML
3255 * This is only intended for styled/linked text, such as HTML with
3256 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3257 * Also, this will not detect things like "display:none" CSS.
3259 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3261 * @param string $text HTML string to truncate
3262 * @param int $length (zero/positive) Maximum length (including ellipses)
3263 * @param string $ellipsis String to append to the truncated text
3266 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3267 # Use the localized ellipsis character
3268 if ( $ellipsis == '...' ) {
3269 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3271 # Check if there is clearly no need to truncate
3272 if ( $length <= 0 ) {
3273 return $ellipsis; // no text shown, nothing to format (convention)
3274 } elseif ( strlen( $text ) <= $length ) {
3275 return $text; // string short enough even *with* HTML (short-circuit)
3278 $dispLen = 0; // innerHTML legth so far
3279 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3280 $tagType = 0; // 0-open, 1-close
3281 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3282 $entityState = 0; // 0-not entity, 1-entity
3283 $tag = $ret = ''; // accumulated tag name, accumulated result string
3284 $openTags = array(); // open tag stack
3285 $maybeState = null; // possible truncation state
3287 $textLen = strlen( $text );
3288 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3289 for ( $pos = 0; true; ++
$pos ) {
3290 # Consider truncation once the display length has reached the maximim.
3291 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3292 # Check that we're not in the middle of a bracket/entity...
3293 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3294 if ( !$testingEllipsis ) {
3295 $testingEllipsis = true;
3296 # Save where we are; we will truncate here unless there turn out to
3297 # be so few remaining characters that truncation is not necessary.
3298 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3299 $maybeState = array( $ret, $openTags ); // save state
3301 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3302 # String in fact does need truncation, the truncation point was OK.
3303 list( $ret, $openTags ) = $maybeState; // reload state
3304 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3305 $ret .= $ellipsis; // add ellipsis
3309 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3311 # Read the next char...
3313 $lastCh = $pos ?
$text[$pos - 1] : '';
3314 $ret .= $ch; // add to result string
3316 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3317 $entityState = 0; // for bad HTML
3318 $bracketState = 1; // tag started (checking for backslash)
3319 } elseif ( $ch == '>' ) {
3320 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3321 $entityState = 0; // for bad HTML
3322 $bracketState = 0; // out of brackets
3323 } elseif ( $bracketState == 1 ) {
3325 $tagType = 1; // close tag (e.g. "</span>")
3327 $tagType = 0; // open tag (e.g. "<span>")
3330 $bracketState = 2; // building tag name
3331 } elseif ( $bracketState == 2 ) {
3335 // Name found (e.g. "<a href=..."), add on tag attributes...
3336 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3338 } elseif ( $bracketState == 0 ) {
3339 if ( $entityState ) {
3342 $dispLen++
; // entity is one displayed char
3345 if ( $neLength == 0 && !$maybeState ) {
3346 // Save state without $ch. We want to *hit* the first
3347 // display char (to get tags) but not *use* it if truncating.
3348 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3351 $entityState = 1; // entity found, (e.g. " ")
3353 $dispLen++
; // this char is displayed
3354 // Add the next $max display text chars after this in one swoop...
3355 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3356 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3357 $dispLen +
= $skipped;
3363 // Close the last tag if left unclosed by bad HTML
3364 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3365 while ( count( $openTags ) > 0 ) {
3366 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3372 * truncateHtml() helper function
3373 * like strcspn() but adds the skipped chars to $ret
3382 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3383 if ( $len === null ) {
3384 $len = -1; // -1 means "no limit" for strcspn
3385 } elseif ( $len < 0 ) {
3389 if ( $start < strlen( $text ) ) {
3390 $skipCount = strcspn( $text, $search, $start, $len );
3391 $ret .= substr( $text, $start, $skipCount );
3397 * truncateHtml() helper function
3398 * (a) push or pop $tag from $openTags as needed
3399 * (b) clear $tag value
3400 * @param &$tag string Current HTML tag name we are looking at
3401 * @param $tagType int (0-open tag, 1-close tag)
3402 * @param $lastCh string Character before the '>' that ended this tag
3403 * @param &$openTags array Open tag stack (not accounting for $tag)
3405 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3406 $tag = ltrim( $tag );
3408 if ( $tagType == 0 && $lastCh != '/' ) {
3409 $openTags[] = $tag; // tag opened (didn't close itself)
3410 } elseif ( $tagType == 1 ) {
3411 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3412 array_pop( $openTags ); // tag closed
3420 * Grammatical transformations, needed for inflected languages
3421 * Invoked by putting {{grammar:case|word}} in a message
3423 * @param $word string
3424 * @param $case string
3427 function convertGrammar( $word, $case ) {
3428 global $wgGrammarForms;
3429 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3430 return $wgGrammarForms[$this->getCode()][$case][$word];
3435 * Get the grammar forms for the content language
3436 * @return array of grammar forms
3439 function getGrammarForms() {
3440 global $wgGrammarForms;
3441 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3442 return $wgGrammarForms[$this->getCode()];
3447 * Provides an alternative text depending on specified gender.
3448 * Usage {{gender:username|masculine|feminine|neutral}}.
3449 * username is optional, in which case the gender of current user is used,
3450 * but only in (some) interface messages; otherwise default gender is used.
3452 * If no forms are given, an empty string is returned. If only one form is
3453 * given, it will be returned unconditionally. These details are implied by
3454 * the caller and cannot be overridden in subclasses.
3456 * If more than one form is given, the default is to use the neutral one
3457 * if it is specified, and to use the masculine one otherwise. These
3458 * details can be overridden in subclasses.
3460 * @param $gender string
3461 * @param $forms array
3465 function gender( $gender, $forms ) {
3466 if ( !count( $forms ) ) {
3469 $forms = $this->preConvertPlural( $forms, 2 );
3470 if ( $gender === 'male' ) {
3473 if ( $gender === 'female' ) {
3476 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3480 * Plural form transformations, needed for some languages.
3481 * For example, there are 3 form of plural in Russian and Polish,
3482 * depending on "count mod 10". See [[w:Plural]]
3483 * For English it is pretty simple.
3485 * Invoked by putting {{plural:count|wordform1|wordform2}}
3486 * or {{plural:count|wordform1|wordform2|wordform3}}
3488 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3490 * @param $count Integer: non-localized number
3491 * @param $forms Array: different plural forms
3492 * @return string Correct form of plural for $count in this language
3494 function convertPlural( $count, $forms ) {
3495 if ( !count( $forms ) ) {
3499 // Handle explicit n=pluralform cases
3500 foreach ( $forms as $index => $form ) {
3501 if ( preg_match( '/\d+=/i', $form ) ) {
3502 $pos = strpos( $form, '=' );
3503 if ( substr( $form, 0, $pos ) === (string) $count ) {
3504 return substr( $form, $pos +
1 );
3506 unset( $forms[$index] );
3509 $forms = array_values( $forms );
3511 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3512 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3513 return $forms[$pluralForm];
3517 * Checks that convertPlural was given an array and pads it to requested
3518 * amount of forms by copying the last one.
3520 * @param $count Integer: How many forms should there be at least
3521 * @param $forms Array of forms given to convertPlural
3522 * @return array Padded array of forms or an exception if not an array
3524 protected function preConvertPlural( /* Array */ $forms, $count ) {
3525 while ( count( $forms ) < $count ) {
3526 $forms[] = $forms[count( $forms ) - 1];
3532 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3533 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3534 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3535 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3538 * @param $str String: the validated block duration in English
3539 * @return string Somehow translated block duration
3540 * @see LanguageFi.php for example implementation
3542 function translateBlockExpiry( $str ) {
3543 $duration = SpecialBlock
::getSuggestedDurations( $this );
3544 foreach ( $duration as $show => $value ) {
3545 if ( strcmp( $str, $value ) == 0 ) {
3546 return htmlspecialchars( trim( $show ) );
3550 // Since usually only infinite or indefinite is only on list, so try
3551 // equivalents if still here.
3552 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3553 if ( in_array( $str, $indefs ) ) {
3554 foreach ( $indefs as $val ) {
3555 $show = array_search( $val, $duration, true );
3556 if ( $show !== false ) {
3557 return htmlspecialchars( trim( $show ) );
3562 // If all else fails, return a standard duration or timestamp description.
3563 $time = strtotime( $str, 0 );
3564 if ( $time === false ) { // Unknown format. Return it as-is in case.
3566 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3567 // $time is relative to 0 so it's a duration length.
3568 return $this->formatDuration( $time );
3569 } else { // It's an absolute timestamp.
3570 if ( $time === 0 ) {
3571 // wfTimestamp() handles 0 as current time instead of epoch.
3572 return $this->timeanddate( '19700101000000' );
3574 return $this->timeanddate( $time );
3580 * languages like Chinese need to be segmented in order for the diff
3583 * @param $text String
3586 public function segmentForDiff( $text ) {
3591 * and unsegment to show the result
3593 * @param $text String
3596 public function unsegmentForDiff( $text ) {
3601 * Return the LanguageConverter used in the Language
3604 * @return LanguageConverter
3606 public function getConverter() {
3607 return $this->mConverter
;
3611 * convert text to all supported variants
3613 * @param $text string
3616 public function autoConvertToAllVariants( $text ) {
3617 return $this->mConverter
->autoConvertToAllVariants( $text );
3621 * convert text to different variants of a language.
3623 * @param $text string
3626 public function convert( $text ) {
3627 return $this->mConverter
->convert( $text );
3631 * Convert a Title object to a string in the preferred variant
3633 * @param $title Title
3636 public function convertTitle( $title ) {
3637 return $this->mConverter
->convertTitle( $title );
3641 * Convert a namespace index to a string in the preferred variant
3646 public function convertNamespace( $ns ) {
3647 return $this->mConverter
->convertNamespace( $ns );
3651 * Check if this is a language with variants
3655 public function hasVariants() {
3656 return count( $this->getVariants() ) > 1;
3660 * Check if the language has the specific variant
3663 * @param $variant string
3666 public function hasVariant( $variant ) {
3667 return (bool)$this->mConverter
->validateVariant( $variant );
3671 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3673 * @param $text string
3676 public function armourMath( $text ) {
3677 return $this->mConverter
->armourMath( $text );
3681 * Perform output conversion on a string, and encode for safe HTML output.
3682 * @param $text String text to be converted
3683 * @param $isTitle Bool whether this conversion is for the article title
3685 * @todo this should get integrated somewhere sane
3687 public function convertHtml( $text, $isTitle = false ) {
3688 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3692 * @param $key string
3695 public function convertCategoryKey( $key ) {
3696 return $this->mConverter
->convertCategoryKey( $key );
3700 * Get the list of variants supported by this language
3701 * see sample implementation in LanguageZh.php
3703 * @return array an array of language codes
3705 public function getVariants() {
3706 return $this->mConverter
->getVariants();
3712 public function getPreferredVariant() {
3713 return $this->mConverter
->getPreferredVariant();
3719 public function getDefaultVariant() {
3720 return $this->mConverter
->getDefaultVariant();
3726 public function getURLVariant() {
3727 return $this->mConverter
->getURLVariant();
3731 * If a language supports multiple variants, it is
3732 * possible that non-existing link in one variant
3733 * actually exists in another variant. this function
3734 * tries to find it. See e.g. LanguageZh.php
3736 * @param $link String: the name of the link
3737 * @param $nt Mixed: the title object of the link
3738 * @param $ignoreOtherCond Boolean: to disable other conditions when
3739 * we need to transclude a template or update a category's link
3740 * @return null the input parameters may be modified upon return
3742 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3743 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3747 * If a language supports multiple variants, converts text
3748 * into an array of all possible variants of the text:
3749 * 'variant' => text in that variant
3751 * @deprecated since 1.17 Use autoConvertToAllVariants()
3753 * @param $text string
3757 public function convertLinkToAllVariants( $text ) {
3758 return $this->mConverter
->convertLinkToAllVariants( $text );
3762 * returns language specific options used by User::getPageRenderHash()
3763 * for example, the preferred language variant
3767 function getExtraHashOptions() {
3768 return $this->mConverter
->getExtraHashOptions();
3772 * For languages that support multiple variants, the title of an
3773 * article may be displayed differently in different variants. this
3774 * function returns the apporiate title defined in the body of the article.
3778 public function getParsedTitle() {
3779 return $this->mConverter
->getParsedTitle();
3783 * Prepare external link text for conversion. When the text is
3784 * a URL, it shouldn't be converted, and it'll be wrapped in
3785 * the "raw" tag (-{R| }-) to prevent conversion.
3787 * This function is called "markNoConversion" for historical
3790 * @param $text String: text to be used for external link
3791 * @param $noParse bool: wrap it without confirming it's a real URL first
3792 * @return string the tagged text
3794 public function markNoConversion( $text, $noParse = false ) {
3795 // Excluding protocal-relative URLs may avoid many false positives.
3796 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3797 return $this->mConverter
->markNoConversion( $text );
3804 * A regular expression to match legal word-trailing characters
3805 * which should be merged onto a link of the form [[foo]]bar.
3809 public function linkTrail() {
3810 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3816 function getLangObj() {
3821 * Get the RFC 3066 code for this language object
3823 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3824 * htmlspecialchars() or similar
3828 public function getCode() {
3829 return $this->mCode
;
3833 * Get the code in Bcp47 format which we can use
3834 * inside of html lang="" tags.
3836 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3837 * htmlspecialchars() or similar.
3842 public function getHtmlCode() {
3843 if ( is_null( $this->mHtmlCode
) ) {
3844 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3846 return $this->mHtmlCode
;
3850 * @param $code string
3852 public function setCode( $code ) {
3853 $this->mCode
= $code;
3854 // Ensure we don't leave an incorrect html code lying around
3855 $this->mHtmlCode
= null;
3859 * Get the name of a file for a certain language code
3860 * @param $prefix string Prepend this to the filename
3861 * @param $code string Language code
3862 * @param $suffix string Append this to the filename
3863 * @throws MWException
3864 * @return string $prefix . $mangledCode . $suffix
3866 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3867 // Protect against path traversal
3868 if ( !Language
::isValidCode( $code )
3869 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3871 throw new MWException( "Invalid language code \"$code\"" );
3874 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3878 * Get the language code from a file name. Inverse of getFileName()
3879 * @param $filename string $prefix . $languageCode . $suffix
3880 * @param $prefix string Prefix before the language code
3881 * @param $suffix string Suffix after the language code
3882 * @return string Language code, or false if $prefix or $suffix isn't found
3884 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3886 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3887 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3888 if ( !count( $m ) ) {
3891 return str_replace( '_', '-', strtolower( $m[1] ) );
3895 * @param $code string
3898 public static function getMessagesFileName( $code ) {
3900 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3901 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3906 * @param $code string
3909 public static function getClassFileName( $code ) {
3911 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3915 * Get the first fallback for a given language.
3917 * @param $code string
3919 * @return bool|string
3921 public static function getFallbackFor( $code ) {
3922 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3925 $fallbacks = self
::getFallbacksFor( $code );
3926 $first = array_shift( $fallbacks );
3932 * Get the ordered list of fallback languages.
3935 * @param $code string Language code
3938 public static function getFallbacksFor( $code ) {
3939 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3942 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3943 $v = array_map( 'trim', explode( ',', $v ) );
3944 if ( $v[count( $v ) - 1] !== 'en' ) {
3952 * Get all messages for a given language
3953 * WARNING: this may take a long time. If you just need all message *keys*
3954 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3956 * @param $code string
3960 public static function getMessagesFor( $code ) {
3961 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3965 * Get a message for a given language
3967 * @param $key string
3968 * @param $code string
3972 public static function getMessageFor( $key, $code ) {
3973 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3977 * Get all message keys for a given language. This is a faster alternative to
3978 * array_keys( Language::getMessagesFor( $code ) )
3981 * @param $code string Language code
3982 * @return array of message keys (strings)
3984 public static function getMessageKeysFor( $code ) {
3985 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3992 function fixVariableInNamespace( $talk ) {
3993 if ( strpos( $talk, '$1' ) === false ) {
3997 global $wgMetaNamespace;
3998 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4000 # Allow grammar transformations
4001 # Allowing full message-style parsing would make simple requests
4002 # such as action=raw much more expensive than they need to be.
4003 # This will hopefully cover most cases.
4004 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4005 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4006 return str_replace( ' ', '_', $talk );
4013 function replaceGrammarInNamespace( $m ) {
4014 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4018 * @throws MWException
4021 static function getCaseMaps() {
4022 static $wikiUpperChars, $wikiLowerChars;
4023 if ( isset( $wikiUpperChars ) ) {
4024 return array( $wikiUpperChars, $wikiLowerChars );
4027 wfProfileIn( __METHOD__
);
4028 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4029 if ( $arr === false ) {
4030 throw new MWException(
4031 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4033 $wikiUpperChars = $arr['wikiUpperChars'];
4034 $wikiLowerChars = $arr['wikiLowerChars'];
4035 wfProfileOut( __METHOD__
);
4036 return array( $wikiUpperChars, $wikiLowerChars );
4040 * Decode an expiry (block, protection, etc) which has come from the DB
4042 * @todo FIXME: why are we returnings DBMS-dependent strings???
4044 * @param $expiry String: Database expiry String
4045 * @param $format Bool|Int true to process using language functions, or TS_ constant
4046 * to return the expiry in a given timestamp
4050 public function formatExpiry( $expiry, $format = true ) {
4051 static $infinity, $infinityMsg;
4052 if ( $infinity === null ) {
4053 $infinityMsg = wfMessage( 'infiniteblock' );
4054 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4057 if ( $expiry == '' ||
$expiry == $infinity ) {
4058 return $format === true
4062 return $format === true
4063 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4064 : wfTimestamp( $format, $expiry );
4070 * @param $seconds int|float
4071 * @param $format Array Optional
4072 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4073 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4074 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4075 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4078 function formatTimePeriod( $seconds, $format = array() ) {
4079 if ( !is_array( $format ) ) {
4080 $format = array( 'avoid' => $format ); // For backwards compatibility
4082 if ( !isset( $format['avoid'] ) ) {
4083 $format['avoid'] = false;
4085 if ( !isset( $format['noabbrevs' ] ) ) {
4086 $format['noabbrevs'] = false;
4088 $secondsMsg = wfMessage(
4089 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4090 $minutesMsg = wfMessage(
4091 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4092 $hoursMsg = wfMessage(
4093 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4094 $daysMsg = wfMessage(
4095 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4097 if ( round( $seconds * 10 ) < 100 ) {
4098 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4099 $s = $secondsMsg->params( $s )->text();
4100 } elseif ( round( $seconds ) < 60 ) {
4101 $s = $this->formatNum( round( $seconds ) );
4102 $s = $secondsMsg->params( $s )->text();
4103 } elseif ( round( $seconds ) < 3600 ) {
4104 $minutes = floor( $seconds / 60 );
4105 $secondsPart = round( fmod( $seconds, 60 ) );
4106 if ( $secondsPart == 60 ) {
4110 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4112 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4113 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4114 $hours = floor( $seconds / 3600 );
4115 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4116 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4117 if ( $secondsPart == 60 ) {
4121 if ( $minutes == 60 ) {
4125 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4127 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4128 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4129 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4132 $days = floor( $seconds / 86400 );
4133 if ( $format['avoid'] === 'avoidminutes' ) {
4134 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4135 if ( $hours == 24 ) {
4139 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4141 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4142 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4143 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4144 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4145 if ( $minutes == 60 ) {
4149 if ( $hours == 24 ) {
4153 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4155 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4157 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4159 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4161 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4168 * Format a bitrate for output, using an appropriate
4169 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4171 * This use base 1000. For base 1024 use formatSize(), for another base
4172 * see formatComputingNumbers()
4177 function formatBitrate( $bps ) {
4178 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4182 * @param $size int Size of the unit
4183 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4184 * @param $messageKey string Message key to be uesd
4187 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4189 return str_replace( '$1', $this->formatNum( $size ),
4190 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4193 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4196 $maxIndex = count( $sizes ) - 1;
4197 while ( $size >= $boundary && $index < $maxIndex ) {
4202 // For small sizes no decimal places necessary
4205 // For MB and bigger two decimal places are smarter
4208 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4210 $size = round( $size, $round );
4211 $text = $this->getMessageFromDB( $msg );
4212 return str_replace( '$1', $this->formatNum( $size ), $text );
4216 * Format a size in bytes for output, using an appropriate
4217 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4219 * This method use base 1024. For base 1000 use formatBitrate(), for
4220 * another base see formatComputingNumbers()
4222 * @param $size int Size to format
4223 * @return string Plain text (not HTML)
4225 function formatSize( $size ) {
4226 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4230 * Make a list item, used by various special pages
4232 * @param $page String Page link
4233 * @param $details String Text between brackets
4234 * @param $oppositedm Boolean Add the direction mark opposite to your
4235 * language, to display text properly
4238 function specialList( $page, $details, $oppositedm = true ) {
4239 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4240 $this->getDirMark();
4241 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4242 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4243 return $page . $details;
4247 * Generate (prev x| next x) (20|50|100...) type links for paging
4249 * @param $title Title object to link
4250 * @param $offset Integer offset parameter
4251 * @param $limit Integer limit parameter
4252 * @param $query array|String optional URL query parameter string
4253 * @param $atend Bool optional param for specified if this is the last page
4256 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4257 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4259 # Make 'previous' link
4260 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4261 if ( $offset > 0 ) {
4262 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4263 $query, $prev, 'prevn-title', 'mw-prevlink' );
4265 $plink = htmlspecialchars( $prev );
4269 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4271 $nlink = htmlspecialchars( $next );
4273 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4274 $query, $next, 'prevn-title', 'mw-nextlink' );
4277 # Make links to set number of items per page
4278 $numLinks = array();
4279 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4280 $numLinks[] = $this->numLink( $title, $offset, $num,
4281 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4284 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4285 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4289 * Helper function for viewPrevNext() that generates links
4291 * @param $title Title object to link
4292 * @param $offset Integer offset parameter
4293 * @param $limit Integer limit parameter
4294 * @param $query Array extra query parameters
4295 * @param $link String text to use for the link; will be escaped
4296 * @param $tooltipMsg String name of the message to use as tooltip
4297 * @param $class String value of the "class" attribute of the link
4298 * @return String HTML fragment
4300 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4301 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4302 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4303 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4304 'title' => $tooltip, 'class' => $class ), $link );
4308 * Get the conversion rule title, if any.
4312 public function getConvRuleTitle() {
4313 return $this->mConverter
->getConvRuleTitle();
4317 * Get the compiled plural rules for the language
4319 * @return array Associative array with plural form, and plural rule as key-value pairs
4321 public function getCompiledPluralRules() {
4322 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4323 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4324 if ( !$pluralRules ) {
4325 foreach ( $fallbacks as $fallbackCode ) {
4326 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4327 if ( $pluralRules ) {
4332 return $pluralRules;
4336 * Get the plural rules for the language
4338 * @return array Associative array with plural form number and plural rule as key-value pairs
4340 public function getPluralRules() {
4341 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4342 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4343 if ( !$pluralRules ) {
4344 foreach ( $fallbacks as $fallbackCode ) {
4345 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4346 if ( $pluralRules ) {
4351 return $pluralRules;
4355 * Get the plural rule types for the language
4357 * @return array Associative array with plural form number and plural rule type as key-value pairs
4359 public function getPluralRuleTypes() {
4360 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4361 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4362 if ( !$pluralRuleTypes ) {
4363 foreach ( $fallbacks as $fallbackCode ) {
4364 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4365 if ( $pluralRuleTypes ) {
4370 return $pluralRuleTypes;
4374 * Find the index number of the plural rule appropriate for the given number
4375 * @return int The index number of the plural rule
4377 public function getPluralRuleIndexNumber( $number ) {
4378 $pluralRules = $this->getCompiledPluralRules();
4379 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4384 * Find the plural rule type appropriate for the given number
4385 * For example, if the language is set to Arabic, getPluralType(5) should
4388 * @return string The name of the plural rule type, e.g. one, two, few, many
4390 public function getPluralRuleType( $number ) {
4391 $index = $this->getPluralRuleIndexNumber( $number );
4392 $pluralRuleTypes = $this->getPluralRuleTypes();
4393 if ( isset( $pluralRuleTypes[$index] ) ) {
4394 return $pluralRuleTypes[$index];