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 ) {
329 static $cache = array();
330 if ( isset( $cache[$code] ) ) {
331 return $cache[$code];
333 // People think language codes are html safe, so enforce it.
334 // Ideally we should only allow a-zA-Z0-9-
335 // but, .+ and other chars are often used for {{int:}} hacks
336 // see bugs 37564, 37587, 36938
338 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
339 && !preg_match( Title
::getTitleInvalidRegex(), $code );
341 return $cache[$code];
345 * Returns true if a language code is of a valid form for the purposes of
346 * internal customisation of MediaWiki, via Messages*.php.
348 * @param $code string
350 * @throws MWException
354 public static function isValidBuiltInCode( $code ) {
356 if ( !is_string( $code ) ) {
357 if ( is_object( $code ) ) {
358 $addmsg = " of class " . get_class( $code );
362 $type = gettype( $code );
363 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
366 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
370 * Returns true if a language code is an IETF tag known to MediaWiki.
372 * @param $code string
377 public static function isKnownLanguageTag( $tag ) {
378 static $coreLanguageNames;
380 if ( $coreLanguageNames === null ) {
381 include MWInit
::compiledPath( 'languages/Names.php' );
384 if ( isset( $coreLanguageNames[$tag] )
385 || self
::fetchLanguageName( $tag, $tag ) !== ''
395 * @return String Name of the language class
397 public static function classFromCode( $code ) {
398 if ( $code == 'en' ) {
401 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
406 * Includes language class files
408 * @param $class string Name of the language class
410 public static function preloadLanguageClass( $class ) {
413 if ( $class === 'Language' ) {
417 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
418 include_once "$IP/languages/classes/$class.php";
423 * Get the LocalisationCache instance
425 * @return LocalisationCache
427 public static function getLocalisationCache() {
428 if ( is_null( self
::$dataCache ) ) {
429 global $wgLocalisationCacheConf;
430 $class = $wgLocalisationCacheConf['class'];
431 self
::$dataCache = new $class( $wgLocalisationCacheConf );
433 return self
::$dataCache;
436 function __construct() {
437 $this->mConverter
= new FakeConverter( $this );
438 // Set the code to the name of the descendant
439 if ( get_class( $this ) == 'Language' ) {
442 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
444 self
::getLocalisationCache();
448 * Reduce memory usage
450 function __destruct() {
451 foreach ( $this as $name => $value ) {
452 unset( $this->$name );
457 * Hook which will be called if this is the content language.
458 * Descendants can use this to register hook functions or modify globals
460 function initContLang() { }
463 * Same as getFallbacksFor for current language.
465 * @deprecated in 1.19
467 function getFallbackLanguageCode() {
468 wfDeprecated( __METHOD__
, '1.19' );
469 return self
::getFallbackFor( $this->mCode
);
476 function getFallbackLanguages() {
477 return self
::getFallbacksFor( $this->mCode
);
481 * Exports $wgBookstoreListEn
484 function getBookstoreList() {
485 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
489 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
490 * available in localised form, it will be included in English.
494 public function getNamespaces() {
495 if ( is_null( $this->namespaceNames
) ) {
496 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
498 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
499 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
501 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
503 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
504 if ( $wgMetaNamespaceTalk ) {
505 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
507 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
508 $this->namespaceNames
[NS_PROJECT_TALK
] =
509 $this->fixVariableInNamespace( $talk );
512 # Sometimes a language will be localised but not actually exist on this wiki.
513 foreach ( $this->namespaceNames
as $key => $text ) {
514 if ( !isset( $validNamespaces[$key] ) ) {
515 unset( $this->namespaceNames
[$key] );
519 # The above mixing may leave namespaces out of canonical order.
520 # Re-order by namespace ID number...
521 ksort( $this->namespaceNames
);
523 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
525 return $this->namespaceNames
;
529 * Arbitrarily set all of the namespace names at once. Mainly used for testing
530 * @param $namespaces Array of namespaces (id => name)
532 public function setNamespaces( array $namespaces ) {
533 $this->namespaceNames
= $namespaces;
534 $this->mNamespaceIds
= null;
538 * Resets all of the namespace caches. Mainly used for testing
540 public function resetNamespaces() {
541 $this->namespaceNames
= null;
542 $this->mNamespaceIds
= null;
543 $this->namespaceAliases
= null;
547 * A convenience function that returns the same thing as
548 * getNamespaces() except with the array values changed to ' '
549 * where it found '_', useful for producing output to be displayed
550 * e.g. in <select> forms.
554 function getFormattedNamespaces() {
555 $ns = $this->getNamespaces();
556 foreach ( $ns as $k => $v ) {
557 $ns[$k] = strtr( $v, '_', ' ' );
563 * Get a namespace value by key
565 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
566 * echo $mw_ns; // prints 'MediaWiki'
569 * @param $index Int: the array key of the namespace to return
570 * @return mixed, string if the namespace value exists, otherwise false
572 function getNsText( $index ) {
573 $ns = $this->getNamespaces();
574 return isset( $ns[$index] ) ?
$ns[$index] : false;
578 * A convenience function that returns the same thing as
579 * getNsText() except with '_' changed to ' ', useful for
583 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
584 * echo $mw_ns; // prints 'MediaWiki talk'
587 * @param int $index The array key of the namespace to return
588 * @return string Namespace name without underscores (empty string if namespace does not exist)
590 function getFormattedNsText( $index ) {
591 $ns = $this->getNsText( $index );
592 return strtr( $ns, '_', ' ' );
596 * Returns gender-dependent namespace alias if available.
597 * @param $index Int: namespace index
598 * @param $gender String: gender key (male, female... )
602 function getGenderNsText( $index, $gender ) {
603 global $wgExtraGenderNamespaces;
605 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
606 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
610 * Whether this language makes distinguishes genders for example in
615 function needsGenderDistinction() {
616 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
617 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
618 // $wgExtraGenderNamespaces overrides everything
620 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
621 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
622 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
625 // Check what is in i18n files
626 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
627 return count( $aliases ) > 0;
632 * Get a namespace key by value, case insensitive.
633 * Only matches namespace names for the current language, not the
634 * canonical ones defined in Namespace.php.
636 * @param $text String
637 * @return mixed An integer if $text is a valid value otherwise false
639 function getLocalNsIndex( $text ) {
640 $lctext = $this->lc( $text );
641 $ids = $this->getNamespaceIds();
642 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
648 function getNamespaceAliases() {
649 if ( is_null( $this->namespaceAliases
) ) {
650 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
654 foreach ( $aliases as $name => $index ) {
655 if ( $index === NS_PROJECT_TALK
) {
656 unset( $aliases[$name] );
657 $name = $this->fixVariableInNamespace( $name );
658 $aliases[$name] = $index;
663 global $wgExtraGenderNamespaces;
664 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
665 foreach ( $genders as $index => $forms ) {
666 foreach ( $forms as $alias ) {
667 $aliases[$alias] = $index;
671 $this->namespaceAliases
= $aliases;
673 return $this->namespaceAliases
;
679 function getNamespaceIds() {
680 if ( is_null( $this->mNamespaceIds
) ) {
681 global $wgNamespaceAliases;
682 # Put namespace names and aliases into a hashtable.
683 # If this is too slow, then we should arrange it so that it is done
684 # before caching. The catch is that at pre-cache time, the above
685 # class-specific fixup hasn't been done.
686 $this->mNamespaceIds
= array();
687 foreach ( $this->getNamespaces() as $index => $name ) {
688 $this->mNamespaceIds
[$this->lc( $name )] = $index;
690 foreach ( $this->getNamespaceAliases() as $name => $index ) {
691 $this->mNamespaceIds
[$this->lc( $name )] = $index;
693 if ( $wgNamespaceAliases ) {
694 foreach ( $wgNamespaceAliases as $name => $index ) {
695 $this->mNamespaceIds
[$this->lc( $name )] = $index;
699 return $this->mNamespaceIds
;
703 * Get a namespace key by value, case insensitive. Canonical namespace
704 * names override custom ones defined for the current language.
706 * @param $text String
707 * @return mixed An integer if $text is a valid value otherwise false
709 function getNsIndex( $text ) {
710 $lctext = $this->lc( $text );
711 $ns = MWNamespace
::getCanonicalIndex( $lctext );
712 if ( $ns !== null ) {
715 $ids = $this->getNamespaceIds();
716 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
720 * short names for language variants used for language conversion links.
722 * @param $code String
723 * @param $usemsg bool Use the "variantname-xyz" message if it exists
726 function getVariantname( $code, $usemsg = true ) {
727 $msg = "variantname-$code";
728 if ( $usemsg && wfMessage( $msg )->exists() ) {
729 return $this->getMessageFromDB( $msg );
731 $name = self
::fetchLanguageName( $code );
733 return $name; # if it's defined as a language name, show that
735 # otherwise, output the language code
741 * @param $name string
744 function specialPage( $name ) {
745 $aliases = $this->getSpecialPageAliases();
746 if ( isset( $aliases[$name][0] ) ) {
747 $name = $aliases[$name][0];
749 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
755 function getDatePreferences() {
756 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
762 function getDateFormats() {
763 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
767 * @return array|string
769 function getDefaultDateFormat() {
770 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
771 if ( $df === 'dmy or mdy' ) {
772 global $wgAmericanDates;
773 return $wgAmericanDates ?
'mdy' : 'dmy';
782 function getDatePreferenceMigrationMap() {
783 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
790 function getImageFile( $image ) {
791 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
797 function getExtraUserToggles() {
798 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
805 function getUserToggle( $tog ) {
806 return $this->getMessageFromDB( "tog-$tog" );
810 * Get native language names, indexed by code.
811 * Only those defined in MediaWiki, no other data like CLDR.
812 * If $customisedOnly is true, only returns codes with a messages file
814 * @param $customisedOnly bool
817 * @deprecated in 1.20, use fetchLanguageNames()
819 public static function getLanguageNames( $customisedOnly = false ) {
820 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
824 * Get translated language names. This is done on best effort and
825 * by default this is exactly the same as Language::getLanguageNames.
826 * The CLDR extension provides translated names.
827 * @param $code String Language code.
828 * @return Array language code => language name
830 * @deprecated in 1.20, use fetchLanguageNames()
832 public static function getTranslatedLanguageNames( $code ) {
833 return self
::fetchLanguageNames( $code, 'all' );
837 * Get an array of language names, indexed by code.
838 * @param $inLanguage null|string: Code of language in which to return the names
839 * Use null for autonyms (native names)
840 * @param $include string:
841 * 'all' all available languages
842 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
843 * 'mwfile' only if the language is in 'mw' *and* has a message file
844 * @return array: language code => language name
847 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
848 global $wgExtraLanguageNames;
849 static $coreLanguageNames;
851 if ( $coreLanguageNames === null ) {
852 include MWInit
::compiledPath( 'languages/Names.php' );
858 # TODO: also include when $inLanguage is null, when this code is more efficient
859 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
862 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
863 foreach ( $mwNames as $mwCode => $mwName ) {
864 # - Prefer own MediaWiki native name when not using the hook
865 # - For other names just add if not added through the hook
866 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
867 $names[$mwCode] = $mwName;
871 if ( $include === 'all' ) {
876 $coreCodes = array_keys( $mwNames );
877 foreach ( $coreCodes as $coreCode ) {
878 $returnMw[$coreCode] = $names[$coreCode];
881 if ( $include === 'mwfile' ) {
882 $namesMwFile = array();
883 # We do this using a foreach over the codes instead of a directory
884 # loop so that messages files in extensions will work correctly.
885 foreach ( $returnMw as $code => $value ) {
886 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
887 $namesMwFile[$code] = $names[$code];
892 # 'mw' option; default if it's not one of the other two options (all/mwfile)
897 * @param $code string: The code of the language for which to get the name
898 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
899 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
900 * @return string: Language name or empty
903 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
904 $array = self
::fetchLanguageNames( $inLanguage, $include );
905 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
909 * Get a message from the MediaWiki namespace.
911 * @param $msg String: message name
914 function getMessageFromDB( $msg ) {
915 return wfMessage( $msg )->inLanguage( $this )->text();
919 * Get the native language name of $code.
920 * Only if defined in MediaWiki, no other data like CLDR.
921 * @param $code string
923 * @deprecated in 1.20, use fetchLanguageName()
925 function getLanguageName( $code ) {
926 return self
::fetchLanguageName( $code );
933 function getMonthName( $key ) {
934 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
940 function getMonthNamesArray() {
941 $monthNames = array( '' );
942 for ( $i = 1; $i < 13; $i++
) {
943 $monthNames[] = $this->getMonthName( $i );
952 function getMonthNameGen( $key ) {
953 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
960 function getMonthAbbreviation( $key ) {
961 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
967 function getMonthAbbreviationsArray() {
968 $monthNames = array( '' );
969 for ( $i = 1; $i < 13; $i++
) {
970 $monthNames[] = $this->getMonthAbbreviation( $i );
979 function getWeekdayName( $key ) {
980 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
987 function getWeekdayAbbreviation( $key ) {
988 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
995 function getIranianCalendarMonthName( $key ) {
996 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1000 * @param $key string
1003 function getHebrewCalendarMonthName( $key ) {
1004 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1008 * @param $key string
1011 function getHebrewCalendarMonthNameGen( $key ) {
1012 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1016 * @param $key string
1019 function getHijriCalendarMonthName( $key ) {
1020 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1024 * This is a workalike of PHP's date() function, but with better
1025 * internationalisation, a reduced set of format characters, and a better
1028 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1029 * the PHP manual for definitions. There are a number of extensions, which
1032 * xn Do not translate digits of the next numeric format character
1033 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1034 * xr Use roman numerals for the next numeric format character
1035 * xh Use hebrew numerals for the next numeric format character
1037 * xg Genitive month name
1039 * xij j (day number) in Iranian calendar
1040 * xiF F (month name) in Iranian calendar
1041 * xin n (month number) in Iranian calendar
1042 * xiy y (two digit year) in Iranian calendar
1043 * xiY Y (full year) in Iranian calendar
1045 * xjj j (day number) in Hebrew calendar
1046 * xjF F (month name) in Hebrew calendar
1047 * xjt t (days in month) in Hebrew calendar
1048 * xjx xg (genitive month name) in Hebrew calendar
1049 * xjn n (month number) in Hebrew calendar
1050 * xjY Y (full year) in Hebrew calendar
1052 * xmj j (day number) in Hijri calendar
1053 * xmF F (month name) in Hijri calendar
1054 * xmn n (month number) in Hijri calendar
1055 * xmY Y (full year) in Hijri calendar
1057 * xkY Y (full year) in Thai solar calendar. Months and days are
1058 * identical to the Gregorian calendar
1059 * xoY Y (full year) in Minguo calendar or Juche year.
1060 * Months and days are identical to the
1061 * Gregorian calendar
1062 * xtY Y (full year) in Japanese nengo. Months and days are
1063 * identical to the Gregorian calendar
1065 * Characters enclosed in double quotes will be considered literal (with
1066 * the quotes themselves removed). Unmatched quotes will be considered
1067 * literal quotes. Example:
1069 * "The month is" F => The month is January
1072 * Backslash escaping is also supported.
1074 * Input timestamp is assumed to be pre-normalized to the desired local
1075 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1076 * $ts is UTC if $zone is not given.
1078 * @param $format String
1079 * @param $ts String: 14-character timestamp
1082 * @param $zone DateTimeZone: Timezone of $ts
1083 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1085 * @throws MWException
1088 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1093 $dateTimeObj = false;
1102 if ( strlen( $ts ) !== 14 ) {
1103 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1106 if ( !ctype_digit( $ts ) ) {
1107 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1110 for ( $p = 0; $p < strlen( $format ); $p++
) {
1112 $code = $format[$p];
1113 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1114 $code .= $format[++
$p];
1117 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1118 $code .= $format[++
$p];
1129 $rawToggle = !$rawToggle;
1138 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1142 $hebrew = self
::tsToHebrew( $ts );
1144 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1147 $num = substr( $ts, 6, 2 );
1150 if ( !$dateTimeObj ) {
1151 $dateTimeObj = DateTime
::createFromFormat(
1152 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1155 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1158 $num = intval( substr( $ts, 6, 2 ) );
1162 $iranian = self
::tsToIranian( $ts );
1168 $hijri = self
::tsToHijri( $ts );
1174 $hebrew = self
::tsToHebrew( $ts );
1179 if ( !$dateTimeObj ) {
1180 $dateTimeObj = DateTime
::createFromFormat(
1181 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1184 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1187 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1191 $iranian = self
::tsToIranian( $ts );
1193 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1197 $hijri = self
::tsToHijri( $ts );
1199 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1203 $hebrew = self
::tsToHebrew( $ts );
1205 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1208 $num = substr( $ts, 4, 2 );
1211 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1214 $num = intval( substr( $ts, 4, 2 ) );
1218 $iranian = self
::tsToIranian( $ts );
1224 $hijri = self
::tsToHijri ( $ts );
1230 $hebrew = self
::tsToHebrew( $ts );
1236 $hebrew = self
::tsToHebrew( $ts );
1241 $num = substr( $ts, 0, 4 );
1245 $iranian = self
::tsToIranian( $ts );
1251 $hijri = self
::tsToHijri( $ts );
1257 $hebrew = self
::tsToHebrew( $ts );
1263 $thai = self
::tsToYear( $ts, 'thai' );
1269 $minguo = self
::tsToYear( $ts, 'minguo' );
1275 $tenno = self
::tsToYear( $ts, 'tenno' );
1280 $num = substr( $ts, 2, 2 );
1284 $iranian = self
::tsToIranian( $ts );
1286 $num = substr( $iranian[0], -2 );
1289 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1292 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1295 $h = substr( $ts, 8, 2 );
1296 $num = $h %
12 ?
$h %
12 : 12;
1299 $num = intval( substr( $ts, 8, 2 ) );
1302 $h = substr( $ts, 8, 2 );
1303 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1306 $num = substr( $ts, 8, 2 );
1309 $num = substr( $ts, 10, 2 );
1312 $num = substr( $ts, 12, 2 );
1320 // Pass through string from $dateTimeObj->format()
1321 if ( !$dateTimeObj ) {
1322 $dateTimeObj = DateTime
::createFromFormat(
1323 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1326 $s .= $dateTimeObj->format( $code );
1338 // Pass through number from $dateTimeObj->format()
1339 if ( !$dateTimeObj ) {
1340 $dateTimeObj = DateTime
::createFromFormat(
1341 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1344 $num = $dateTimeObj->format( $code );
1347 # Backslash escaping
1348 if ( $p < strlen( $format ) - 1 ) {
1349 $s .= $format[++
$p];
1356 if ( $p < strlen( $format ) - 1 ) {
1357 $endQuote = strpos( $format, '"', $p +
1 );
1358 if ( $endQuote === false ) {
1359 # No terminating quote, assume literal "
1362 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1366 # Quote at end of string, assume literal "
1373 if ( $num !== false ) {
1374 if ( $rawToggle ||
$raw ) {
1377 } elseif ( $roman ) {
1378 $s .= Language
::romanNumeral( $num );
1380 } elseif ( $hebrewNum ) {
1381 $s .= self
::hebrewNumeral( $num );
1384 $s .= $this->formatNum( $num, true );
1391 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1392 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1395 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1396 * Gregorian dates to Iranian dates. Originally written in C, it
1397 * is released under the terms of GNU Lesser General Public
1398 * License. Conversion to PHP was performed by Niklas Laxström.
1400 * Link: http://www.farsiweb.info/jalali/jalali.c
1406 private static function tsToIranian( $ts ) {
1407 $gy = substr( $ts, 0, 4 ) -1600;
1408 $gm = substr( $ts, 4, 2 ) -1;
1409 $gd = substr( $ts, 6, 2 ) -1;
1411 # Days passed from the beginning (including leap years)
1413 +
floor( ( $gy +
3 ) / 4 )
1414 - floor( ( $gy +
99 ) / 100 )
1415 +
floor( ( $gy +
399 ) / 400 );
1417 // Add days of the past months of this year
1418 for ( $i = 0; $i < $gm; $i++
) {
1419 $gDayNo +
= self
::$GREG_DAYS[$i];
1423 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1427 // Days passed in current month
1428 $gDayNo +
= (int)$gd;
1430 $jDayNo = $gDayNo - 79;
1432 $jNp = floor( $jDayNo / 12053 );
1435 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1438 if ( $jDayNo >= 366 ) {
1439 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1440 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1443 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1444 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1450 return array( $jy, $jm, $jd );
1454 * Converting Gregorian dates to Hijri dates.
1456 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1458 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1464 private static function tsToHijri( $ts ) {
1465 $year = substr( $ts, 0, 4 );
1466 $month = substr( $ts, 4, 2 );
1467 $day = substr( $ts, 6, 2 );
1475 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1476 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1479 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1480 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1481 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1484 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1485 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1488 $zl = $zjd -1948440 +
10632;
1489 $zn = (int)( ( $zl - 1 ) / 10631 );
1490 $zl = $zl - 10631 * $zn +
354;
1491 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1492 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1493 $zm = (int)( ( 24 * $zl ) / 709 );
1494 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1495 $zy = 30 * $zn +
$zj - 30;
1497 return array( $zy, $zm, $zd );
1501 * Converting Gregorian dates to Hebrew dates.
1503 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1504 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1505 * to translate the relevant functions into PHP and release them under
1508 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1509 * and Adar II is 14. In a non-leap year, Adar is 6.
1515 private static function tsToHebrew( $ts ) {
1517 $year = substr( $ts, 0, 4 );
1518 $month = substr( $ts, 4, 2 );
1519 $day = substr( $ts, 6, 2 );
1521 # Calculate Hebrew year
1522 $hebrewYear = $year +
3760;
1524 # Month number when September = 1, August = 12
1526 if ( $month > 12 ) {
1533 # Calculate day of year from 1 September
1535 for ( $i = 1; $i < $month; $i++
) {
1539 # Check if the year is leap
1540 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1543 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1550 # Calculate the start of the Hebrew year
1551 $start = self
::hebrewYearStart( $hebrewYear );
1553 # Calculate next year's start
1554 if ( $dayOfYear <= $start ) {
1555 # Day is before the start of the year - it is the previous year
1557 $nextStart = $start;
1561 # Add days since previous year's 1 September
1563 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1567 # Start of the new (previous) year
1568 $start = self
::hebrewYearStart( $hebrewYear );
1571 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1574 # Calculate Hebrew day of year
1575 $hebrewDayOfYear = $dayOfYear - $start;
1577 # Difference between year's days
1578 $diff = $nextStart - $start;
1579 # Add 12 (or 13 for leap years) days to ignore the difference between
1580 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1581 # difference is only about the year type
1582 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1588 # Check the year pattern, and is leap year
1589 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1590 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1591 # and non-leap years
1592 $yearPattern = $diff %
30;
1593 # Check if leap year
1594 $isLeap = $diff >= 30;
1596 # Calculate day in the month from number of day in the Hebrew year
1597 # Don't check Adar - if the day is not in Adar, we will stop before;
1598 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1599 $hebrewDay = $hebrewDayOfYear;
1602 while ( $hebrewMonth <= 12 ) {
1603 # Calculate days in this month
1604 if ( $isLeap && $hebrewMonth == 6 ) {
1605 # Adar in a leap year
1607 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1609 if ( $hebrewDay <= $days ) {
1613 # Subtract the days of Adar I
1614 $hebrewDay -= $days;
1617 if ( $hebrewDay <= $days ) {
1623 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1624 # Cheshvan in a complete year (otherwise as the rule below)
1626 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1627 # Kislev in an incomplete year (otherwise as the rule below)
1630 # Odd months have 30 days, even have 29
1631 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1633 if ( $hebrewDay <= $days ) {
1634 # In the current month
1637 # Subtract the days of the current month
1638 $hebrewDay -= $days;
1639 # Try in the next month
1644 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1648 * This calculates the Hebrew year start, as days since 1 September.
1649 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1650 * Used for Hebrew date.
1656 private static function hebrewYearStart( $year ) {
1657 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1658 $b = intval( ( $year - 1 ) %
4 );
1659 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1663 $Mar = intval( $m );
1669 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1670 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1672 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1674 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1678 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1683 * Algorithm to convert Gregorian dates to Thai solar dates,
1684 * Minguo dates or Minguo dates.
1686 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1687 * http://en.wikipedia.org/wiki/Minguo_calendar
1688 * http://en.wikipedia.org/wiki/Japanese_era_name
1690 * @param $ts String: 14-character timestamp
1691 * @param $cName String: calender name
1692 * @return Array: converted year, month, day
1694 private static function tsToYear( $ts, $cName ) {
1695 $gy = substr( $ts, 0, 4 );
1696 $gm = substr( $ts, 4, 2 );
1697 $gd = substr( $ts, 6, 2 );
1699 if ( !strcmp( $cName, 'thai' ) ) {
1701 # Add 543 years to the Gregorian calendar
1702 # Months and days are identical
1703 $gy_offset = $gy +
543;
1704 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1706 # Deduct 1911 years from the Gregorian calendar
1707 # Months and days are identical
1708 $gy_offset = $gy - 1911;
1709 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1710 # Nengō dates up to Meiji period
1711 # Deduct years from the Gregorian calendar
1712 # depending on the nengo periods
1713 # Months and days are identical
1714 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1716 $gy_gannen = $gy - 1868 +
1;
1717 $gy_offset = $gy_gannen;
1718 if ( $gy_gannen == 1 ) {
1721 $gy_offset = '明治' . $gy_offset;
1723 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1724 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1725 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1726 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1727 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1731 $gy_gannen = $gy - 1912 +
1;
1732 $gy_offset = $gy_gannen;
1733 if ( $gy_gannen == 1 ) {
1736 $gy_offset = '大正' . $gy_offset;
1738 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1739 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1740 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1744 $gy_gannen = $gy - 1926 +
1;
1745 $gy_offset = $gy_gannen;
1746 if ( $gy_gannen == 1 ) {
1749 $gy_offset = '昭和' . $gy_offset;
1752 $gy_gannen = $gy - 1989 +
1;
1753 $gy_offset = $gy_gannen;
1754 if ( $gy_gannen == 1 ) {
1757 $gy_offset = '平成' . $gy_offset;
1763 return array( $gy_offset, $gm, $gd );
1767 * Roman number formatting up to 10000
1773 static function romanNumeral( $num ) {
1774 static $table = array(
1775 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1776 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1777 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1778 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1781 $num = intval( $num );
1782 if ( $num > 10000 ||
$num <= 0 ) {
1787 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1788 if ( $num >= $pow10 ) {
1789 $s .= $table[$i][(int)floor( $num / $pow10 )];
1791 $num = $num %
$pow10;
1797 * Hebrew Gematria number formatting up to 9999
1803 static function hebrewNumeral( $num ) {
1804 static $table = array(
1805 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1806 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1807 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1808 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1811 $num = intval( $num );
1812 if ( $num > 9999 ||
$num <= 0 ) {
1817 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1818 if ( $num >= $pow10 ) {
1819 if ( $num == 15 ||
$num == 16 ) {
1820 $s .= $table[0][9] . $table[0][$num - 9];
1823 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1824 if ( $pow10 == 1000 ) {
1829 $num = $num %
$pow10;
1831 if ( strlen( $s ) == 2 ) {
1834 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1835 $str .= substr( $s, strlen( $s ) - 2, 2 );
1837 $start = substr( $str, 0, strlen( $str ) - 2 );
1838 $end = substr( $str, strlen( $str ) - 2 );
1841 $str = $start . 'ך';
1844 $str = $start . 'ם';
1847 $str = $start . 'ן';
1850 $str = $start . 'ף';
1853 $str = $start . 'ץ';
1860 * Used by date() and time() to adjust the time output.
1862 * @param $ts Int the time in date('YmdHis') format
1863 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1864 * get user timecorrection setting)
1867 function userAdjust( $ts, $tz = false ) {
1868 global $wgUser, $wgLocalTZoffset;
1870 if ( $tz === false ) {
1871 $tz = $wgUser->getOption( 'timecorrection' );
1874 $data = explode( '|', $tz, 3 );
1876 if ( $data[0] == 'ZoneInfo' ) {
1877 wfSuppressWarnings();
1878 $userTZ = timezone_open( $data[2] );
1879 wfRestoreWarnings();
1880 if ( $userTZ !== false ) {
1881 $date = date_create( $ts, timezone_open( 'UTC' ) );
1882 date_timezone_set( $date, $userTZ );
1883 $date = date_format( $date, 'YmdHis' );
1886 # Unrecognized timezone, default to 'Offset' with the stored offset.
1887 $data[0] = 'Offset';
1891 if ( $data[0] == 'System' ||
$tz == '' ) {
1892 # Global offset in minutes.
1893 if ( isset( $wgLocalTZoffset ) ) {
1894 $minDiff = $wgLocalTZoffset;
1896 } elseif ( $data[0] == 'Offset' ) {
1897 $minDiff = intval( $data[1] );
1899 $data = explode( ':', $tz );
1900 if ( count( $data ) == 2 ) {
1901 $data[0] = intval( $data[0] );
1902 $data[1] = intval( $data[1] );
1903 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1904 if ( $data[0] < 0 ) {
1905 $minDiff = -$minDiff;
1908 $minDiff = intval( $data[0] ) * 60;
1912 # No difference ? Return time unchanged
1913 if ( 0 == $minDiff ) {
1917 wfSuppressWarnings(); // E_STRICT system time bitching
1918 # Generate an adjusted date; take advantage of the fact that mktime
1919 # will normalize out-of-range values so we don't have to split $minDiff
1920 # into hours and minutes.
1922 (int)substr( $ts, 8, 2 ) ), # Hours
1923 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1924 (int)substr( $ts, 12, 2 ), # Seconds
1925 (int)substr( $ts, 4, 2 ), # Month
1926 (int)substr( $ts, 6, 2 ), # Day
1927 (int)substr( $ts, 0, 4 ) ); # Year
1929 $date = date( 'YmdHis', $t );
1930 wfRestoreWarnings();
1936 * This is meant to be used by time(), date(), and timeanddate() to get
1937 * the date preference they're supposed to use, it should be used in
1941 * function timeanddate([...], $format = true) {
1942 * $datePreference = $this->dateFormat($format);
1947 * @param $usePrefs Mixed: if true, the user's preference is used
1948 * if false, the site/language default is used
1949 * if int/string, assumed to be a format.
1952 function dateFormat( $usePrefs = true ) {
1955 if ( is_bool( $usePrefs ) ) {
1957 $datePreference = $wgUser->getDatePreference();
1959 $datePreference = (string)User
::getDefaultOption( 'date' );
1962 $datePreference = (string)$usePrefs;
1966 if ( $datePreference == '' ) {
1970 return $datePreference;
1974 * Get a format string for a given type and preference
1975 * @param $type string May be date, time or both
1976 * @param $pref string The format name as it appears in Messages*.php
1978 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1982 function getDateFormatString( $type, $pref ) {
1983 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1984 if ( $pref == 'default' ) {
1985 $pref = $this->getDefaultDateFormat();
1986 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1988 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1990 if ( $type === 'pretty' && $df === null ) {
1991 $df = $this->getDateFormatString( 'date', $pref );
1994 if ( $df === null ) {
1995 $pref = $this->getDefaultDateFormat();
1996 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1999 $this->dateFormatStrings
[$type][$pref] = $df;
2001 return $this->dateFormatStrings
[$type][$pref];
2005 * @param $ts Mixed: the time format which needs to be turned into a
2006 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2007 * @param $adj Bool: whether to adjust the time output according to the
2008 * user configured offset ($timecorrection)
2009 * @param $format Mixed: true to use user's date format preference
2010 * @param $timecorrection String|bool the time offset as returned by
2011 * validateTimeZone() in Special:Preferences
2014 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2015 $ts = wfTimestamp( TS_MW
, $ts );
2017 $ts = $this->userAdjust( $ts, $timecorrection );
2019 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2020 return $this->sprintfDate( $df, $ts );
2024 * @param $ts Mixed: the time format which needs to be turned into a
2025 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2026 * @param $adj Bool: whether to adjust the time output according to the
2027 * user configured offset ($timecorrection)
2028 * @param $format Mixed: true to use user's date format preference
2029 * @param $timecorrection String|bool the time offset as returned by
2030 * validateTimeZone() in Special:Preferences
2033 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2034 $ts = wfTimestamp( TS_MW
, $ts );
2036 $ts = $this->userAdjust( $ts, $timecorrection );
2038 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2039 return $this->sprintfDate( $df, $ts );
2043 * @param $ts Mixed: the time format which needs to be turned into a
2044 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2045 * @param $adj Bool: whether to adjust the time output according to the
2046 * user configured offset ($timecorrection)
2047 * @param $format Mixed: what format to return, if it's false output the
2048 * default one (default true)
2049 * @param $timecorrection String|bool the time offset as returned by
2050 * validateTimeZone() in Special:Preferences
2053 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2054 $ts = wfTimestamp( TS_MW
, $ts );
2056 $ts = $this->userAdjust( $ts, $timecorrection );
2058 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2059 return $this->sprintfDate( $df, $ts );
2063 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2067 * @param integer $seconds The amount of seconds.
2068 * @param array $chosenIntervals The intervals to enable.
2072 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2073 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2075 $segments = array();
2077 foreach ( $intervals as $intervalName => $intervalValue ) {
2078 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2079 $segments[] = $message->inLanguage( $this )->escaped();
2082 return $this->listToText( $segments );
2086 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2087 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2091 * @param integer $seconds The amount of seconds.
2092 * @param array $chosenIntervals The intervals to enable.
2096 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2097 if ( empty( $chosenIntervals ) ) {
2098 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2101 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2102 $sortedNames = array_keys( $intervals );
2103 $smallestInterval = array_pop( $sortedNames );
2105 $segments = array();
2107 foreach ( $intervals as $name => $length ) {
2108 $value = floor( $seconds / $length );
2110 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2111 $seconds -= $value * $length;
2112 $segments[$name] = $value;
2120 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2122 * @param $type String: can be 'date', 'time' or 'both'
2123 * @param $ts Mixed: the time format which needs to be turned into a
2124 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2125 * @param $user User object used to get preferences for timezone and format
2126 * @param $options Array, can contain the following keys:
2127 * - 'timecorrection': time correction, can have the following values:
2128 * - true: use user's preference
2129 * - false: don't use time correction
2130 * - integer: value of time correction in minutes
2131 * - 'format': format to use, can have the following values:
2132 * - true: use user's preference
2133 * - false: use default preference
2134 * - string: format to use
2138 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2139 $ts = wfTimestamp( TS_MW
, $ts );
2140 $options +
= array( 'timecorrection' => true, 'format' => true );
2141 if ( $options['timecorrection'] !== false ) {
2142 if ( $options['timecorrection'] === true ) {
2143 $offset = $user->getOption( 'timecorrection' );
2145 $offset = $options['timecorrection'];
2147 $ts = $this->userAdjust( $ts, $offset );
2149 if ( $options['format'] === true ) {
2150 $format = $user->getDatePreference();
2152 $format = $options['format'];
2154 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2155 return $this->sprintfDate( $df, $ts );
2159 * Get the formatted date for the given timestamp and formatted for
2162 * @param $ts Mixed: the time format which needs to be turned into a
2163 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2164 * @param $user User object used to get preferences for timezone and format
2165 * @param $options Array, can contain the following keys:
2166 * - 'timecorrection': time correction, can have the following values:
2167 * - true: use user's preference
2168 * - false: don't use time correction
2169 * - integer: value of time correction in minutes
2170 * - 'format': format to use, can have the following values:
2171 * - true: use user's preference
2172 * - false: use default preference
2173 * - string: format to use
2177 public function userDate( $ts, User
$user, array $options = array() ) {
2178 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2182 * Get the formatted time for the given timestamp and formatted for
2185 * @param $ts Mixed: the time format which needs to be turned into a
2186 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2187 * @param $user User object used to get preferences for timezone and format
2188 * @param $options Array, can contain the following keys:
2189 * - 'timecorrection': time correction, can have the following values:
2190 * - true: use user's preference
2191 * - false: don't use time correction
2192 * - integer: value of time correction in minutes
2193 * - 'format': format to use, can have the following values:
2194 * - true: use user's preference
2195 * - false: use default preference
2196 * - string: format to use
2200 public function userTime( $ts, User
$user, array $options = array() ) {
2201 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2205 * Get the formatted date and time for the given timestamp and formatted for
2208 * @param $ts Mixed: the time format which needs to be turned into a
2209 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2210 * @param $user User object used to get preferences for timezone and format
2211 * @param $options Array, can contain the following keys:
2212 * - 'timecorrection': time correction, can have the following values:
2213 * - true: use user's preference
2214 * - false: don't use time correction
2215 * - integer: value of time correction in minutes
2216 * - 'format': format to use, can have the following values:
2217 * - true: use user's preference
2218 * - false: use default preference
2219 * - string: format to use
2223 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2224 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2228 * Convert an MWTimestamp into a pretty human-readable timestamp using
2229 * the given user preferences and relative base time.
2231 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2232 * on your timestamp object, which will then call this function. Calling
2233 * this function directly will cause hooks to be skipped over.
2235 * @see MWTimestamp::getHumanTimestamp
2236 * @param MWTimestamp $ts Timestamp to prettify
2237 * @param MWTimestamp $relativeTo Base timestamp
2238 * @param User $user User preferences to use
2239 * @return string Human timestamp
2242 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2243 $diff = $ts->diff( $relativeTo );
2244 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) - (int)$relativeTo->timestamp
->format( 'w' ) );
2245 $days = $diff->days ?
: (int)$diffDay;
2246 if ( $diff->invert ||
$days > 5 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' ) ) {
2247 // Timestamps are in different years: use full timestamp
2248 // Also do full timestamp for future dates
2250 * @FIXME Add better handling of future timestamps.
2252 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2253 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2254 } elseif ( $days > 5 ) {
2255 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2256 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2257 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2258 } elseif ( $days > 1 ) {
2259 // Timestamp within the past week: show the day of the week and time
2260 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2261 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2262 $ts = wfMessage( "$weekday-at" )
2263 ->inLanguage( $this )
2264 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2266 } elseif ( $days == 1 ) {
2267 // Timestamp was yesterday: say 'yesterday' and the time.
2268 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2269 $ts = wfMessage( 'yesterday-at' )
2270 ->inLanguage( $this )
2271 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2273 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2274 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2275 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2276 $ts = wfMessage( 'today-at' )
2277 ->inLanguage( $this )
2278 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2281 // From here on in, the timestamp was soon enough ago so that we can simply say
2282 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2283 } elseif ( $diff->h
== 1 ) {
2284 // Less than 90 minutes, but more than an hour ago.
2285 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2286 } elseif ( $diff->i
>= 1 ) {
2287 // A few minutes ago.
2288 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2289 } elseif ( $diff->s
>= 30 ) {
2290 // Less than a minute, but more than 30 sec ago.
2291 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2293 // Less than 30 seconds ago.
2294 $ts = wfMessage( 'just-now' )->text();
2301 * @param $key string
2302 * @return array|null
2304 function getMessage( $key ) {
2305 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2311 function getAllMessages() {
2312 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2321 function iconv( $in, $out, $string ) {
2322 # This is a wrapper for iconv in all languages except esperanto,
2323 # which does some nasty x-conversions beforehand
2325 # Even with //IGNORE iconv can whine about illegal characters in
2326 # *input* string. We just ignore those too.
2327 # REF: http://bugs.php.net/bug.php?id=37166
2328 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2329 wfSuppressWarnings();
2330 $text = iconv( $in, $out . '//IGNORE', $string );
2331 wfRestoreWarnings();
2335 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2338 * @param $matches array
2339 * @return mixed|string
2341 function ucwordbreaksCallbackAscii( $matches ) {
2342 return $this->ucfirst( $matches[1] );
2346 * @param $matches array
2349 function ucwordbreaksCallbackMB( $matches ) {
2350 return mb_strtoupper( $matches[0] );
2354 * @param $matches array
2357 function ucCallback( $matches ) {
2358 list( $wikiUpperChars ) = self
::getCaseMaps();
2359 return strtr( $matches[1], $wikiUpperChars );
2363 * @param $matches array
2366 function lcCallback( $matches ) {
2367 list( , $wikiLowerChars ) = self
::getCaseMaps();
2368 return strtr( $matches[1], $wikiLowerChars );
2372 * @param $matches array
2375 function ucwordsCallbackMB( $matches ) {
2376 return mb_strtoupper( $matches[0] );
2380 * @param $matches array
2383 function ucwordsCallbackWiki( $matches ) {
2384 list( $wikiUpperChars ) = self
::getCaseMaps();
2385 return strtr( $matches[0], $wikiUpperChars );
2389 * Make a string's first character uppercase
2391 * @param $str string
2395 function ucfirst( $str ) {
2397 if ( $o < 96 ) { // if already uppercase...
2399 } elseif ( $o < 128 ) {
2400 return ucfirst( $str ); // use PHP's ucfirst()
2402 // fall back to more complex logic in case of multibyte strings
2403 return $this->uc( $str, true );
2408 * Convert a string to uppercase
2410 * @param $str string
2411 * @param $first bool
2415 function uc( $str, $first = false ) {
2416 if ( function_exists( 'mb_strtoupper' ) ) {
2418 if ( $this->isMultibyte( $str ) ) {
2419 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2421 return ucfirst( $str );
2424 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2427 if ( $this->isMultibyte( $str ) ) {
2428 $x = $first ?
'^' : '';
2429 return preg_replace_callback(
2430 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2431 array( $this, 'ucCallback' ),
2435 return $first ?
ucfirst( $str ) : strtoupper( $str );
2441 * @param $str string
2442 * @return mixed|string
2444 function lcfirst( $str ) {
2447 return strval( $str );
2448 } elseif ( $o >= 128 ) {
2449 return $this->lc( $str, true );
2450 } elseif ( $o > 96 ) {
2453 $str[0] = strtolower( $str[0] );
2459 * @param $str string
2460 * @param $first bool
2461 * @return mixed|string
2463 function lc( $str, $first = false ) {
2464 if ( function_exists( 'mb_strtolower' ) ) {
2466 if ( $this->isMultibyte( $str ) ) {
2467 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2469 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2472 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2475 if ( $this->isMultibyte( $str ) ) {
2476 $x = $first ?
'^' : '';
2477 return preg_replace_callback(
2478 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2479 array( $this, 'lcCallback' ),
2483 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2489 * @param $str string
2492 function isMultibyte( $str ) {
2493 return (bool)preg_match( '/[\x80-\xff]/', $str );
2497 * @param $str string
2498 * @return mixed|string
2500 function ucwords( $str ) {
2501 if ( $this->isMultibyte( $str ) ) {
2502 $str = $this->lc( $str );
2504 // regexp to find first letter in each word (i.e. after each space)
2505 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2507 // function to use to capitalize a single char
2508 if ( function_exists( 'mb_strtoupper' ) ) {
2509 return preg_replace_callback(
2511 array( $this, 'ucwordsCallbackMB' ),
2515 return preg_replace_callback(
2517 array( $this, 'ucwordsCallbackWiki' ),
2522 return ucwords( strtolower( $str ) );
2527 * capitalize words at word breaks
2529 * @param $str string
2532 function ucwordbreaks( $str ) {
2533 if ( $this->isMultibyte( $str ) ) {
2534 $str = $this->lc( $str );
2536 // since \b doesn't work for UTF-8, we explicitely define word break chars
2537 $breaks = "[ \-\(\)\}\{\.,\?!]";
2539 // find first letter after word break
2540 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2542 if ( function_exists( 'mb_strtoupper' ) ) {
2543 return preg_replace_callback(
2545 array( $this, 'ucwordbreaksCallbackMB' ),
2549 return preg_replace_callback(
2551 array( $this, 'ucwordsCallbackWiki' ),
2556 return preg_replace_callback(
2557 '/\b([\w\x80-\xff]+)\b/',
2558 array( $this, 'ucwordbreaksCallbackAscii' ),
2565 * Return a case-folded representation of $s
2567 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2568 * and $s2 are the same except for the case of their characters. It is not
2569 * necessary for the value returned to make sense when displayed.
2571 * Do *not* perform any other normalisation in this function. If a caller
2572 * uses this function when it should be using a more general normalisation
2573 * function, then fix the caller.
2579 function caseFold( $s ) {
2580 return $this->uc( $s );
2587 function checkTitleEncoding( $s ) {
2588 if ( is_array( $s ) ) {
2589 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2591 if ( StringUtils
::isUtf8( $s ) ) {
2595 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2601 function fallback8bitEncoding() {
2602 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2606 * Most writing systems use whitespace to break up words.
2607 * Some languages such as Chinese don't conventionally do this,
2608 * which requires special handling when breaking up words for
2613 function hasWordBreaks() {
2618 * Some languages such as Chinese require word segmentation,
2619 * Specify such segmentation when overridden in derived class.
2621 * @param $string String
2624 function segmentByWord( $string ) {
2629 * Some languages have special punctuation need to be normalized.
2630 * Make such changes here.
2632 * @param $string String
2635 function normalizeForSearch( $string ) {
2636 return self
::convertDoubleWidth( $string );
2640 * convert double-width roman characters to single-width.
2641 * range: ff00-ff5f ~= 0020-007f
2643 * @param $string string
2647 protected static function convertDoubleWidth( $string ) {
2648 static $full = null;
2649 static $half = null;
2651 if ( $full === null ) {
2652 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2653 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2654 $full = str_split( $fullWidth, 3 );
2655 $half = str_split( $halfWidth );
2658 $string = str_replace( $full, $half, $string );
2663 * @param $string string
2664 * @param $pattern string
2667 protected static function insertSpace( $string, $pattern ) {
2668 $string = preg_replace( $pattern, " $1 ", $string );
2669 $string = preg_replace( '/ +/', ' ', $string );
2674 * @param $termsArray array
2677 function convertForSearchResult( $termsArray ) {
2678 # some languages, e.g. Chinese, need to do a conversion
2679 # in order for search results to be displayed correctly
2684 * Get the first character of a string.
2689 function firstChar( $s ) {
2692 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2693 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2698 if ( isset( $matches[1] ) ) {
2699 if ( strlen( $matches[1] ) != 3 ) {
2703 // Break down Hangul syllables to grab the first jamo
2704 $code = utf8ToCodepoint( $matches[1] );
2705 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2707 } elseif ( $code < 0xb098 ) {
2708 return "\xe3\x84\xb1";
2709 } elseif ( $code < 0xb2e4 ) {
2710 return "\xe3\x84\xb4";
2711 } elseif ( $code < 0xb77c ) {
2712 return "\xe3\x84\xb7";
2713 } elseif ( $code < 0xb9c8 ) {
2714 return "\xe3\x84\xb9";
2715 } elseif ( $code < 0xbc14 ) {
2716 return "\xe3\x85\x81";
2717 } elseif ( $code < 0xc0ac ) {
2718 return "\xe3\x85\x82";
2719 } elseif ( $code < 0xc544 ) {
2720 return "\xe3\x85\x85";
2721 } elseif ( $code < 0xc790 ) {
2722 return "\xe3\x85\x87";
2723 } elseif ( $code < 0xcc28 ) {
2724 return "\xe3\x85\x88";
2725 } elseif ( $code < 0xce74 ) {
2726 return "\xe3\x85\x8a";
2727 } elseif ( $code < 0xd0c0 ) {
2728 return "\xe3\x85\x8b";
2729 } elseif ( $code < 0xd30c ) {
2730 return "\xe3\x85\x8c";
2731 } elseif ( $code < 0xd558 ) {
2732 return "\xe3\x85\x8d";
2734 return "\xe3\x85\x8e";
2741 function initEncoding() {
2742 # Some languages may have an alternate char encoding option
2743 # (Esperanto X-coding, Japanese furigana conversion, etc)
2744 # If this language is used as the primary content language,
2745 # an override to the defaults can be set here on startup.
2752 function recodeForEdit( $s ) {
2753 # For some languages we'll want to explicitly specify
2754 # which characters make it into the edit box raw
2755 # or are converted in some way or another.
2756 global $wgEditEncoding;
2757 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2760 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2768 function recodeInput( $s ) {
2769 # Take the previous into account.
2770 global $wgEditEncoding;
2771 if ( $wgEditEncoding != '' ) {
2772 $enc = $wgEditEncoding;
2776 if ( $enc == 'UTF-8' ) {
2779 return $this->iconv( $enc, 'UTF-8', $s );
2784 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2785 * also cleans up certain backwards-compatible sequences, converting them
2786 * to the modern Unicode equivalent.
2788 * This is language-specific for performance reasons only.
2794 function normalize( $s ) {
2795 global $wgAllUnicodeFixes;
2796 $s = UtfNormal
::cleanUp( $s );
2797 if ( $wgAllUnicodeFixes ) {
2798 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2799 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2806 * Transform a string using serialized data stored in the given file (which
2807 * must be in the serialized subdirectory of $IP). The file contains pairs
2808 * mapping source characters to destination characters.
2810 * The data is cached in process memory. This will go faster if you have the
2811 * FastStringSearch extension.
2813 * @param $file string
2814 * @param $string string
2816 * @throws MWException
2819 function transformUsingPairFile( $file, $string ) {
2820 if ( !isset( $this->transformData
[$file] ) ) {
2821 $data = wfGetPrecompiledData( $file );
2822 if ( $data === false ) {
2823 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2825 $this->transformData
[$file] = new ReplacementArray( $data );
2827 return $this->transformData
[$file]->replace( $string );
2831 * For right-to-left language support
2836 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2840 * Return the correct HTML 'dir' attribute value for this language.
2844 return $this->isRTL() ?
'rtl' : 'ltr';
2848 * Return 'left' or 'right' as appropriate alignment for line-start
2849 * for this language's text direction.
2851 * Should be equivalent to CSS3 'start' text-align value....
2855 function alignStart() {
2856 return $this->isRTL() ?
'right' : 'left';
2860 * Return 'right' or 'left' as appropriate alignment for line-end
2861 * for this language's text direction.
2863 * Should be equivalent to CSS3 'end' text-align value....
2867 function alignEnd() {
2868 return $this->isRTL() ?
'left' : 'right';
2872 * A hidden direction mark (LRM or RLM), depending on the language direction.
2873 * Unlike getDirMark(), this function returns the character as an HTML entity.
2874 * This function should be used when the output is guaranteed to be HTML,
2875 * because it makes the output HTML source code more readable. When
2876 * the output is plain text or can be escaped, getDirMark() should be used.
2878 * @param $opposite Boolean Get the direction mark opposite to your language
2882 function getDirMarkEntity( $opposite = false ) {
2884 return $this->isRTL() ?
'‎' : '‏';
2886 return $this->isRTL() ?
'‏' : '‎';
2890 * A hidden direction mark (LRM or RLM), depending on the language direction.
2891 * This function produces them as invisible Unicode characters and
2892 * the output may be hard to read and debug, so it should only be used
2893 * when the output is plain text or can be escaped. When the output is
2894 * HTML, use getDirMarkEntity() instead.
2896 * @param $opposite Boolean Get the direction mark opposite to your language
2899 function getDirMark( $opposite = false ) {
2900 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2901 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2903 return $this->isRTL() ?
$lrm : $rlm;
2905 return $this->isRTL() ?
$rlm : $lrm;
2911 function capitalizeAllNouns() {
2912 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2916 * An arrow, depending on the language direction.
2918 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2921 function getArrow( $direction = 'forwards' ) {
2922 switch ( $direction ) {
2924 return $this->isRTL() ?
'←' : '→';
2926 return $this->isRTL() ?
'→' : '←';
2939 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2943 function linkPrefixExtension() {
2944 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2950 function getMagicWords() {
2951 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2954 protected function doMagicHook() {
2955 if ( $this->mMagicHookDone
) {
2958 $this->mMagicHookDone
= true;
2959 wfProfileIn( 'LanguageGetMagic' );
2960 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2961 wfProfileOut( 'LanguageGetMagic' );
2965 * Fill a MagicWord object with data from here
2969 function getMagic( $mw ) {
2970 $this->doMagicHook();
2972 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2973 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2975 $magicWords = $this->getMagicWords();
2976 if ( isset( $magicWords[$mw->mId
] ) ) {
2977 $rawEntry = $magicWords[$mw->mId
];
2983 if ( !is_array( $rawEntry ) ) {
2984 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2986 $mw->mCaseSensitive
= $rawEntry[0];
2987 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2992 * Add magic words to the extension array
2994 * @param $newWords array
2996 function addMagicWordsByLang( $newWords ) {
2997 $fallbackChain = $this->getFallbackLanguages();
2998 $fallbackChain = array_reverse( $fallbackChain );
2999 foreach ( $fallbackChain as $code ) {
3000 if ( isset( $newWords[$code] ) ) {
3001 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3007 * Get special page names, as an associative array
3008 * case folded alias => real name
3010 function getSpecialPageAliases() {
3011 // Cache aliases because it may be slow to load them
3012 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3014 $this->mExtendedSpecialPageAliases
=
3015 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3016 wfRunHooks( 'LanguageGetSpecialPageAliases',
3017 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3020 return $this->mExtendedSpecialPageAliases
;
3024 * Italic is unsuitable for some languages
3026 * @param $text String: the text to be emphasized.
3029 function emphasize( $text ) {
3030 return "<em>$text</em>";
3034 * Normally we output all numbers in plain en_US style, that is
3035 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3036 * point twohundredthirtyfive. However this is not suitable for all
3037 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3038 * Icelandic just want to use commas instead of dots, and dots instead
3039 * of commas like "293.291,235".
3041 * An example of this function being called:
3043 * wfMessage( 'message' )->numParams( $num )->text()
3046 * See LanguageGu.php for the Gujarati implementation and
3047 * $separatorTransformTable on MessageIs.php for
3048 * the , => . and . => , implementation.
3050 * @todo check if it's viable to use localeconv() for the decimal
3052 * @param $number Mixed: the string to be formatted, should be an integer
3053 * or a floating point number.
3054 * @param $nocommafy Bool: set to true for special numbers like dates
3057 public function formatNum( $number, $nocommafy = false ) {
3058 global $wgTranslateNumerals;
3059 if ( !$nocommafy ) {
3060 $number = $this->commafy( $number );
3061 $s = $this->separatorTransformTable();
3063 $number = strtr( $number, $s );
3067 if ( $wgTranslateNumerals ) {
3068 $s = $this->digitTransformTable();
3070 $number = strtr( $number, $s );
3078 * Front-end for non-commafied formatNum
3080 * @param mixed $number the string to be formatted, should be an integer
3081 * or a floating point number.
3085 public function formatNumNoSeparators( $number ) {
3086 return $this->formatNum( $number, true );
3090 * @param $number string
3093 function parseFormattedNumber( $number ) {
3094 $s = $this->digitTransformTable();
3096 $number = strtr( $number, array_flip( $s ) );
3099 $s = $this->separatorTransformTable();
3101 $number = strtr( $number, array_flip( $s ) );
3104 $number = strtr( $number, array( ',' => '' ) );
3109 * Adds commas to a given number
3111 * @param $number mixed
3114 function commafy( $number ) {
3115 $digitGroupingPattern = $this->digitGroupingPattern();
3116 if ( $number === null ) {
3120 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3121 // default grouping is at thousands, use the same for ###,###,### pattern too.
3122 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3124 // Ref: http://cldr.unicode.org/translation/number-patterns
3126 if ( intval( $number ) < 0 ) {
3127 // For negative numbers apply the algorithm like positive number and add sign.
3129 $number = substr( $number, 1 );
3131 $integerPart = array();
3132 $decimalPart = array();
3133 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3134 preg_match( "/\d+/", $number, $integerPart );
3135 preg_match( "/\.\d*/", $number, $decimalPart );
3136 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3137 if ( $groupedNumber === $number ) {
3138 // the string does not have any number part. Eg: .12345
3139 return $sign . $groupedNumber;
3141 $start = $end = strlen( $integerPart[0] );
3142 while ( $start > 0 ) {
3143 $match = $matches[0][$numMatches - 1];
3144 $matchLen = strlen( $match );
3145 $start = $end - $matchLen;
3149 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3151 if ( $numMatches > 1 ) {
3152 // use the last pattern for the rest of the number
3156 $groupedNumber = "," . $groupedNumber;
3159 return $sign . $groupedNumber;
3166 function digitGroupingPattern() {
3167 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3173 function digitTransformTable() {
3174 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3180 function separatorTransformTable() {
3181 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3185 * Take a list of strings and build a locale-friendly comma-separated
3186 * list, using the local comma-separator message.
3187 * The last two strings are chained with an "and".
3188 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3193 function listToText( array $l ) {
3194 $m = count( $l ) - 1;
3199 $and = $this->getMessageFromDB( 'and' );
3200 $space = $this->getMessageFromDB( 'word-separator' );
3202 $comma = $this->getMessageFromDB( 'comma-separator' );
3206 for ( $i = $m - 1; $i >= 0; $i-- ) {
3207 if ( $i == $m - 1 ) {
3208 $s = $l[$i] . $and . $space . $s;
3210 $s = $l[$i] . $comma . $s;
3217 * Take a list of strings and build a locale-friendly comma-separated
3218 * list, using the local comma-separator message.
3219 * @param $list array of strings to put in a comma list
3222 function commaList( array $list ) {
3224 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3230 * Take a list of strings and build a locale-friendly semicolon-separated
3231 * list, using the local semicolon-separator message.
3232 * @param $list array of strings to put in a semicolon list
3235 function semicolonList( array $list ) {
3237 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3243 * Same as commaList, but separate it with the pipe instead.
3244 * @param $list array of strings to put in a pipe list
3247 function pipeList( array $list ) {
3249 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3255 * Truncate a string to a specified length in bytes, appending an optional
3256 * string (e.g. for ellipses)
3258 * The database offers limited byte lengths for some columns in the database;
3259 * multi-byte character sets mean we need to ensure that only whole characters
3260 * are included, otherwise broken characters can be passed to the user
3262 * If $length is negative, the string will be truncated from the beginning
3264 * @param $string String to truncate
3265 * @param $length Int: maximum length (including ellipses)
3266 * @param $ellipsis String to append to the truncated text
3267 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3268 * $adjustLength was introduced in 1.18, before that behaved as if false.
3271 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3272 # Use the localized ellipsis character
3273 if ( $ellipsis == '...' ) {
3274 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3276 # Check if there is no need to truncate
3277 if ( $length == 0 ) {
3278 return $ellipsis; // convention
3279 } elseif ( strlen( $string ) <= abs( $length ) ) {
3280 return $string; // no need to truncate
3282 $stringOriginal = $string;
3283 # If ellipsis length is >= $length then we can't apply $adjustLength
3284 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3285 $string = $ellipsis; // this can be slightly unexpected
3286 # Otherwise, truncate and add ellipsis...
3288 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3289 if ( $length > 0 ) {
3290 $length -= $eLength;
3291 $string = substr( $string, 0, $length ); // xyz...
3292 $string = $this->removeBadCharLast( $string );
3293 $string = $string . $ellipsis;
3295 $length +
= $eLength;
3296 $string = substr( $string, $length ); // ...xyz
3297 $string = $this->removeBadCharFirst( $string );
3298 $string = $ellipsis . $string;
3301 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3302 # This check is *not* redundant if $adjustLength, due to the single case where
3303 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3304 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3307 return $stringOriginal;
3312 * Remove bytes that represent an incomplete Unicode character
3313 * at the end of string (e.g. bytes of the char are missing)
3315 * @param $string String
3318 protected function removeBadCharLast( $string ) {
3319 if ( $string != '' ) {
3320 $char = ord( $string[strlen( $string ) - 1] );
3322 if ( $char >= 0xc0 ) {
3323 # We got the first byte only of a multibyte char; remove it.
3324 $string = substr( $string, 0, -1 );
3325 } elseif ( $char >= 0x80 &&
3326 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3327 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3329 # We chopped in the middle of a character; remove it
3337 * Remove bytes that represent an incomplete Unicode character
3338 * at the start of string (e.g. bytes of the char are missing)
3340 * @param $string String
3343 protected function removeBadCharFirst( $string ) {
3344 if ( $string != '' ) {
3345 $char = ord( $string[0] );
3346 if ( $char >= 0x80 && $char < 0xc0 ) {
3347 # We chopped in the middle of a character; remove the whole thing
3348 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3355 * Truncate a string of valid HTML to a specified length in bytes,
3356 * appending an optional string (e.g. for ellipses), and return valid HTML
3358 * This is only intended for styled/linked text, such as HTML with
3359 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3360 * Also, this will not detect things like "display:none" CSS.
3362 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3364 * @param string $text HTML string to truncate
3365 * @param int $length (zero/positive) Maximum length (including ellipses)
3366 * @param string $ellipsis String to append to the truncated text
3369 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3370 # Use the localized ellipsis character
3371 if ( $ellipsis == '...' ) {
3372 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3374 # Check if there is clearly no need to truncate
3375 if ( $length <= 0 ) {
3376 return $ellipsis; // no text shown, nothing to format (convention)
3377 } elseif ( strlen( $text ) <= $length ) {
3378 return $text; // string short enough even *with* HTML (short-circuit)
3381 $dispLen = 0; // innerHTML legth so far
3382 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3383 $tagType = 0; // 0-open, 1-close
3384 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3385 $entityState = 0; // 0-not entity, 1-entity
3386 $tag = $ret = ''; // accumulated tag name, accumulated result string
3387 $openTags = array(); // open tag stack
3388 $maybeState = null; // possible truncation state
3390 $textLen = strlen( $text );
3391 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3392 for ( $pos = 0; true; ++
$pos ) {
3393 # Consider truncation once the display length has reached the maximim.
3394 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3395 # Check that we're not in the middle of a bracket/entity...
3396 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3397 if ( !$testingEllipsis ) {
3398 $testingEllipsis = true;
3399 # Save where we are; we will truncate here unless there turn out to
3400 # be so few remaining characters that truncation is not necessary.
3401 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3402 $maybeState = array( $ret, $openTags ); // save state
3404 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3405 # String in fact does need truncation, the truncation point was OK.
3406 list( $ret, $openTags ) = $maybeState; // reload state
3407 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3408 $ret .= $ellipsis; // add ellipsis
3412 if ( $pos >= $textLen ) {
3413 break; // extra iteration just for above checks
3416 # Read the next char...
3418 $lastCh = $pos ?
$text[$pos - 1] : '';
3419 $ret .= $ch; // add to result string
3421 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3422 $entityState = 0; // for bad HTML
3423 $bracketState = 1; // tag started (checking for backslash)
3424 } elseif ( $ch == '>' ) {
3425 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3426 $entityState = 0; // for bad HTML
3427 $bracketState = 0; // out of brackets
3428 } elseif ( $bracketState == 1 ) {
3430 $tagType = 1; // close tag (e.g. "</span>")
3432 $tagType = 0; // open tag (e.g. "<span>")
3435 $bracketState = 2; // building tag name
3436 } elseif ( $bracketState == 2 ) {
3440 // Name found (e.g. "<a href=..."), add on tag attributes...
3441 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3443 } elseif ( $bracketState == 0 ) {
3444 if ( $entityState ) {
3447 $dispLen++
; // entity is one displayed char
3450 if ( $neLength == 0 && !$maybeState ) {
3451 // Save state without $ch. We want to *hit* the first
3452 // display char (to get tags) but not *use* it if truncating.
3453 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3456 $entityState = 1; // entity found, (e.g. " ")
3458 $dispLen++
; // this char is displayed
3459 // Add the next $max display text chars after this in one swoop...
3460 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3461 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3462 $dispLen +
= $skipped;
3468 // Close the last tag if left unclosed by bad HTML
3469 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3470 while ( count( $openTags ) > 0 ) {
3471 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3477 * truncateHtml() helper function
3478 * like strcspn() but adds the skipped chars to $ret
3487 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3488 if ( $len === null ) {
3489 $len = -1; // -1 means "no limit" for strcspn
3490 } elseif ( $len < 0 ) {
3494 if ( $start < strlen( $text ) ) {
3495 $skipCount = strcspn( $text, $search, $start, $len );
3496 $ret .= substr( $text, $start, $skipCount );
3502 * truncateHtml() helper function
3503 * (a) push or pop $tag from $openTags as needed
3504 * (b) clear $tag value
3505 * @param &$tag string Current HTML tag name we are looking at
3506 * @param $tagType int (0-open tag, 1-close tag)
3507 * @param $lastCh string Character before the '>' that ended this tag
3508 * @param &$openTags array Open tag stack (not accounting for $tag)
3510 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3511 $tag = ltrim( $tag );
3513 if ( $tagType == 0 && $lastCh != '/' ) {
3514 $openTags[] = $tag; // tag opened (didn't close itself)
3515 } elseif ( $tagType == 1 ) {
3516 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3517 array_pop( $openTags ); // tag closed
3525 * Grammatical transformations, needed for inflected languages
3526 * Invoked by putting {{grammar:case|word}} in a message
3528 * @param $word string
3529 * @param $case string
3532 function convertGrammar( $word, $case ) {
3533 global $wgGrammarForms;
3534 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3535 return $wgGrammarForms[$this->getCode()][$case][$word];
3540 * Get the grammar forms for the content language
3541 * @return array of grammar forms
3544 function getGrammarForms() {
3545 global $wgGrammarForms;
3546 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3547 return $wgGrammarForms[$this->getCode()];
3552 * Provides an alternative text depending on specified gender.
3553 * Usage {{gender:username|masculine|feminine|neutral}}.
3554 * username is optional, in which case the gender of current user is used,
3555 * but only in (some) interface messages; otherwise default gender is used.
3557 * If no forms are given, an empty string is returned. If only one form is
3558 * given, it will be returned unconditionally. These details are implied by
3559 * the caller and cannot be overridden in subclasses.
3561 * If more than one form is given, the default is to use the neutral one
3562 * if it is specified, and to use the masculine one otherwise. These
3563 * details can be overridden in subclasses.
3565 * @param $gender string
3566 * @param $forms array
3570 function gender( $gender, $forms ) {
3571 if ( !count( $forms ) ) {
3574 $forms = $this->preConvertPlural( $forms, 2 );
3575 if ( $gender === 'male' ) {
3578 if ( $gender === 'female' ) {
3581 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3585 * Plural form transformations, needed for some languages.
3586 * For example, there are 3 form of plural in Russian and Polish,
3587 * depending on "count mod 10". See [[w:Plural]]
3588 * For English it is pretty simple.
3590 * Invoked by putting {{plural:count|wordform1|wordform2}}
3591 * or {{plural:count|wordform1|wordform2|wordform3}}
3593 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3595 * @param $count Integer: non-localized number
3596 * @param $forms Array: different plural forms
3597 * @return string Correct form of plural for $count in this language
3599 function convertPlural( $count, $forms ) {
3600 if ( !count( $forms ) ) {
3604 // Handle explicit n=pluralform cases
3605 foreach ( $forms as $index => $form ) {
3606 if ( preg_match( '/\d+=/i', $form ) ) {
3607 $pos = strpos( $form, '=' );
3608 if ( substr( $form, 0, $pos ) === (string) $count ) {
3609 return substr( $form, $pos +
1 );
3611 unset( $forms[$index] );
3614 $forms = array_values( $forms );
3616 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3617 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3618 return $forms[$pluralForm];
3622 * Checks that convertPlural was given an array and pads it to requested
3623 * amount of forms by copying the last one.
3625 * @param $count Integer: How many forms should there be at least
3626 * @param $forms Array of forms given to convertPlural
3627 * @return array Padded array of forms or an exception if not an array
3629 protected function preConvertPlural( /* Array */ $forms, $count ) {
3630 while ( count( $forms ) < $count ) {
3631 $forms[] = $forms[count( $forms ) - 1];
3637 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3638 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3639 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3640 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3643 * @param $str String: the validated block duration in English
3644 * @return string Somehow translated block duration
3645 * @see LanguageFi.php for example implementation
3647 function translateBlockExpiry( $str ) {
3648 $duration = SpecialBlock
::getSuggestedDurations( $this );
3649 foreach ( $duration as $show => $value ) {
3650 if ( strcmp( $str, $value ) == 0 ) {
3651 return htmlspecialchars( trim( $show ) );
3655 // Since usually only infinite or indefinite is only on list, so try
3656 // equivalents if still here.
3657 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3658 if ( in_array( $str, $indefs ) ) {
3659 foreach ( $indefs as $val ) {
3660 $show = array_search( $val, $duration, true );
3661 if ( $show !== false ) {
3662 return htmlspecialchars( trim( $show ) );
3667 // If all else fails, return a standard duration or timestamp description.
3668 $time = strtotime( $str, 0 );
3669 if ( $time === false ) { // Unknown format. Return it as-is in case.
3671 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3672 // $time is relative to 0 so it's a duration length.
3673 return $this->formatDuration( $time );
3674 } else { // It's an absolute timestamp.
3675 if ( $time === 0 ) {
3676 // wfTimestamp() handles 0 as current time instead of epoch.
3677 return $this->timeanddate( '19700101000000' );
3679 return $this->timeanddate( $time );
3685 * languages like Chinese need to be segmented in order for the diff
3688 * @param $text String
3691 public function segmentForDiff( $text ) {
3696 * and unsegment to show the result
3698 * @param $text String
3701 public function unsegmentForDiff( $text ) {
3706 * Return the LanguageConverter used in the Language
3709 * @return LanguageConverter
3711 public function getConverter() {
3712 return $this->mConverter
;
3716 * convert text to all supported variants
3718 * @param $text string
3721 public function autoConvertToAllVariants( $text ) {
3722 return $this->mConverter
->autoConvertToAllVariants( $text );
3726 * convert text to different variants of a language.
3728 * @param $text string
3731 public function convert( $text ) {
3732 return $this->mConverter
->convert( $text );
3736 * Convert a Title object to a string in the preferred variant
3738 * @param $title Title
3741 public function convertTitle( $title ) {
3742 return $this->mConverter
->convertTitle( $title );
3746 * Convert a namespace index to a string in the preferred variant
3751 public function convertNamespace( $ns ) {
3752 return $this->mConverter
->convertNamespace( $ns );
3756 * Check if this is a language with variants
3760 public function hasVariants() {
3761 return count( $this->getVariants() ) > 1;
3765 * Check if the language has the specific variant
3768 * @param $variant string
3771 public function hasVariant( $variant ) {
3772 return (bool)$this->mConverter
->validateVariant( $variant );
3776 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3778 * @param $text string
3781 public function armourMath( $text ) {
3782 return $this->mConverter
->armourMath( $text );
3786 * Perform output conversion on a string, and encode for safe HTML output.
3787 * @param $text String text to be converted
3788 * @param $isTitle Bool whether this conversion is for the article title
3790 * @todo this should get integrated somewhere sane
3792 public function convertHtml( $text, $isTitle = false ) {
3793 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3797 * @param $key string
3800 public function convertCategoryKey( $key ) {
3801 return $this->mConverter
->convertCategoryKey( $key );
3805 * Get the list of variants supported by this language
3806 * see sample implementation in LanguageZh.php
3808 * @return array an array of language codes
3810 public function getVariants() {
3811 return $this->mConverter
->getVariants();
3817 public function getPreferredVariant() {
3818 return $this->mConverter
->getPreferredVariant();
3824 public function getDefaultVariant() {
3825 return $this->mConverter
->getDefaultVariant();
3831 public function getURLVariant() {
3832 return $this->mConverter
->getURLVariant();
3836 * If a language supports multiple variants, it is
3837 * possible that non-existing link in one variant
3838 * actually exists in another variant. this function
3839 * tries to find it. See e.g. LanguageZh.php
3841 * @param $link String: the name of the link
3842 * @param $nt Mixed: the title object of the link
3843 * @param $ignoreOtherCond Boolean: to disable other conditions when
3844 * we need to transclude a template or update a category's link
3845 * @return null the input parameters may be modified upon return
3847 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3848 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3852 * If a language supports multiple variants, converts text
3853 * into an array of all possible variants of the text:
3854 * 'variant' => text in that variant
3856 * @deprecated since 1.17 Use autoConvertToAllVariants()
3858 * @param $text string
3862 public function convertLinkToAllVariants( $text ) {
3863 return $this->mConverter
->convertLinkToAllVariants( $text );
3867 * returns language specific options used by User::getPageRenderHash()
3868 * for example, the preferred language variant
3872 function getExtraHashOptions() {
3873 return $this->mConverter
->getExtraHashOptions();
3877 * For languages that support multiple variants, the title of an
3878 * article may be displayed differently in different variants. this
3879 * function returns the apporiate title defined in the body of the article.
3883 public function getParsedTitle() {
3884 return $this->mConverter
->getParsedTitle();
3888 * Prepare external link text for conversion. When the text is
3889 * a URL, it shouldn't be converted, and it'll be wrapped in
3890 * the "raw" tag (-{R| }-) to prevent conversion.
3892 * This function is called "markNoConversion" for historical
3895 * @param $text String: text to be used for external link
3896 * @param $noParse bool: wrap it without confirming it's a real URL first
3897 * @return string the tagged text
3899 public function markNoConversion( $text, $noParse = false ) {
3900 // Excluding protocal-relative URLs may avoid many false positives.
3901 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3902 return $this->mConverter
->markNoConversion( $text );
3909 * A regular expression to match legal word-trailing characters
3910 * which should be merged onto a link of the form [[foo]]bar.
3914 public function linkTrail() {
3915 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3921 function getLangObj() {
3926 * Get the RFC 3066 code for this language object
3928 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3929 * htmlspecialchars() or similar
3933 public function getCode() {
3934 return $this->mCode
;
3938 * Get the code in Bcp47 format which we can use
3939 * inside of html lang="" tags.
3941 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3942 * htmlspecialchars() or similar.
3947 public function getHtmlCode() {
3948 if ( is_null( $this->mHtmlCode
) ) {
3949 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3951 return $this->mHtmlCode
;
3955 * @param $code string
3957 public function setCode( $code ) {
3958 $this->mCode
= $code;
3959 // Ensure we don't leave an incorrect html code lying around
3960 $this->mHtmlCode
= null;
3964 * Get the name of a file for a certain language code
3965 * @param $prefix string Prepend this to the filename
3966 * @param $code string Language code
3967 * @param $suffix string Append this to the filename
3968 * @throws MWException
3969 * @return string $prefix . $mangledCode . $suffix
3971 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3972 // Protect against path traversal
3973 if ( !Language
::isValidCode( $code )
3974 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3976 throw new MWException( "Invalid language code \"$code\"" );
3979 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3983 * Get the language code from a file name. Inverse of getFileName()
3984 * @param $filename string $prefix . $languageCode . $suffix
3985 * @param $prefix string Prefix before the language code
3986 * @param $suffix string Suffix after the language code
3987 * @return string Language code, or false if $prefix or $suffix isn't found
3989 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3991 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3992 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3993 if ( !count( $m ) ) {
3996 return str_replace( '_', '-', strtolower( $m[1] ) );
4000 * @param $code string
4003 public static function getMessagesFileName( $code ) {
4005 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4006 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4011 * @param $code string
4014 public static function getClassFileName( $code ) {
4016 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4020 * Get the first fallback for a given language.
4022 * @param $code string
4024 * @return bool|string
4026 public static function getFallbackFor( $code ) {
4027 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4030 $fallbacks = self
::getFallbacksFor( $code );
4031 $first = array_shift( $fallbacks );
4037 * Get the ordered list of fallback languages.
4040 * @param $code string Language code
4043 public static function getFallbacksFor( $code ) {
4044 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4047 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4048 $v = array_map( 'trim', explode( ',', $v ) );
4049 if ( $v[count( $v ) - 1] !== 'en' ) {
4057 * Get all messages for a given language
4058 * WARNING: this may take a long time. If you just need all message *keys*
4059 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4061 * @param $code string
4065 public static function getMessagesFor( $code ) {
4066 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4070 * Get a message for a given language
4072 * @param $key string
4073 * @param $code string
4077 public static function getMessageFor( $key, $code ) {
4078 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4082 * Get all message keys for a given language. This is a faster alternative to
4083 * array_keys( Language::getMessagesFor( $code ) )
4086 * @param $code string Language code
4087 * @return array of message keys (strings)
4089 public static function getMessageKeysFor( $code ) {
4090 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4097 function fixVariableInNamespace( $talk ) {
4098 if ( strpos( $talk, '$1' ) === false ) {
4102 global $wgMetaNamespace;
4103 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4105 # Allow grammar transformations
4106 # Allowing full message-style parsing would make simple requests
4107 # such as action=raw much more expensive than they need to be.
4108 # This will hopefully cover most cases.
4109 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4110 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4111 return str_replace( ' ', '_', $talk );
4118 function replaceGrammarInNamespace( $m ) {
4119 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4123 * @throws MWException
4126 static function getCaseMaps() {
4127 static $wikiUpperChars, $wikiLowerChars;
4128 if ( isset( $wikiUpperChars ) ) {
4129 return array( $wikiUpperChars, $wikiLowerChars );
4132 wfProfileIn( __METHOD__
);
4133 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4134 if ( $arr === false ) {
4135 throw new MWException(
4136 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4138 $wikiUpperChars = $arr['wikiUpperChars'];
4139 $wikiLowerChars = $arr['wikiLowerChars'];
4140 wfProfileOut( __METHOD__
);
4141 return array( $wikiUpperChars, $wikiLowerChars );
4145 * Decode an expiry (block, protection, etc) which has come from the DB
4147 * @todo FIXME: why are we returnings DBMS-dependent strings???
4149 * @param $expiry String: Database expiry String
4150 * @param $format Bool|Int true to process using language functions, or TS_ constant
4151 * to return the expiry in a given timestamp
4155 public function formatExpiry( $expiry, $format = true ) {
4157 if ( $infinity === null ) {
4158 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4161 if ( $expiry == '' ||
$expiry == $infinity ) {
4162 return $format === true
4163 ?
$this->getMessageFromDB( 'infiniteblock' )
4166 return $format === true
4167 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4168 : wfTimestamp( $format, $expiry );
4174 * @param $seconds int|float
4175 * @param $format Array Optional
4176 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4177 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4178 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4179 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4182 function formatTimePeriod( $seconds, $format = array() ) {
4183 if ( !is_array( $format ) ) {
4184 $format = array( 'avoid' => $format ); // For backwards compatibility
4186 if ( !isset( $format['avoid'] ) ) {
4187 $format['avoid'] = false;
4189 if ( !isset( $format['noabbrevs' ] ) ) {
4190 $format['noabbrevs'] = false;
4192 $secondsMsg = wfMessage(
4193 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4194 $minutesMsg = wfMessage(
4195 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4196 $hoursMsg = wfMessage(
4197 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4198 $daysMsg = wfMessage(
4199 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4201 if ( round( $seconds * 10 ) < 100 ) {
4202 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4203 $s = $secondsMsg->params( $s )->text();
4204 } elseif ( round( $seconds ) < 60 ) {
4205 $s = $this->formatNum( round( $seconds ) );
4206 $s = $secondsMsg->params( $s )->text();
4207 } elseif ( round( $seconds ) < 3600 ) {
4208 $minutes = floor( $seconds / 60 );
4209 $secondsPart = round( fmod( $seconds, 60 ) );
4210 if ( $secondsPart == 60 ) {
4214 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4216 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4217 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4218 $hours = floor( $seconds / 3600 );
4219 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4220 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4221 if ( $secondsPart == 60 ) {
4225 if ( $minutes == 60 ) {
4229 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4231 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4232 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4233 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4236 $days = floor( $seconds / 86400 );
4237 if ( $format['avoid'] === 'avoidminutes' ) {
4238 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4239 if ( $hours == 24 ) {
4243 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4245 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4246 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4247 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4248 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4249 if ( $minutes == 60 ) {
4253 if ( $hours == 24 ) {
4257 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4259 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4261 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4263 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4265 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4272 * Format a bitrate for output, using an appropriate
4273 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4275 * This use base 1000. For base 1024 use formatSize(), for another base
4276 * see formatComputingNumbers()
4281 function formatBitrate( $bps ) {
4282 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4286 * @param $size int Size of the unit
4287 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4288 * @param $messageKey string Message key to be uesd
4291 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4293 return str_replace( '$1', $this->formatNum( $size ),
4294 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4297 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4300 $maxIndex = count( $sizes ) - 1;
4301 while ( $size >= $boundary && $index < $maxIndex ) {
4306 // For small sizes no decimal places necessary
4309 // For MB and bigger two decimal places are smarter
4312 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4314 $size = round( $size, $round );
4315 $text = $this->getMessageFromDB( $msg );
4316 return str_replace( '$1', $this->formatNum( $size ), $text );
4320 * Format a size in bytes for output, using an appropriate
4321 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4323 * This method use base 1024. For base 1000 use formatBitrate(), for
4324 * another base see formatComputingNumbers()
4326 * @param $size int Size to format
4327 * @return string Plain text (not HTML)
4329 function formatSize( $size ) {
4330 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4334 * Make a list item, used by various special pages
4336 * @param $page String Page link
4337 * @param $details String Text between brackets
4338 * @param $oppositedm Boolean Add the direction mark opposite to your
4339 * language, to display text properly
4342 function specialList( $page, $details, $oppositedm = true ) {
4343 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4344 $this->getDirMark();
4345 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4346 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4347 return $page . $details;
4351 * Generate (prev x| next x) (20|50|100...) type links for paging
4353 * @param $title Title object to link
4354 * @param $offset Integer offset parameter
4355 * @param $limit Integer limit parameter
4356 * @param $query array|String optional URL query parameter string
4357 * @param $atend Bool optional param for specified if this is the last page
4360 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4361 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4363 # Make 'previous' link
4364 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4365 if ( $offset > 0 ) {
4366 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4367 $query, $prev, 'prevn-title', 'mw-prevlink' );
4369 $plink = htmlspecialchars( $prev );
4373 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4375 $nlink = htmlspecialchars( $next );
4377 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4378 $query, $next, 'prevn-title', 'mw-nextlink' );
4381 # Make links to set number of items per page
4382 $numLinks = array();
4383 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4384 $numLinks[] = $this->numLink( $title, $offset, $num,
4385 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4388 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4389 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4393 * Helper function for viewPrevNext() that generates links
4395 * @param $title Title object to link
4396 * @param $offset Integer offset parameter
4397 * @param $limit Integer limit parameter
4398 * @param $query Array extra query parameters
4399 * @param $link String text to use for the link; will be escaped
4400 * @param $tooltipMsg String name of the message to use as tooltip
4401 * @param $class String value of the "class" attribute of the link
4402 * @return String HTML fragment
4404 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4405 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4406 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4407 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4408 'title' => $tooltip, 'class' => $class ), $link );
4412 * Get the conversion rule title, if any.
4416 public function getConvRuleTitle() {
4417 return $this->mConverter
->getConvRuleTitle();
4421 * Get the compiled plural rules for the language
4423 * @return array Associative array with plural form, and plural rule as key-value pairs
4425 public function getCompiledPluralRules() {
4426 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4427 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4428 if ( !$pluralRules ) {
4429 foreach ( $fallbacks as $fallbackCode ) {
4430 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4431 if ( $pluralRules ) {
4436 return $pluralRules;
4440 * Get the plural rules for the language
4442 * @return array Associative array with plural form number and plural rule as key-value pairs
4444 public function getPluralRules() {
4445 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4446 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4447 if ( !$pluralRules ) {
4448 foreach ( $fallbacks as $fallbackCode ) {
4449 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4450 if ( $pluralRules ) {
4455 return $pluralRules;
4459 * Get the plural rule types for the language
4461 * @return array Associative array with plural form number and plural rule type as key-value pairs
4463 public function getPluralRuleTypes() {
4464 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4465 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4466 if ( !$pluralRuleTypes ) {
4467 foreach ( $fallbacks as $fallbackCode ) {
4468 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4469 if ( $pluralRuleTypes ) {
4474 return $pluralRuleTypes;
4478 * Find the index number of the plural rule appropriate for the given number
4479 * @return int The index number of the plural rule
4481 public function getPluralRuleIndexNumber( $number ) {
4482 $pluralRules = $this->getCompiledPluralRules();
4483 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4488 * Find the plural rule type appropriate for the given number
4489 * For example, if the language is set to Arabic, getPluralType(5) should
4492 * @return string The name of the plural rule type, e.g. one, two, few, many
4494 public function getPluralRuleType( $number ) {
4495 $index = $this->getPluralRuleIndexNumber( $number );
4496 $pluralRuleTypes = $this->getPluralRuleTypes();
4497 if ( isset( $pluralRuleTypes[$index] ) ) {
4498 return $pluralRuleTypes[$index];