3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once( __DIR__
. '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
51 function __construct( $langobj ) { $this->mLang
= $langobj; }
52 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
53 function convert( $t ) { return $t; }
54 function convertTo( $text, $variant ) { return $text; }
55 function convertTitle( $t ) { return $t->getPrefixedText(); }
56 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
57 function getVariants() { return array( $this->mLang
->getCode() ); }
58 function getPreferredVariant() { return $this->mLang
->getCode(); }
59 function getDefaultVariant() { return $this->mLang
->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
72 * Internationalisation code
78 * @var LanguageConverter
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 public $dateFormatStrings = array();
87 public $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
92 * ReplacementArray object caches
94 public $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
174 * Get a cached or new language object for a given language code
175 * @param $code String
178 static function factory( $code ) {
179 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
181 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
182 $code = $wgDummyLanguageCodes[$code];
185 // get the language object to process
186 $langObj = isset( self
::$mLangObjCache[$code] )
187 ? self
::$mLangObjCache[$code]
188 : self
::newFromCode( $code );
190 // merge the language object in to get it up front in the cache
191 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
192 // get rid of the oldest ones in case we have an overflow
193 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
199 * Create a language object for a given language code
200 * @param $code String
201 * @throws MWException
204 protected static function newFromCode( $code ) {
205 // Protect against path traversal below
206 if ( !Language
::isValidCode( $code )
207 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
209 throw new MWException( "Invalid language code \"$code\"" );
212 if ( !Language
::isValidBuiltInCode( $code ) ) {
213 // It's not possible to customise this code with class files, so
214 // just return a Language object. This is to support uselang= hacks.
215 $lang = new Language
;
216 $lang->setCode( $code );
220 // Check if there is a language class for the code
221 $class = self
::classFromCode( $code );
222 self
::preloadLanguageClass( $class );
223 if ( MWInit
::classExists( $class ) ) {
228 // Keep trying the fallback list until we find an existing class
229 $fallbacks = Language
::getFallbacksFor( $code );
230 foreach ( $fallbacks as $fallbackCode ) {
231 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
232 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
235 $class = self
::classFromCode( $fallbackCode );
236 self
::preloadLanguageClass( $class );
237 if ( MWInit
::classExists( $class ) ) {
238 $lang = Language
::newFromCode( $fallbackCode );
239 $lang->setCode( $code );
244 throw new MWException( "Invalid fallback sequence for language '$code'" );
248 * Checks whether any localisation is available for that language tag
249 * in MediaWiki (MessagesXx.php exists).
251 * @param string $code Language tag (in lower case)
252 * @return bool Whether language is supported
255 public static function isSupportedLanguage( $code ) {
256 return $code === strtolower( $code ) && is_readable( self
::getMessagesFileName( $code ) );
260 * Returns true if a language code string is a well-formed language tag
261 * according to RFC 5646.
262 * This function only checks well-formedness; it doesn't check that
263 * language, script or variant codes actually exist in the repositories.
265 * Based on regexes by Mark Davis of the Unicode Consortium:
266 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
268 * @param $code string
269 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
274 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
277 $alphanum = '[a-z0-9]';
278 $x = 'x'; # private use singleton
279 $singleton = '[a-wy-z]'; # other singleton
280 $s = $lenient ?
'[-_]' : '-';
282 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
283 $script = "$alpha{4}"; # ISO 15924
284 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
285 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
286 $extension = "$singleton(?:$s$alphanum{2,8})+";
287 $privateUse = "$x(?:$s$alphanum{1,8})+";
289 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
290 # Since these are limited, this is safe even later changes to the registry --
291 # the only oddity is that it might change the type of the tag, and thus
292 # the results from the capturing groups.
293 # http://www.iana.org/assignments/language-subtag-registry
295 $grandfathered = "en{$s}GB{$s}oed"
296 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
297 . "|no{$s}(?:bok|nyn)"
298 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
299 . "|zh{$s}min{$s}nan";
301 $variantList = "$variant(?:$s$variant)*";
302 $extensionList = "$extension(?:$s$extension)*";
304 $langtag = "(?:($language)"
307 . "(?:$s$variantList)?"
308 . "(?:$s$extensionList)?"
309 . "(?:$s$privateUse)?)";
311 # The final breakdown, with capturing groups for each of these components
312 # The variants, extensions, grandfathered, and private-use may have interior '-'
314 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
316 return (bool)preg_match( "/$root/", strtolower( $code ) );
320 * Returns true if a language code string is of a valid form, whether or
321 * not it exists. This includes codes which are used solely for
322 * customisation via the MediaWiki namespace.
324 * @param $code string
328 public static function isValidCode( $code ) {
330 // People think language codes are html safe, so enforce it.
331 // Ideally we should only allow a-zA-Z0-9-
332 // but, .+ and other chars are often used for {{int:}} hacks
333 // see bugs 37564, 37587, 36938
334 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
335 && !preg_match( Title
::getTitleInvalidRegex(), $code );
339 * Returns true if a language code is of a valid form for the purposes of
340 * internal customisation of MediaWiki, via Messages*.php.
342 * @param $code string
344 * @throws MWException
348 public static function isValidBuiltInCode( $code ) {
350 if ( !is_string( $code ) ) {
351 if ( is_object( $code ) ) {
352 $addmsg = " of class " . get_class( $code );
356 $type = gettype( $code );
357 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
360 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
364 * Returns true if a language code is an IETF tag known to MediaWiki.
366 * @param $code string
371 public static function isKnownLanguageTag( $tag ) {
372 static $coreLanguageNames;
374 if ( $coreLanguageNames === null ) {
375 include( MWInit
::compiledPath( 'languages/Names.php' ) );
378 if ( isset( $coreLanguageNames[$tag] )
379 || self
::fetchLanguageName( $tag, $tag ) !== ''
389 * @return String Name of the language class
391 public static function classFromCode( $code ) {
392 if ( $code == 'en' ) {
395 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
400 * Includes language class files
402 * @param $class string Name of the language class
404 public static function preloadLanguageClass( $class ) {
407 if ( $class === 'Language' ) {
411 if ( !defined( 'MW_COMPILED' ) ) {
412 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
413 include_once( "$IP/languages/classes/$class.php" );
419 * Get the LocalisationCache instance
421 * @return LocalisationCache
423 public static function getLocalisationCache() {
424 if ( is_null( self
::$dataCache ) ) {
425 global $wgLocalisationCacheConf;
426 $class = $wgLocalisationCacheConf['class'];
427 self
::$dataCache = new $class( $wgLocalisationCacheConf );
429 return self
::$dataCache;
432 function __construct() {
433 $this->mConverter
= new FakeConverter( $this );
434 // Set the code to the name of the descendant
435 if ( get_class( $this ) == 'Language' ) {
438 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
440 self
::getLocalisationCache();
444 * Reduce memory usage
446 function __destruct() {
447 foreach ( $this as $name => $value ) {
448 unset( $this->$name );
453 * Hook which will be called if this is the content language.
454 * Descendants can use this to register hook functions or modify globals
456 function initContLang() { }
459 * Same as getFallbacksFor for current language.
461 * @deprecated in 1.19
463 function getFallbackLanguageCode() {
464 wfDeprecated( __METHOD__
, '1.19' );
465 return self
::getFallbackFor( $this->mCode
);
472 function getFallbackLanguages() {
473 return self
::getFallbacksFor( $this->mCode
);
477 * Exports $wgBookstoreListEn
480 function getBookstoreList() {
481 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
485 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
486 * available in localised form, it will be included in English.
490 public function getNamespaces() {
491 if ( is_null( $this->namespaceNames
) ) {
492 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
494 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
495 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
497 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
499 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
500 if ( $wgMetaNamespaceTalk ) {
501 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
503 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
504 $this->namespaceNames
[NS_PROJECT_TALK
] =
505 $this->fixVariableInNamespace( $talk );
508 # Sometimes a language will be localised but not actually exist on this wiki.
509 foreach ( $this->namespaceNames
as $key => $text ) {
510 if ( !isset( $validNamespaces[$key] ) ) {
511 unset( $this->namespaceNames
[$key] );
515 # The above mixing may leave namespaces out of canonical order.
516 # Re-order by namespace ID number...
517 ksort( $this->namespaceNames
);
519 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
521 return $this->namespaceNames
;
525 * Arbitrarily set all of the namespace names at once. Mainly used for testing
526 * @param $namespaces Array of namespaces (id => name)
528 public function setNamespaces( array $namespaces ) {
529 $this->namespaceNames
= $namespaces;
530 $this->mNamespaceIds
= null;
534 * Resets all of the namespace caches. Mainly used for testing
536 public function resetNamespaces() {
537 $this->namespaceNames
= null;
538 $this->mNamespaceIds
= null;
539 $this->namespaceAliases
= null;
543 * A convenience function that returns the same thing as
544 * getNamespaces() except with the array values changed to ' '
545 * where it found '_', useful for producing output to be displayed
546 * e.g. in <select> forms.
550 function getFormattedNamespaces() {
551 $ns = $this->getNamespaces();
552 foreach ( $ns as $k => $v ) {
553 $ns[$k] = strtr( $v, '_', ' ' );
559 * Get a namespace value by key
561 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
562 * echo $mw_ns; // prints 'MediaWiki'
565 * @param $index Int: the array key of the namespace to return
566 * @return mixed, string if the namespace value exists, otherwise false
568 function getNsText( $index ) {
569 $ns = $this->getNamespaces();
570 return isset( $ns[$index] ) ?
$ns[$index] : false;
574 * A convenience function that returns the same thing as
575 * getNsText() except with '_' changed to ' ', useful for
579 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
580 * echo $mw_ns; // prints 'MediaWiki talk'
583 * @param int $index The array key of the namespace to return
584 * @return string Namespace name without underscores (empty string if namespace does not exist)
586 function getFormattedNsText( $index ) {
587 $ns = $this->getNsText( $index );
588 return strtr( $ns, '_', ' ' );
592 * Returns gender-dependent namespace alias if available.
593 * @param $index Int: namespace index
594 * @param $gender String: gender key (male, female... )
598 function getGenderNsText( $index, $gender ) {
599 global $wgExtraGenderNamespaces;
601 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
602 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
606 * Whether this language makes distinguishes genders for example in
611 function needsGenderDistinction() {
612 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
613 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
614 // $wgExtraGenderNamespaces overrides everything
616 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
617 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
618 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
621 // Check what is in i18n files
622 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
623 return count( $aliases ) > 0;
628 * Get a namespace key by value, case insensitive.
629 * Only matches namespace names for the current language, not the
630 * canonical ones defined in Namespace.php.
632 * @param $text String
633 * @return mixed An integer if $text is a valid value otherwise false
635 function getLocalNsIndex( $text ) {
636 $lctext = $this->lc( $text );
637 $ids = $this->getNamespaceIds();
638 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
644 function getNamespaceAliases() {
645 if ( is_null( $this->namespaceAliases
) ) {
646 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
650 foreach ( $aliases as $name => $index ) {
651 if ( $index === NS_PROJECT_TALK
) {
652 unset( $aliases[$name] );
653 $name = $this->fixVariableInNamespace( $name );
654 $aliases[$name] = $index;
659 global $wgExtraGenderNamespaces;
660 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
661 foreach ( $genders as $index => $forms ) {
662 foreach ( $forms as $alias ) {
663 $aliases[$alias] = $index;
667 $this->namespaceAliases
= $aliases;
669 return $this->namespaceAliases
;
675 function getNamespaceIds() {
676 if ( is_null( $this->mNamespaceIds
) ) {
677 global $wgNamespaceAliases;
678 # Put namespace names and aliases into a hashtable.
679 # If this is too slow, then we should arrange it so that it is done
680 # before caching. The catch is that at pre-cache time, the above
681 # class-specific fixup hasn't been done.
682 $this->mNamespaceIds
= array();
683 foreach ( $this->getNamespaces() as $index => $name ) {
684 $this->mNamespaceIds
[$this->lc( $name )] = $index;
686 foreach ( $this->getNamespaceAliases() as $name => $index ) {
687 $this->mNamespaceIds
[$this->lc( $name )] = $index;
689 if ( $wgNamespaceAliases ) {
690 foreach ( $wgNamespaceAliases as $name => $index ) {
691 $this->mNamespaceIds
[$this->lc( $name )] = $index;
695 return $this->mNamespaceIds
;
699 * Get a namespace key by value, case insensitive. Canonical namespace
700 * names override custom ones defined for the current language.
702 * @param $text String
703 * @return mixed An integer if $text is a valid value otherwise false
705 function getNsIndex( $text ) {
706 $lctext = $this->lc( $text );
707 $ns = MWNamespace
::getCanonicalIndex( $lctext );
708 if ( $ns !== null ) {
711 $ids = $this->getNamespaceIds();
712 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
716 * short names for language variants used for language conversion links.
718 * @param $code String
719 * @param $usemsg bool Use the "variantname-xyz" message if it exists
722 function getVariantname( $code, $usemsg = true ) {
723 $msg = "variantname-$code";
724 if ( $usemsg && wfMessage( $msg )->exists() ) {
725 return $this->getMessageFromDB( $msg );
727 $name = self
::fetchLanguageName( $code );
729 return $name; # if it's defined as a language name, show that
731 # otherwise, output the language code
737 * @param $name string
740 function specialPage( $name ) {
741 $aliases = $this->getSpecialPageAliases();
742 if ( isset( $aliases[$name][0] ) ) {
743 $name = $aliases[$name][0];
745 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
751 function getDatePreferences() {
752 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
758 function getDateFormats() {
759 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
763 * @return array|string
765 function getDefaultDateFormat() {
766 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
767 if ( $df === 'dmy or mdy' ) {
768 global $wgAmericanDates;
769 return $wgAmericanDates ?
'mdy' : 'dmy';
778 function getDatePreferenceMigrationMap() {
779 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
786 function getImageFile( $image ) {
787 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
793 function getExtraUserToggles() {
794 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
801 function getUserToggle( $tog ) {
802 return $this->getMessageFromDB( "tog-$tog" );
806 * Get native language names, indexed by code.
807 * Only those defined in MediaWiki, no other data like CLDR.
808 * If $customisedOnly is true, only returns codes with a messages file
810 * @param $customisedOnly bool
813 * @deprecated in 1.20, use fetchLanguageNames()
815 public static function getLanguageNames( $customisedOnly = false ) {
816 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
820 * Get translated language names. This is done on best effort and
821 * by default this is exactly the same as Language::getLanguageNames.
822 * The CLDR extension provides translated names.
823 * @param $code String Language code.
824 * @return Array language code => language name
826 * @deprecated in 1.20, use fetchLanguageNames()
828 public static function getTranslatedLanguageNames( $code ) {
829 return self
::fetchLanguageNames( $code, 'all' );
833 * Get an array of language names, indexed by code.
834 * @param $inLanguage null|string: Code of language in which to return the names
835 * Use null for autonyms (native names)
836 * @param $include string:
837 * 'all' all available languages
838 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
839 * 'mwfile' only if the language is in 'mw' *and* has a message file
840 * @return array: language code => language name
843 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
844 global $wgExtraLanguageNames;
845 static $coreLanguageNames;
847 if ( $coreLanguageNames === null ) {
848 include( MWInit
::compiledPath( 'languages/Names.php' ) );
854 # TODO: also include when $inLanguage is null, when this code is more efficient
855 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
858 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
859 foreach ( $mwNames as $mwCode => $mwName ) {
860 # - Prefer own MediaWiki native name when not using the hook
861 # - For other names just add if not added through the hook
862 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
863 $names[$mwCode] = $mwName;
867 if ( $include === 'all' ) {
872 $coreCodes = array_keys( $mwNames );
873 foreach ( $coreCodes as $coreCode ) {
874 $returnMw[$coreCode] = $names[$coreCode];
877 if ( $include === 'mwfile' ) {
878 $namesMwFile = array();
879 # We do this using a foreach over the codes instead of a directory
880 # loop so that messages files in extensions will work correctly.
881 foreach ( $returnMw as $code => $value ) {
882 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
883 $namesMwFile[$code] = $names[$code];
888 # 'mw' option; default if it's not one of the other two options (all/mwfile)
893 * @param $code string: The code of the language for which to get the name
894 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
895 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
896 * @return string: Language name or empty
899 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
900 $array = self
::fetchLanguageNames( $inLanguage, $include );
901 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
905 * Get a message from the MediaWiki namespace.
907 * @param $msg String: message name
910 function getMessageFromDB( $msg ) {
911 return wfMessage( $msg )->inLanguage( $this )->text();
915 * Get the native language name of $code.
916 * Only if defined in MediaWiki, no other data like CLDR.
917 * @param $code string
919 * @deprecated in 1.20, use fetchLanguageName()
921 function getLanguageName( $code ) {
922 return self
::fetchLanguageName( $code );
929 function getMonthName( $key ) {
930 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
936 function getMonthNamesArray() {
937 $monthNames = array( '' );
938 for ( $i = 1; $i < 13; $i++
) {
939 $monthNames[] = $this->getMonthName( $i );
948 function getMonthNameGen( $key ) {
949 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
956 function getMonthAbbreviation( $key ) {
957 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
963 function getMonthAbbreviationsArray() {
964 $monthNames = array( '' );
965 for ( $i = 1; $i < 13; $i++
) {
966 $monthNames[] = $this->getMonthAbbreviation( $i );
975 function getWeekdayName( $key ) {
976 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
983 function getWeekdayAbbreviation( $key ) {
984 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
991 function getIranianCalendarMonthName( $key ) {
992 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
999 function getHebrewCalendarMonthName( $key ) {
1000 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1004 * @param $key string
1007 function getHebrewCalendarMonthNameGen( $key ) {
1008 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1012 * @param $key string
1015 function getHijriCalendarMonthName( $key ) {
1016 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1020 * This is a workalike of PHP's date() function, but with better
1021 * internationalisation, a reduced set of format characters, and a better
1024 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1025 * the PHP manual for definitions. There are a number of extensions, which
1028 * xn Do not translate digits of the next numeric format character
1029 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1030 * xr Use roman numerals for the next numeric format character
1031 * xh Use hebrew numerals for the next numeric format character
1033 * xg Genitive month name
1035 * xij j (day number) in Iranian calendar
1036 * xiF F (month name) in Iranian calendar
1037 * xin n (month number) in Iranian calendar
1038 * xiy y (two digit year) in Iranian calendar
1039 * xiY Y (full year) in Iranian calendar
1041 * xjj j (day number) in Hebrew calendar
1042 * xjF F (month name) in Hebrew calendar
1043 * xjt t (days in month) in Hebrew calendar
1044 * xjx xg (genitive month name) in Hebrew calendar
1045 * xjn n (month number) in Hebrew calendar
1046 * xjY Y (full year) in Hebrew calendar
1048 * xmj j (day number) in Hijri calendar
1049 * xmF F (month name) in Hijri calendar
1050 * xmn n (month number) in Hijri calendar
1051 * xmY Y (full year) in Hijri calendar
1053 * xkY Y (full year) in Thai solar calendar. Months and days are
1054 * identical to the Gregorian calendar
1055 * xoY Y (full year) in Minguo calendar or Juche year.
1056 * Months and days are identical to the
1057 * Gregorian calendar
1058 * xtY Y (full year) in Japanese nengo. Months and days are
1059 * identical to the Gregorian calendar
1061 * Characters enclosed in double quotes will be considered literal (with
1062 * the quotes themselves removed). Unmatched quotes will be considered
1063 * literal quotes. Example:
1065 * "The month is" F => The month is January
1068 * Backslash escaping is also supported.
1070 * Input timestamp is assumed to be pre-normalized to the desired local
1071 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1072 * $ts is UTC if $zone is not given.
1074 * @param $format String
1075 * @param $ts String: 14-character timestamp
1078 * @param $zone DateTimeZone: Timezone of $ts
1079 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1083 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1088 $dateTimeObj = false;
1096 for ( $p = 0; $p < strlen( $format ); $p++
) {
1098 $code = $format[$p];
1099 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1100 $code .= $format[++
$p];
1103 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1104 $code .= $format[++
$p];
1115 $rawToggle = !$rawToggle;
1124 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1128 $hebrew = self
::tsToHebrew( $ts );
1130 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1133 $num = substr( $ts, 6, 2 );
1136 if ( !$dateTimeObj ) {
1137 $dateTimeObj = DateTime
::createFromFormat(
1138 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1141 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1144 $num = intval( substr( $ts, 6, 2 ) );
1148 $iranian = self
::tsToIranian( $ts );
1154 $hijri = self
::tsToHijri( $ts );
1160 $hebrew = self
::tsToHebrew( $ts );
1165 if ( !$dateTimeObj ) {
1166 $dateTimeObj = DateTime
::createFromFormat(
1167 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1170 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1173 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1177 $iranian = self
::tsToIranian( $ts );
1179 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1183 $hijri = self
::tsToHijri( $ts );
1185 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1189 $hebrew = self
::tsToHebrew( $ts );
1191 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1194 $num = substr( $ts, 4, 2 );
1197 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1200 $num = intval( substr( $ts, 4, 2 ) );
1204 $iranian = self
::tsToIranian( $ts );
1210 $hijri = self
::tsToHijri ( $ts );
1216 $hebrew = self
::tsToHebrew( $ts );
1222 $hebrew = self
::tsToHebrew( $ts );
1227 $num = substr( $ts, 0, 4 );
1231 $iranian = self
::tsToIranian( $ts );
1237 $hijri = self
::tsToHijri( $ts );
1243 $hebrew = self
::tsToHebrew( $ts );
1249 $thai = self
::tsToYear( $ts, 'thai' );
1255 $minguo = self
::tsToYear( $ts, 'minguo' );
1261 $tenno = self
::tsToYear( $ts, 'tenno' );
1266 $num = substr( $ts, 2, 2 );
1270 $iranian = self
::tsToIranian( $ts );
1272 $num = substr( $iranian[0], -2 );
1275 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1278 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1281 $h = substr( $ts, 8, 2 );
1282 $num = $h %
12 ?
$h %
12 : 12;
1285 $num = intval( substr( $ts, 8, 2 ) );
1288 $h = substr( $ts, 8, 2 );
1289 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1292 $num = substr( $ts, 8, 2 );
1295 $num = substr( $ts, 10, 2 );
1298 $num = substr( $ts, 12, 2 );
1306 // Pass through string from $dateTimeObj->format()
1307 if ( !$dateTimeObj ) {
1308 $dateTimeObj = DateTime
::createFromFormat(
1309 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1312 $s .= $dateTimeObj->format( $code );
1324 // Pass through number from $dateTimeObj->format()
1325 if ( !$dateTimeObj ) {
1326 $dateTimeObj = DateTime
::createFromFormat(
1327 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1330 $num = $dateTimeObj->format( $code );
1333 # Backslash escaping
1334 if ( $p < strlen( $format ) - 1 ) {
1335 $s .= $format[++
$p];
1342 if ( $p < strlen( $format ) - 1 ) {
1343 $endQuote = strpos( $format, '"', $p +
1 );
1344 if ( $endQuote === false ) {
1345 # No terminating quote, assume literal "
1348 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1352 # Quote at end of string, assume literal "
1359 if ( $num !== false ) {
1360 if ( $rawToggle ||
$raw ) {
1363 } elseif ( $roman ) {
1364 $s .= Language
::romanNumeral( $num );
1366 } elseif ( $hebrewNum ) {
1367 $s .= self
::hebrewNumeral( $num );
1370 $s .= $this->formatNum( $num, true );
1377 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1378 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1381 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1382 * Gregorian dates to Iranian dates. Originally written in C, it
1383 * is released under the terms of GNU Lesser General Public
1384 * License. Conversion to PHP was performed by Niklas Laxström.
1386 * Link: http://www.farsiweb.info/jalali/jalali.c
1392 private static function tsToIranian( $ts ) {
1393 $gy = substr( $ts, 0, 4 ) -1600;
1394 $gm = substr( $ts, 4, 2 ) -1;
1395 $gd = substr( $ts, 6, 2 ) -1;
1397 # Days passed from the beginning (including leap years)
1399 +
floor( ( $gy +
3 ) / 4 )
1400 - floor( ( $gy +
99 ) / 100 )
1401 +
floor( ( $gy +
399 ) / 400 );
1403 // Add days of the past months of this year
1404 for ( $i = 0; $i < $gm; $i++
) {
1405 $gDayNo +
= self
::$GREG_DAYS[$i];
1409 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1413 // Days passed in current month
1414 $gDayNo +
= (int)$gd;
1416 $jDayNo = $gDayNo - 79;
1418 $jNp = floor( $jDayNo / 12053 );
1421 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1424 if ( $jDayNo >= 366 ) {
1425 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1426 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1429 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1430 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1436 return array( $jy, $jm, $jd );
1440 * Converting Gregorian dates to Hijri dates.
1442 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1444 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1450 private static function tsToHijri( $ts ) {
1451 $year = substr( $ts, 0, 4 );
1452 $month = substr( $ts, 4, 2 );
1453 $day = substr( $ts, 6, 2 );
1461 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1462 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1465 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1466 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1467 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1470 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1471 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1474 $zl = $zjd -1948440 +
10632;
1475 $zn = (int)( ( $zl - 1 ) / 10631 );
1476 $zl = $zl - 10631 * $zn +
354;
1477 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1478 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1479 $zm = (int)( ( 24 * $zl ) / 709 );
1480 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1481 $zy = 30 * $zn +
$zj - 30;
1483 return array( $zy, $zm, $zd );
1487 * Converting Gregorian dates to Hebrew dates.
1489 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1490 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1491 * to translate the relevant functions into PHP and release them under
1494 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1495 * and Adar II is 14. In a non-leap year, Adar is 6.
1501 private static function tsToHebrew( $ts ) {
1503 $year = substr( $ts, 0, 4 );
1504 $month = substr( $ts, 4, 2 );
1505 $day = substr( $ts, 6, 2 );
1507 # Calculate Hebrew year
1508 $hebrewYear = $year +
3760;
1510 # Month number when September = 1, August = 12
1512 if ( $month > 12 ) {
1519 # Calculate day of year from 1 September
1521 for ( $i = 1; $i < $month; $i++
) {
1525 # Check if the year is leap
1526 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1529 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1536 # Calculate the start of the Hebrew year
1537 $start = self
::hebrewYearStart( $hebrewYear );
1539 # Calculate next year's start
1540 if ( $dayOfYear <= $start ) {
1541 # Day is before the start of the year - it is the previous year
1543 $nextStart = $start;
1547 # Add days since previous year's 1 September
1549 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1553 # Start of the new (previous) year
1554 $start = self
::hebrewYearStart( $hebrewYear );
1557 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1560 # Calculate Hebrew day of year
1561 $hebrewDayOfYear = $dayOfYear - $start;
1563 # Difference between year's days
1564 $diff = $nextStart - $start;
1565 # Add 12 (or 13 for leap years) days to ignore the difference between
1566 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1567 # difference is only about the year type
1568 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1574 # Check the year pattern, and is leap year
1575 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1576 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1577 # and non-leap years
1578 $yearPattern = $diff %
30;
1579 # Check if leap year
1580 $isLeap = $diff >= 30;
1582 # Calculate day in the month from number of day in the Hebrew year
1583 # Don't check Adar - if the day is not in Adar, we will stop before;
1584 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1585 $hebrewDay = $hebrewDayOfYear;
1588 while ( $hebrewMonth <= 12 ) {
1589 # Calculate days in this month
1590 if ( $isLeap && $hebrewMonth == 6 ) {
1591 # Adar in a leap year
1593 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1595 if ( $hebrewDay <= $days ) {
1599 # Subtract the days of Adar I
1600 $hebrewDay -= $days;
1603 if ( $hebrewDay <= $days ) {
1609 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1610 # Cheshvan in a complete year (otherwise as the rule below)
1612 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1613 # Kislev in an incomplete year (otherwise as the rule below)
1616 # Odd months have 30 days, even have 29
1617 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1619 if ( $hebrewDay <= $days ) {
1620 # In the current month
1623 # Subtract the days of the current month
1624 $hebrewDay -= $days;
1625 # Try in the next month
1630 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1634 * This calculates the Hebrew year start, as days since 1 September.
1635 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1636 * Used for Hebrew date.
1642 private static function hebrewYearStart( $year ) {
1643 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1644 $b = intval( ( $year - 1 ) %
4 );
1645 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1649 $Mar = intval( $m );
1655 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1656 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1658 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1660 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1664 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1669 * Algorithm to convert Gregorian dates to Thai solar dates,
1670 * Minguo dates or Minguo dates.
1672 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1673 * http://en.wikipedia.org/wiki/Minguo_calendar
1674 * http://en.wikipedia.org/wiki/Japanese_era_name
1676 * @param $ts String: 14-character timestamp
1677 * @param $cName String: calender name
1678 * @return Array: converted year, month, day
1680 private static function tsToYear( $ts, $cName ) {
1681 $gy = substr( $ts, 0, 4 );
1682 $gm = substr( $ts, 4, 2 );
1683 $gd = substr( $ts, 6, 2 );
1685 if ( !strcmp( $cName, 'thai' ) ) {
1687 # Add 543 years to the Gregorian calendar
1688 # Months and days are identical
1689 $gy_offset = $gy +
543;
1690 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1692 # Deduct 1911 years from the Gregorian calendar
1693 # Months and days are identical
1694 $gy_offset = $gy - 1911;
1695 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1696 # Nengō dates up to Meiji period
1697 # Deduct years from the Gregorian calendar
1698 # depending on the nengo periods
1699 # Months and days are identical
1700 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1702 $gy_gannen = $gy - 1868 +
1;
1703 $gy_offset = $gy_gannen;
1704 if ( $gy_gannen == 1 ) {
1707 $gy_offset = '明治' . $gy_offset;
1709 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1710 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1711 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1712 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1713 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1717 $gy_gannen = $gy - 1912 +
1;
1718 $gy_offset = $gy_gannen;
1719 if ( $gy_gannen == 1 ) {
1722 $gy_offset = '大正' . $gy_offset;
1724 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1725 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1726 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1730 $gy_gannen = $gy - 1926 +
1;
1731 $gy_offset = $gy_gannen;
1732 if ( $gy_gannen == 1 ) {
1735 $gy_offset = '昭和' . $gy_offset;
1738 $gy_gannen = $gy - 1989 +
1;
1739 $gy_offset = $gy_gannen;
1740 if ( $gy_gannen == 1 ) {
1743 $gy_offset = '平成' . $gy_offset;
1749 return array( $gy_offset, $gm, $gd );
1753 * Roman number formatting up to 10000
1759 static function romanNumeral( $num ) {
1760 static $table = array(
1761 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1762 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1763 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1764 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1767 $num = intval( $num );
1768 if ( $num > 10000 ||
$num <= 0 ) {
1773 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1774 if ( $num >= $pow10 ) {
1775 $s .= $table[$i][(int)floor( $num / $pow10 )];
1777 $num = $num %
$pow10;
1783 * Hebrew Gematria number formatting up to 9999
1789 static function hebrewNumeral( $num ) {
1790 static $table = array(
1791 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1792 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1793 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1794 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1797 $num = intval( $num );
1798 if ( $num > 9999 ||
$num <= 0 ) {
1803 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1804 if ( $num >= $pow10 ) {
1805 if ( $num == 15 ||
$num == 16 ) {
1806 $s .= $table[0][9] . $table[0][$num - 9];
1809 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1810 if ( $pow10 == 1000 ) {
1815 $num = $num %
$pow10;
1817 if ( strlen( $s ) == 2 ) {
1820 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1821 $str .= substr( $s, strlen( $s ) - 2, 2 );
1823 $start = substr( $str, 0, strlen( $str ) - 2 );
1824 $end = substr( $str, strlen( $str ) - 2 );
1827 $str = $start . 'ך';
1830 $str = $start . 'ם';
1833 $str = $start . 'ן';
1836 $str = $start . 'ף';
1839 $str = $start . 'ץ';
1846 * Used by date() and time() to adjust the time output.
1848 * @param $ts Int the time in date('YmdHis') format
1849 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1850 * get user timecorrection setting)
1853 function userAdjust( $ts, $tz = false ) {
1854 global $wgUser, $wgLocalTZoffset;
1856 if ( $tz === false ) {
1857 $tz = $wgUser->getOption( 'timecorrection' );
1860 $data = explode( '|', $tz, 3 );
1862 if ( $data[0] == 'ZoneInfo' ) {
1863 wfSuppressWarnings();
1864 $userTZ = timezone_open( $data[2] );
1865 wfRestoreWarnings();
1866 if ( $userTZ !== false ) {
1867 $date = date_create( $ts, timezone_open( 'UTC' ) );
1868 date_timezone_set( $date, $userTZ );
1869 $date = date_format( $date, 'YmdHis' );
1872 # Unrecognized timezone, default to 'Offset' with the stored offset.
1873 $data[0] = 'Offset';
1877 if ( $data[0] == 'System' ||
$tz == '' ) {
1878 # Global offset in minutes.
1879 if ( isset( $wgLocalTZoffset ) ) {
1880 $minDiff = $wgLocalTZoffset;
1882 } elseif ( $data[0] == 'Offset' ) {
1883 $minDiff = intval( $data[1] );
1885 $data = explode( ':', $tz );
1886 if ( count( $data ) == 2 ) {
1887 $data[0] = intval( $data[0] );
1888 $data[1] = intval( $data[1] );
1889 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1890 if ( $data[0] < 0 ) {
1891 $minDiff = -$minDiff;
1894 $minDiff = intval( $data[0] ) * 60;
1898 # No difference ? Return time unchanged
1899 if ( 0 == $minDiff ) {
1903 wfSuppressWarnings(); // E_STRICT system time bitching
1904 # Generate an adjusted date; take advantage of the fact that mktime
1905 # will normalize out-of-range values so we don't have to split $minDiff
1906 # into hours and minutes.
1908 (int)substr( $ts, 8, 2 ) ), # Hours
1909 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1910 (int)substr( $ts, 12, 2 ), # Seconds
1911 (int)substr( $ts, 4, 2 ), # Month
1912 (int)substr( $ts, 6, 2 ), # Day
1913 (int)substr( $ts, 0, 4 ) ); # Year
1915 $date = date( 'YmdHis', $t );
1916 wfRestoreWarnings();
1922 * This is meant to be used by time(), date(), and timeanddate() to get
1923 * the date preference they're supposed to use, it should be used in
1927 * function timeanddate([...], $format = true) {
1928 * $datePreference = $this->dateFormat($format);
1933 * @param $usePrefs Mixed: if true, the user's preference is used
1934 * if false, the site/language default is used
1935 * if int/string, assumed to be a format.
1938 function dateFormat( $usePrefs = true ) {
1941 if ( is_bool( $usePrefs ) ) {
1943 $datePreference = $wgUser->getDatePreference();
1945 $datePreference = (string)User
::getDefaultOption( 'date' );
1948 $datePreference = (string)$usePrefs;
1952 if ( $datePreference == '' ) {
1956 return $datePreference;
1960 * Get a format string for a given type and preference
1961 * @param $type string May be date, time or both
1962 * @param $pref string The format name as it appears in Messages*.php
1964 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1968 function getDateFormatString( $type, $pref ) {
1969 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1970 if ( $pref == 'default' ) {
1971 $pref = $this->getDefaultDateFormat();
1972 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1974 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1976 if ( $type === 'pretty' && $df === null ) {
1977 $df = $this->getDateFormatString( 'date', $pref );
1980 if ( $df === null ) {
1981 $pref = $this->getDefaultDateFormat();
1982 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1985 $this->dateFormatStrings
[$type][$pref] = $df;
1987 return $this->dateFormatStrings
[$type][$pref];
1991 * @param $ts Mixed: the time format which needs to be turned into a
1992 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1993 * @param $adj Bool: whether to adjust the time output according to the
1994 * user configured offset ($timecorrection)
1995 * @param $format Mixed: true to use user's date format preference
1996 * @param $timecorrection String|bool the time offset as returned by
1997 * validateTimeZone() in Special:Preferences
2000 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2001 $ts = wfTimestamp( TS_MW
, $ts );
2003 $ts = $this->userAdjust( $ts, $timecorrection );
2005 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2006 return $this->sprintfDate( $df, $ts );
2010 * @param $ts Mixed: the time format which needs to be turned into a
2011 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2012 * @param $adj Bool: whether to adjust the time output according to the
2013 * user configured offset ($timecorrection)
2014 * @param $format Mixed: true to use user's date format preference
2015 * @param $timecorrection String|bool the time offset as returned by
2016 * validateTimeZone() in Special:Preferences
2019 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2020 $ts = wfTimestamp( TS_MW
, $ts );
2022 $ts = $this->userAdjust( $ts, $timecorrection );
2024 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2025 return $this->sprintfDate( $df, $ts );
2029 * @param $ts Mixed: the time format which needs to be turned into a
2030 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2031 * @param $adj Bool: whether to adjust the time output according to the
2032 * user configured offset ($timecorrection)
2033 * @param $format Mixed: what format to return, if it's false output the
2034 * default one (default true)
2035 * @param $timecorrection String|bool the time offset as returned by
2036 * validateTimeZone() in Special:Preferences
2039 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2040 $ts = wfTimestamp( TS_MW
, $ts );
2042 $ts = $this->userAdjust( $ts, $timecorrection );
2044 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2045 return $this->sprintfDate( $df, $ts );
2049 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2053 * @param integer $seconds The amount of seconds.
2054 * @param array $chosenIntervals The intervals to enable.
2058 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2059 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2061 $segments = array();
2063 foreach ( $intervals as $intervalName => $intervalValue ) {
2064 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2065 $segments[] = $message->inLanguage( $this )->escaped();
2068 return $this->listToText( $segments );
2072 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2073 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2077 * @param integer $seconds The amount of seconds.
2078 * @param array $chosenIntervals The intervals to enable.
2082 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2083 if ( empty( $chosenIntervals ) ) {
2084 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2087 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2088 $sortedNames = array_keys( $intervals );
2089 $smallestInterval = array_pop( $sortedNames );
2091 $segments = array();
2093 foreach ( $intervals as $name => $length ) {
2094 $value = floor( $seconds / $length );
2096 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2097 $seconds -= $value * $length;
2098 $segments[$name] = $value;
2106 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2108 * @param $type String: can be 'date', 'time' or 'both'
2109 * @param $ts Mixed: the time format which needs to be turned into a
2110 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2111 * @param $user User object used to get preferences for timezone and format
2112 * @param $options Array, can contain the following keys:
2113 * - 'timecorrection': time correction, can have the following values:
2114 * - true: use user's preference
2115 * - false: don't use time correction
2116 * - integer: value of time correction in minutes
2117 * - 'format': format to use, can have the following values:
2118 * - true: use user's preference
2119 * - false: use default preference
2120 * - string: format to use
2124 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2125 $ts = wfTimestamp( TS_MW
, $ts );
2126 $options +
= array( 'timecorrection' => true, 'format' => true );
2127 if ( $options['timecorrection'] !== false ) {
2128 if ( $options['timecorrection'] === true ) {
2129 $offset = $user->getOption( 'timecorrection' );
2131 $offset = $options['timecorrection'];
2133 $ts = $this->userAdjust( $ts, $offset );
2135 if ( $options['format'] === true ) {
2136 $format = $user->getDatePreference();
2138 $format = $options['format'];
2140 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2141 return $this->sprintfDate( $df, $ts );
2145 * Get the formatted date for the given timestamp and formatted for
2148 * @param $ts Mixed: the time format which needs to be turned into a
2149 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2150 * @param $user User object used to get preferences for timezone and format
2151 * @param $options Array, can contain the following keys:
2152 * - 'timecorrection': time correction, can have the following values:
2153 * - true: use user's preference
2154 * - false: don't use time correction
2155 * - integer: value of time correction in minutes
2156 * - 'format': format to use, can have the following values:
2157 * - true: use user's preference
2158 * - false: use default preference
2159 * - string: format to use
2163 public function userDate( $ts, User
$user, array $options = array() ) {
2164 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2168 * Get the formatted time for the given timestamp and formatted for
2171 * @param $ts Mixed: the time format which needs to be turned into a
2172 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2173 * @param $user User object used to get preferences for timezone and format
2174 * @param $options Array, can contain the following keys:
2175 * - 'timecorrection': time correction, can have the following values:
2176 * - true: use user's preference
2177 * - false: don't use time correction
2178 * - integer: value of time correction in minutes
2179 * - 'format': format to use, can have the following values:
2180 * - true: use user's preference
2181 * - false: use default preference
2182 * - string: format to use
2186 public function userTime( $ts, User
$user, array $options = array() ) {
2187 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2191 * Get the formatted date and time for the given timestamp and formatted for
2194 * @param $ts Mixed: the time format which needs to be turned into a
2195 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2196 * @param $user User object used to get preferences for timezone and format
2197 * @param $options Array, can contain the following keys:
2198 * - 'timecorrection': time correction, can have the following values:
2199 * - true: use user's preference
2200 * - false: don't use time correction
2201 * - integer: value of time correction in minutes
2202 * - 'format': format to use, can have the following values:
2203 * - true: use user's preference
2204 * - false: use default preference
2205 * - string: format to use
2209 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2210 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2214 * Convert an MWTimestamp into a pretty human-readable timestamp using
2215 * the given user preferences and relative base time.
2217 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2218 * on your timestamp object, which will then call this function. Calling
2219 * this function directly will cause hooks to be skipped over.
2221 * @see MWTimestamp::getHumanTimestamp
2222 * @param MWTimestamp $ts Timestamp to prettify
2223 * @param MWTimestamp $relativeTo Base timestamp
2224 * @param User $user User preferences to use
2225 * @return string Human timestamp
2228 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2229 $diff = $ts->diff( $relativeTo );
2230 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) - (int)$relativeTo->timestamp
->format( 'w' ) );
2231 $days = $diff->days ?
: (int)$diffDay;
2232 if ( $diff->invert ||
$days > 5 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' ) ) {
2233 // Timestamps are in different years: use full timestamp
2234 // Also do full timestamp for future dates
2236 * @FIXME Add better handling of future timestamps.
2238 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2239 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2240 } elseif ( $days > 5 ) {
2241 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2242 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2243 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2244 } elseif ( $days > 1 ) {
2245 // Timestamp within the past week: show the day of the week and time
2246 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2247 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2248 $ts = wfMessage( "$weekday-at" )
2249 ->inLanguage( $this )
2250 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2252 } elseif ( $days == 1 ) {
2253 // Timestamp was yesterday: say 'yesterday' and the time.
2254 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2255 $ts = wfMessage( 'yesterday-at' )
2256 ->inLanguage( $this )
2257 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2259 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2260 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2261 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2262 $ts = wfMessage( 'today-at' )
2263 ->inLanguage( $this )
2264 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2267 // From here on in, the timestamp was soon enough ago so that we can simply say
2268 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2269 } elseif ( $diff->h
== 1 ) {
2270 // Less than 90 minutes, but more than an hour ago.
2271 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2272 } elseif ( $diff->i
>= 1 ) {
2273 // A few minutes ago.
2274 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2275 } elseif ( $diff->s
>= 30 ) {
2276 // Less than a minute, but more than 30 sec ago.
2277 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2279 // Less than 30 seconds ago.
2280 $ts = wfMessage( 'just-now' )->text();
2287 * @param $key string
2288 * @return array|null
2290 function getMessage( $key ) {
2291 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2297 function getAllMessages() {
2298 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2307 function iconv( $in, $out, $string ) {
2308 # This is a wrapper for iconv in all languages except esperanto,
2309 # which does some nasty x-conversions beforehand
2311 # Even with //IGNORE iconv can whine about illegal characters in
2312 # *input* string. We just ignore those too.
2313 # REF: http://bugs.php.net/bug.php?id=37166
2314 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2315 wfSuppressWarnings();
2316 $text = iconv( $in, $out . '//IGNORE', $string );
2317 wfRestoreWarnings();
2321 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2324 * @param $matches array
2325 * @return mixed|string
2327 function ucwordbreaksCallbackAscii( $matches ) {
2328 return $this->ucfirst( $matches[1] );
2332 * @param $matches array
2335 function ucwordbreaksCallbackMB( $matches ) {
2336 return mb_strtoupper( $matches[0] );
2340 * @param $matches array
2343 function ucCallback( $matches ) {
2344 list( $wikiUpperChars ) = self
::getCaseMaps();
2345 return strtr( $matches[1], $wikiUpperChars );
2349 * @param $matches array
2352 function lcCallback( $matches ) {
2353 list( , $wikiLowerChars ) = self
::getCaseMaps();
2354 return strtr( $matches[1], $wikiLowerChars );
2358 * @param $matches array
2361 function ucwordsCallbackMB( $matches ) {
2362 return mb_strtoupper( $matches[0] );
2366 * @param $matches array
2369 function ucwordsCallbackWiki( $matches ) {
2370 list( $wikiUpperChars ) = self
::getCaseMaps();
2371 return strtr( $matches[0], $wikiUpperChars );
2375 * Make a string's first character uppercase
2377 * @param $str string
2381 function ucfirst( $str ) {
2383 if ( $o < 96 ) { // if already uppercase...
2385 } elseif ( $o < 128 ) {
2386 return ucfirst( $str ); // use PHP's ucfirst()
2388 // fall back to more complex logic in case of multibyte strings
2389 return $this->uc( $str, true );
2394 * Convert a string to uppercase
2396 * @param $str string
2397 * @param $first bool
2401 function uc( $str, $first = false ) {
2402 if ( function_exists( 'mb_strtoupper' ) ) {
2404 if ( $this->isMultibyte( $str ) ) {
2405 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2407 return ucfirst( $str );
2410 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2413 if ( $this->isMultibyte( $str ) ) {
2414 $x = $first ?
'^' : '';
2415 return preg_replace_callback(
2416 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2417 array( $this, 'ucCallback' ),
2421 return $first ?
ucfirst( $str ) : strtoupper( $str );
2427 * @param $str string
2428 * @return mixed|string
2430 function lcfirst( $str ) {
2433 return strval( $str );
2434 } elseif ( $o >= 128 ) {
2435 return $this->lc( $str, true );
2436 } elseif ( $o > 96 ) {
2439 $str[0] = strtolower( $str[0] );
2445 * @param $str string
2446 * @param $first bool
2447 * @return mixed|string
2449 function lc( $str, $first = false ) {
2450 if ( function_exists( 'mb_strtolower' ) ) {
2452 if ( $this->isMultibyte( $str ) ) {
2453 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2455 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2458 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2461 if ( $this->isMultibyte( $str ) ) {
2462 $x = $first ?
'^' : '';
2463 return preg_replace_callback(
2464 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2465 array( $this, 'lcCallback' ),
2469 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2475 * @param $str string
2478 function isMultibyte( $str ) {
2479 return (bool)preg_match( '/[\x80-\xff]/', $str );
2483 * @param $str string
2484 * @return mixed|string
2486 function ucwords( $str ) {
2487 if ( $this->isMultibyte( $str ) ) {
2488 $str = $this->lc( $str );
2490 // regexp to find first letter in each word (i.e. after each space)
2491 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2493 // function to use to capitalize a single char
2494 if ( function_exists( 'mb_strtoupper' ) ) {
2495 return preg_replace_callback(
2497 array( $this, 'ucwordsCallbackMB' ),
2501 return preg_replace_callback(
2503 array( $this, 'ucwordsCallbackWiki' ),
2508 return ucwords( strtolower( $str ) );
2513 * capitalize words at word breaks
2515 * @param $str string
2518 function ucwordbreaks( $str ) {
2519 if ( $this->isMultibyte( $str ) ) {
2520 $str = $this->lc( $str );
2522 // since \b doesn't work for UTF-8, we explicitely define word break chars
2523 $breaks = "[ \-\(\)\}\{\.,\?!]";
2525 // find first letter after word break
2526 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2528 if ( function_exists( 'mb_strtoupper' ) ) {
2529 return preg_replace_callback(
2531 array( $this, 'ucwordbreaksCallbackMB' ),
2535 return preg_replace_callback(
2537 array( $this, 'ucwordsCallbackWiki' ),
2542 return preg_replace_callback(
2543 '/\b([\w\x80-\xff]+)\b/',
2544 array( $this, 'ucwordbreaksCallbackAscii' ),
2551 * Return a case-folded representation of $s
2553 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2554 * and $s2 are the same except for the case of their characters. It is not
2555 * necessary for the value returned to make sense when displayed.
2557 * Do *not* perform any other normalisation in this function. If a caller
2558 * uses this function when it should be using a more general normalisation
2559 * function, then fix the caller.
2565 function caseFold( $s ) {
2566 return $this->uc( $s );
2573 function checkTitleEncoding( $s ) {
2574 if ( is_array( $s ) ) {
2575 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2577 if ( StringUtils
::isUtf8( $s ) ) {
2581 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2587 function fallback8bitEncoding() {
2588 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2592 * Most writing systems use whitespace to break up words.
2593 * Some languages such as Chinese don't conventionally do this,
2594 * which requires special handling when breaking up words for
2599 function hasWordBreaks() {
2604 * Some languages such as Chinese require word segmentation,
2605 * Specify such segmentation when overridden in derived class.
2607 * @param $string String
2610 function segmentByWord( $string ) {
2615 * Some languages have special punctuation need to be normalized.
2616 * Make such changes here.
2618 * @param $string String
2621 function normalizeForSearch( $string ) {
2622 return self
::convertDoubleWidth( $string );
2626 * convert double-width roman characters to single-width.
2627 * range: ff00-ff5f ~= 0020-007f
2629 * @param $string string
2633 protected static function convertDoubleWidth( $string ) {
2634 static $full = null;
2635 static $half = null;
2637 if ( $full === null ) {
2638 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2639 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2640 $full = str_split( $fullWidth, 3 );
2641 $half = str_split( $halfWidth );
2644 $string = str_replace( $full, $half, $string );
2649 * @param $string string
2650 * @param $pattern string
2653 protected static function insertSpace( $string, $pattern ) {
2654 $string = preg_replace( $pattern, " $1 ", $string );
2655 $string = preg_replace( '/ +/', ' ', $string );
2660 * @param $termsArray array
2663 function convertForSearchResult( $termsArray ) {
2664 # some languages, e.g. Chinese, need to do a conversion
2665 # in order for search results to be displayed correctly
2670 * Get the first character of a string.
2675 function firstChar( $s ) {
2678 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2679 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2684 if ( isset( $matches[1] ) ) {
2685 if ( strlen( $matches[1] ) != 3 ) {
2689 // Break down Hangul syllables to grab the first jamo
2690 $code = utf8ToCodepoint( $matches[1] );
2691 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2693 } elseif ( $code < 0xb098 ) {
2694 return "\xe3\x84\xb1";
2695 } elseif ( $code < 0xb2e4 ) {
2696 return "\xe3\x84\xb4";
2697 } elseif ( $code < 0xb77c ) {
2698 return "\xe3\x84\xb7";
2699 } elseif ( $code < 0xb9c8 ) {
2700 return "\xe3\x84\xb9";
2701 } elseif ( $code < 0xbc14 ) {
2702 return "\xe3\x85\x81";
2703 } elseif ( $code < 0xc0ac ) {
2704 return "\xe3\x85\x82";
2705 } elseif ( $code < 0xc544 ) {
2706 return "\xe3\x85\x85";
2707 } elseif ( $code < 0xc790 ) {
2708 return "\xe3\x85\x87";
2709 } elseif ( $code < 0xcc28 ) {
2710 return "\xe3\x85\x88";
2711 } elseif ( $code < 0xce74 ) {
2712 return "\xe3\x85\x8a";
2713 } elseif ( $code < 0xd0c0 ) {
2714 return "\xe3\x85\x8b";
2715 } elseif ( $code < 0xd30c ) {
2716 return "\xe3\x85\x8c";
2717 } elseif ( $code < 0xd558 ) {
2718 return "\xe3\x85\x8d";
2720 return "\xe3\x85\x8e";
2727 function initEncoding() {
2728 # Some languages may have an alternate char encoding option
2729 # (Esperanto X-coding, Japanese furigana conversion, etc)
2730 # If this language is used as the primary content language,
2731 # an override to the defaults can be set here on startup.
2738 function recodeForEdit( $s ) {
2739 # For some languages we'll want to explicitly specify
2740 # which characters make it into the edit box raw
2741 # or are converted in some way or another.
2742 global $wgEditEncoding;
2743 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2746 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2754 function recodeInput( $s ) {
2755 # Take the previous into account.
2756 global $wgEditEncoding;
2757 if ( $wgEditEncoding != '' ) {
2758 $enc = $wgEditEncoding;
2762 if ( $enc == 'UTF-8' ) {
2765 return $this->iconv( $enc, 'UTF-8', $s );
2770 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2771 * also cleans up certain backwards-compatible sequences, converting them
2772 * to the modern Unicode equivalent.
2774 * This is language-specific for performance reasons only.
2780 function normalize( $s ) {
2781 global $wgAllUnicodeFixes;
2782 $s = UtfNormal
::cleanUp( $s );
2783 if ( $wgAllUnicodeFixes ) {
2784 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2785 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2792 * Transform a string using serialized data stored in the given file (which
2793 * must be in the serialized subdirectory of $IP). The file contains pairs
2794 * mapping source characters to destination characters.
2796 * The data is cached in process memory. This will go faster if you have the
2797 * FastStringSearch extension.
2799 * @param $file string
2800 * @param $string string
2802 * @throws MWException
2805 function transformUsingPairFile( $file, $string ) {
2806 if ( !isset( $this->transformData
[$file] ) ) {
2807 $data = wfGetPrecompiledData( $file );
2808 if ( $data === false ) {
2809 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2811 $this->transformData
[$file] = new ReplacementArray( $data );
2813 return $this->transformData
[$file]->replace( $string );
2817 * For right-to-left language support
2822 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2826 * Return the correct HTML 'dir' attribute value for this language.
2830 return $this->isRTL() ?
'rtl' : 'ltr';
2834 * Return 'left' or 'right' as appropriate alignment for line-start
2835 * for this language's text direction.
2837 * Should be equivalent to CSS3 'start' text-align value....
2841 function alignStart() {
2842 return $this->isRTL() ?
'right' : 'left';
2846 * Return 'right' or 'left' as appropriate alignment for line-end
2847 * for this language's text direction.
2849 * Should be equivalent to CSS3 'end' text-align value....
2853 function alignEnd() {
2854 return $this->isRTL() ?
'left' : 'right';
2858 * A hidden direction mark (LRM or RLM), depending on the language direction.
2859 * Unlike getDirMark(), this function returns the character as an HTML entity.
2860 * This function should be used when the output is guaranteed to be HTML,
2861 * because it makes the output HTML source code more readable. When
2862 * the output is plain text or can be escaped, getDirMark() should be used.
2864 * @param $opposite Boolean Get the direction mark opposite to your language
2868 function getDirMarkEntity( $opposite = false ) {
2870 return $this->isRTL() ?
'‎' : '‏';
2872 return $this->isRTL() ?
'‏' : '‎';
2876 * A hidden direction mark (LRM or RLM), depending on the language direction.
2877 * This function produces them as invisible Unicode characters and
2878 * the output may be hard to read and debug, so it should only be used
2879 * when the output is plain text or can be escaped. When the output is
2880 * HTML, use getDirMarkEntity() instead.
2882 * @param $opposite Boolean Get the direction mark opposite to your language
2885 function getDirMark( $opposite = false ) {
2886 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2887 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2889 return $this->isRTL() ?
$lrm : $rlm;
2891 return $this->isRTL() ?
$rlm : $lrm;
2897 function capitalizeAllNouns() {
2898 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2902 * An arrow, depending on the language direction.
2904 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2907 function getArrow( $direction = 'forwards' ) {
2908 switch ( $direction ) {
2910 return $this->isRTL() ?
'←' : '→';
2912 return $this->isRTL() ?
'→' : '←';
2925 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2929 function linkPrefixExtension() {
2930 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2936 function getMagicWords() {
2937 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2940 protected function doMagicHook() {
2941 if ( $this->mMagicHookDone
) {
2944 $this->mMagicHookDone
= true;
2945 wfProfileIn( 'LanguageGetMagic' );
2946 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2947 wfProfileOut( 'LanguageGetMagic' );
2951 * Fill a MagicWord object with data from here
2955 function getMagic( $mw ) {
2956 $this->doMagicHook();
2958 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2959 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2961 $magicWords = $this->getMagicWords();
2962 if ( isset( $magicWords[$mw->mId
] ) ) {
2963 $rawEntry = $magicWords[$mw->mId
];
2969 if ( !is_array( $rawEntry ) ) {
2970 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2972 $mw->mCaseSensitive
= $rawEntry[0];
2973 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2978 * Add magic words to the extension array
2980 * @param $newWords array
2982 function addMagicWordsByLang( $newWords ) {
2983 $fallbackChain = $this->getFallbackLanguages();
2984 $fallbackChain = array_reverse( $fallbackChain );
2985 foreach ( $fallbackChain as $code ) {
2986 if ( isset( $newWords[$code] ) ) {
2987 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2993 * Get special page names, as an associative array
2994 * case folded alias => real name
2996 function getSpecialPageAliases() {
2997 // Cache aliases because it may be slow to load them
2998 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3000 $this->mExtendedSpecialPageAliases
=
3001 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3002 wfRunHooks( 'LanguageGetSpecialPageAliases',
3003 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3006 return $this->mExtendedSpecialPageAliases
;
3010 * Italic is unsuitable for some languages
3012 * @param $text String: the text to be emphasized.
3015 function emphasize( $text ) {
3016 return "<em>$text</em>";
3020 * Normally we output all numbers in plain en_US style, that is
3021 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3022 * point twohundredthirtyfive. However this is not suitable for all
3023 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3024 * Icelandic just want to use commas instead of dots, and dots instead
3025 * of commas like "293.291,235".
3027 * An example of this function being called:
3029 * wfMessage( 'message' )->numParams( $num )->text()
3032 * See LanguageGu.php for the Gujarati implementation and
3033 * $separatorTransformTable on MessageIs.php for
3034 * the , => . and . => , implementation.
3036 * @todo check if it's viable to use localeconv() for the decimal
3038 * @param $number Mixed: the string to be formatted, should be an integer
3039 * or a floating point number.
3040 * @param $nocommafy Bool: set to true for special numbers like dates
3043 public function formatNum( $number, $nocommafy = false ) {
3044 global $wgTranslateNumerals;
3045 if ( !$nocommafy ) {
3046 $number = $this->commafy( $number );
3047 $s = $this->separatorTransformTable();
3049 $number = strtr( $number, $s );
3053 if ( $wgTranslateNumerals ) {
3054 $s = $this->digitTransformTable();
3056 $number = strtr( $number, $s );
3064 * Front-end for non-commafied formatNum
3066 * @param mixed $number the string to be formatted, should be an integer
3067 * or a floating point number.
3071 public function formatNumNoSeparators( $number ) {
3072 return $this->formatNum( $number, true );
3076 * @param $number string
3079 function parseFormattedNumber( $number ) {
3080 $s = $this->digitTransformTable();
3082 $number = strtr( $number, array_flip( $s ) );
3085 $s = $this->separatorTransformTable();
3087 $number = strtr( $number, array_flip( $s ) );
3090 $number = strtr( $number, array( ',' => '' ) );
3095 * Adds commas to a given number
3097 * @param $number mixed
3100 function commafy( $number ) {
3101 $digitGroupingPattern = $this->digitGroupingPattern();
3102 if ( $number === null ) {
3106 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3107 // default grouping is at thousands, use the same for ###,###,### pattern too.
3108 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3110 // Ref: http://cldr.unicode.org/translation/number-patterns
3112 if ( intval( $number ) < 0 ) {
3113 // For negative numbers apply the algorithm like positive number and add sign.
3115 $number = substr( $number, 1 );
3117 $integerPart = array();
3118 $decimalPart = array();
3119 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3120 preg_match( "/\d+/", $number, $integerPart );
3121 preg_match( "/\.\d*/", $number, $decimalPart );
3122 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3123 if ( $groupedNumber === $number ) {
3124 // the string does not have any number part. Eg: .12345
3125 return $sign . $groupedNumber;
3127 $start = $end = strlen( $integerPart[0] );
3128 while ( $start > 0 ) {
3129 $match = $matches[0][$numMatches - 1];
3130 $matchLen = strlen( $match );
3131 $start = $end - $matchLen;
3135 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3137 if ( $numMatches > 1 ) {
3138 // use the last pattern for the rest of the number
3142 $groupedNumber = "," . $groupedNumber;
3145 return $sign . $groupedNumber;
3152 function digitGroupingPattern() {
3153 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3159 function digitTransformTable() {
3160 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3166 function separatorTransformTable() {
3167 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3171 * Take a list of strings and build a locale-friendly comma-separated
3172 * list, using the local comma-separator message.
3173 * The last two strings are chained with an "and".
3174 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3179 function listToText( array $l ) {
3180 $m = count( $l ) - 1;
3185 $and = $this->getMessageFromDB( 'and' );
3186 $space = $this->getMessageFromDB( 'word-separator' );
3188 $comma = $this->getMessageFromDB( 'comma-separator' );
3192 for ( $i = $m - 1; $i >= 0; $i-- ) {
3193 if ( $i == $m - 1 ) {
3194 $s = $l[$i] . $and . $space . $s;
3196 $s = $l[$i] . $comma . $s;
3203 * Take a list of strings and build a locale-friendly comma-separated
3204 * list, using the local comma-separator message.
3205 * @param $list array of strings to put in a comma list
3208 function commaList( array $list ) {
3210 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3216 * Take a list of strings and build a locale-friendly semicolon-separated
3217 * list, using the local semicolon-separator message.
3218 * @param $list array of strings to put in a semicolon list
3221 function semicolonList( array $list ) {
3223 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3229 * Same as commaList, but separate it with the pipe instead.
3230 * @param $list array of strings to put in a pipe list
3233 function pipeList( array $list ) {
3235 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3241 * Truncate a string to a specified length in bytes, appending an optional
3242 * string (e.g. for ellipses)
3244 * The database offers limited byte lengths for some columns in the database;
3245 * multi-byte character sets mean we need to ensure that only whole characters
3246 * are included, otherwise broken characters can be passed to the user
3248 * If $length is negative, the string will be truncated from the beginning
3250 * @param $string String to truncate
3251 * @param $length Int: maximum length (including ellipses)
3252 * @param $ellipsis String to append to the truncated text
3253 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3254 * $adjustLength was introduced in 1.18, before that behaved as if false.
3257 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3258 # Use the localized ellipsis character
3259 if ( $ellipsis == '...' ) {
3260 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3262 # Check if there is no need to truncate
3263 if ( $length == 0 ) {
3264 return $ellipsis; // convention
3265 } elseif ( strlen( $string ) <= abs( $length ) ) {
3266 return $string; // no need to truncate
3268 $stringOriginal = $string;
3269 # If ellipsis length is >= $length then we can't apply $adjustLength
3270 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3271 $string = $ellipsis; // this can be slightly unexpected
3272 # Otherwise, truncate and add ellipsis...
3274 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3275 if ( $length > 0 ) {
3276 $length -= $eLength;
3277 $string = substr( $string, 0, $length ); // xyz...
3278 $string = $this->removeBadCharLast( $string );
3279 $string = $string . $ellipsis;
3281 $length +
= $eLength;
3282 $string = substr( $string, $length ); // ...xyz
3283 $string = $this->removeBadCharFirst( $string );
3284 $string = $ellipsis . $string;
3287 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3288 # This check is *not* redundant if $adjustLength, due to the single case where
3289 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3290 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3293 return $stringOriginal;
3298 * Remove bytes that represent an incomplete Unicode character
3299 * at the end of string (e.g. bytes of the char are missing)
3301 * @param $string String
3304 protected function removeBadCharLast( $string ) {
3305 if ( $string != '' ) {
3306 $char = ord( $string[strlen( $string ) - 1] );
3308 if ( $char >= 0xc0 ) {
3309 # We got the first byte only of a multibyte char; remove it.
3310 $string = substr( $string, 0, -1 );
3311 } elseif ( $char >= 0x80 &&
3312 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3313 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3315 # We chopped in the middle of a character; remove it
3323 * Remove bytes that represent an incomplete Unicode character
3324 * at the start of string (e.g. bytes of the char are missing)
3326 * @param $string String
3329 protected function removeBadCharFirst( $string ) {
3330 if ( $string != '' ) {
3331 $char = ord( $string[0] );
3332 if ( $char >= 0x80 && $char < 0xc0 ) {
3333 # We chopped in the middle of a character; remove the whole thing
3334 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3341 * Truncate a string of valid HTML to a specified length in bytes,
3342 * appending an optional string (e.g. for ellipses), and return valid HTML
3344 * This is only intended for styled/linked text, such as HTML with
3345 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3346 * Also, this will not detect things like "display:none" CSS.
3348 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3350 * @param string $text HTML string to truncate
3351 * @param int $length (zero/positive) Maximum length (including ellipses)
3352 * @param string $ellipsis String to append to the truncated text
3355 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3356 # Use the localized ellipsis character
3357 if ( $ellipsis == '...' ) {
3358 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3360 # Check if there is clearly no need to truncate
3361 if ( $length <= 0 ) {
3362 return $ellipsis; // no text shown, nothing to format (convention)
3363 } elseif ( strlen( $text ) <= $length ) {
3364 return $text; // string short enough even *with* HTML (short-circuit)
3367 $dispLen = 0; // innerHTML legth so far
3368 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3369 $tagType = 0; // 0-open, 1-close
3370 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3371 $entityState = 0; // 0-not entity, 1-entity
3372 $tag = $ret = ''; // accumulated tag name, accumulated result string
3373 $openTags = array(); // open tag stack
3374 $maybeState = null; // possible truncation state
3376 $textLen = strlen( $text );
3377 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3378 for ( $pos = 0; true; ++
$pos ) {
3379 # Consider truncation once the display length has reached the maximim.
3380 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3381 # Check that we're not in the middle of a bracket/entity...
3382 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3383 if ( !$testingEllipsis ) {
3384 $testingEllipsis = true;
3385 # Save where we are; we will truncate here unless there turn out to
3386 # be so few remaining characters that truncation is not necessary.
3387 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3388 $maybeState = array( $ret, $openTags ); // save state
3390 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3391 # String in fact does need truncation, the truncation point was OK.
3392 list( $ret, $openTags ) = $maybeState; // reload state
3393 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3394 $ret .= $ellipsis; // add ellipsis
3398 if ( $pos >= $textLen ) {
3399 break; // extra iteration just for above checks
3402 # Read the next char...
3404 $lastCh = $pos ?
$text[$pos - 1] : '';
3405 $ret .= $ch; // add to result string
3407 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3408 $entityState = 0; // for bad HTML
3409 $bracketState = 1; // tag started (checking for backslash)
3410 } elseif ( $ch == '>' ) {
3411 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3412 $entityState = 0; // for bad HTML
3413 $bracketState = 0; // out of brackets
3414 } elseif ( $bracketState == 1 ) {
3416 $tagType = 1; // close tag (e.g. "</span>")
3418 $tagType = 0; // open tag (e.g. "<span>")
3421 $bracketState = 2; // building tag name
3422 } elseif ( $bracketState == 2 ) {
3426 // Name found (e.g. "<a href=..."), add on tag attributes...
3427 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3429 } elseif ( $bracketState == 0 ) {
3430 if ( $entityState ) {
3433 $dispLen++
; // entity is one displayed char
3436 if ( $neLength == 0 && !$maybeState ) {
3437 // Save state without $ch. We want to *hit* the first
3438 // display char (to get tags) but not *use* it if truncating.
3439 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3442 $entityState = 1; // entity found, (e.g. " ")
3444 $dispLen++
; // this char is displayed
3445 // Add the next $max display text chars after this in one swoop...
3446 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3447 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3448 $dispLen +
= $skipped;
3454 // Close the last tag if left unclosed by bad HTML
3455 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3456 while ( count( $openTags ) > 0 ) {
3457 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3463 * truncateHtml() helper function
3464 * like strcspn() but adds the skipped chars to $ret
3473 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3474 if ( $len === null ) {
3475 $len = -1; // -1 means "no limit" for strcspn
3476 } elseif ( $len < 0 ) {
3480 if ( $start < strlen( $text ) ) {
3481 $skipCount = strcspn( $text, $search, $start, $len );
3482 $ret .= substr( $text, $start, $skipCount );
3488 * truncateHtml() helper function
3489 * (a) push or pop $tag from $openTags as needed
3490 * (b) clear $tag value
3491 * @param &$tag string Current HTML tag name we are looking at
3492 * @param $tagType int (0-open tag, 1-close tag)
3493 * @param $lastCh string Character before the '>' that ended this tag
3494 * @param &$openTags array Open tag stack (not accounting for $tag)
3496 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3497 $tag = ltrim( $tag );
3499 if ( $tagType == 0 && $lastCh != '/' ) {
3500 $openTags[] = $tag; // tag opened (didn't close itself)
3501 } elseif ( $tagType == 1 ) {
3502 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3503 array_pop( $openTags ); // tag closed
3511 * Grammatical transformations, needed for inflected languages
3512 * Invoked by putting {{grammar:case|word}} in a message
3514 * @param $word string
3515 * @param $case string
3518 function convertGrammar( $word, $case ) {
3519 global $wgGrammarForms;
3520 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3521 return $wgGrammarForms[$this->getCode()][$case][$word];
3526 * Get the grammar forms for the content language
3527 * @return array of grammar forms
3530 function getGrammarForms() {
3531 global $wgGrammarForms;
3532 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3533 return $wgGrammarForms[$this->getCode()];
3538 * Provides an alternative text depending on specified gender.
3539 * Usage {{gender:username|masculine|feminine|neutral}}.
3540 * username is optional, in which case the gender of current user is used,
3541 * but only in (some) interface messages; otherwise default gender is used.
3543 * If no forms are given, an empty string is returned. If only one form is
3544 * given, it will be returned unconditionally. These details are implied by
3545 * the caller and cannot be overridden in subclasses.
3547 * If more than one form is given, the default is to use the neutral one
3548 * if it is specified, and to use the masculine one otherwise. These
3549 * details can be overridden in subclasses.
3551 * @param $gender string
3552 * @param $forms array
3556 function gender( $gender, $forms ) {
3557 if ( !count( $forms ) ) {
3560 $forms = $this->preConvertPlural( $forms, 2 );
3561 if ( $gender === 'male' ) {
3564 if ( $gender === 'female' ) {
3567 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3571 * Plural form transformations, needed for some languages.
3572 * For example, there are 3 form of plural in Russian and Polish,
3573 * depending on "count mod 10". See [[w:Plural]]
3574 * For English it is pretty simple.
3576 * Invoked by putting {{plural:count|wordform1|wordform2}}
3577 * or {{plural:count|wordform1|wordform2|wordform3}}
3579 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3581 * @param $count Integer: non-localized number
3582 * @param $forms Array: different plural forms
3583 * @return string Correct form of plural for $count in this language
3585 function convertPlural( $count, $forms ) {
3586 if ( !count( $forms ) ) {
3590 // Handle explicit n=pluralform cases
3591 foreach ( $forms as $index => $form ) {
3592 if ( preg_match( '/\d+=/i', $form ) ) {
3593 $pos = strpos( $form, '=' );
3594 if ( substr( $form, 0, $pos ) === (string) $count ) {
3595 return substr( $form, $pos +
1 );
3597 unset( $forms[$index] );
3600 $forms = array_values( $forms );
3602 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3603 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3604 return $forms[$pluralForm];
3608 * Checks that convertPlural was given an array and pads it to requested
3609 * amount of forms by copying the last one.
3611 * @param $count Integer: How many forms should there be at least
3612 * @param $forms Array of forms given to convertPlural
3613 * @return array Padded array of forms or an exception if not an array
3615 protected function preConvertPlural( /* Array */ $forms, $count ) {
3616 while ( count( $forms ) < $count ) {
3617 $forms[] = $forms[count( $forms ) - 1];
3623 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3624 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3625 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3626 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3629 * @param $str String: the validated block duration in English
3630 * @return string Somehow translated block duration
3631 * @see LanguageFi.php for example implementation
3633 function translateBlockExpiry( $str ) {
3634 $duration = SpecialBlock
::getSuggestedDurations( $this );
3635 foreach ( $duration as $show => $value ) {
3636 if ( strcmp( $str, $value ) == 0 ) {
3637 return htmlspecialchars( trim( $show ) );
3641 // Since usually only infinite or indefinite is only on list, so try
3642 // equivalents if still here.
3643 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3644 if ( in_array( $str, $indefs ) ) {
3645 foreach ( $indefs as $val ) {
3646 $show = array_search( $val, $duration, true );
3647 if ( $show !== false ) {
3648 return htmlspecialchars( trim( $show ) );
3653 // If all else fails, return a standard duration or timestamp description.
3654 $time = strtotime( $str, 0 );
3655 if ( $time === false ) { // Unknown format. Return it as-is in case.
3657 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3658 // $time is relative to 0 so it's a duration length.
3659 return $this->formatDuration( $time );
3660 } else { // It's an absolute timestamp.
3661 if ( $time === 0 ) {
3662 // wfTimestamp() handles 0 as current time instead of epoch.
3663 return $this->timeanddate( '19700101000000' );
3665 return $this->timeanddate( $time );
3671 * languages like Chinese need to be segmented in order for the diff
3674 * @param $text String
3677 public function segmentForDiff( $text ) {
3682 * and unsegment to show the result
3684 * @param $text String
3687 public function unsegmentForDiff( $text ) {
3692 * Return the LanguageConverter used in the Language
3695 * @return LanguageConverter
3697 public function getConverter() {
3698 return $this->mConverter
;
3702 * convert text to all supported variants
3704 * @param $text string
3707 public function autoConvertToAllVariants( $text ) {
3708 return $this->mConverter
->autoConvertToAllVariants( $text );
3712 * convert text to different variants of a language.
3714 * @param $text string
3717 public function convert( $text ) {
3718 return $this->mConverter
->convert( $text );
3722 * Convert a Title object to a string in the preferred variant
3724 * @param $title Title
3727 public function convertTitle( $title ) {
3728 return $this->mConverter
->convertTitle( $title );
3732 * Convert a namespace index to a string in the preferred variant
3737 public function convertNamespace( $ns ) {
3738 return $this->mConverter
->convertNamespace( $ns );
3742 * Check if this is a language with variants
3746 public function hasVariants() {
3747 return count( $this->getVariants() ) > 1;
3751 * Check if the language has the specific variant
3754 * @param $variant string
3757 public function hasVariant( $variant ) {
3758 return (bool)$this->mConverter
->validateVariant( $variant );
3762 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3764 * @param $text string
3767 public function armourMath( $text ) {
3768 return $this->mConverter
->armourMath( $text );
3772 * Perform output conversion on a string, and encode for safe HTML output.
3773 * @param $text String text to be converted
3774 * @param $isTitle Bool whether this conversion is for the article title
3776 * @todo this should get integrated somewhere sane
3778 public function convertHtml( $text, $isTitle = false ) {
3779 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3783 * @param $key string
3786 public function convertCategoryKey( $key ) {
3787 return $this->mConverter
->convertCategoryKey( $key );
3791 * Get the list of variants supported by this language
3792 * see sample implementation in LanguageZh.php
3794 * @return array an array of language codes
3796 public function getVariants() {
3797 return $this->mConverter
->getVariants();
3803 public function getPreferredVariant() {
3804 return $this->mConverter
->getPreferredVariant();
3810 public function getDefaultVariant() {
3811 return $this->mConverter
->getDefaultVariant();
3817 public function getURLVariant() {
3818 return $this->mConverter
->getURLVariant();
3822 * If a language supports multiple variants, it is
3823 * possible that non-existing link in one variant
3824 * actually exists in another variant. this function
3825 * tries to find it. See e.g. LanguageZh.php
3827 * @param $link String: the name of the link
3828 * @param $nt Mixed: the title object of the link
3829 * @param $ignoreOtherCond Boolean: to disable other conditions when
3830 * we need to transclude a template or update a category's link
3831 * @return null the input parameters may be modified upon return
3833 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3834 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3838 * If a language supports multiple variants, converts text
3839 * into an array of all possible variants of the text:
3840 * 'variant' => text in that variant
3842 * @deprecated since 1.17 Use autoConvertToAllVariants()
3844 * @param $text string
3848 public function convertLinkToAllVariants( $text ) {
3849 return $this->mConverter
->convertLinkToAllVariants( $text );
3853 * returns language specific options used by User::getPageRenderHash()
3854 * for example, the preferred language variant
3858 function getExtraHashOptions() {
3859 return $this->mConverter
->getExtraHashOptions();
3863 * For languages that support multiple variants, the title of an
3864 * article may be displayed differently in different variants. this
3865 * function returns the apporiate title defined in the body of the article.
3869 public function getParsedTitle() {
3870 return $this->mConverter
->getParsedTitle();
3874 * Prepare external link text for conversion. When the text is
3875 * a URL, it shouldn't be converted, and it'll be wrapped in
3876 * the "raw" tag (-{R| }-) to prevent conversion.
3878 * This function is called "markNoConversion" for historical
3881 * @param $text String: text to be used for external link
3882 * @param $noParse bool: wrap it without confirming it's a real URL first
3883 * @return string the tagged text
3885 public function markNoConversion( $text, $noParse = false ) {
3886 // Excluding protocal-relative URLs may avoid many false positives.
3887 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3888 return $this->mConverter
->markNoConversion( $text );
3895 * A regular expression to match legal word-trailing characters
3896 * which should be merged onto a link of the form [[foo]]bar.
3900 public function linkTrail() {
3901 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3907 function getLangObj() {
3912 * Get the RFC 3066 code for this language object
3914 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3915 * htmlspecialchars() or similar
3919 public function getCode() {
3920 return $this->mCode
;
3924 * Get the code in Bcp47 format which we can use
3925 * inside of html lang="" tags.
3927 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3928 * htmlspecialchars() or similar.
3933 public function getHtmlCode() {
3934 if ( is_null( $this->mHtmlCode
) ) {
3935 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3937 return $this->mHtmlCode
;
3941 * @param $code string
3943 public function setCode( $code ) {
3944 $this->mCode
= $code;
3945 // Ensure we don't leave an incorrect html code lying around
3946 $this->mHtmlCode
= null;
3950 * Get the name of a file for a certain language code
3951 * @param $prefix string Prepend this to the filename
3952 * @param $code string Language code
3953 * @param $suffix string Append this to the filename
3954 * @throws MWException
3955 * @return string $prefix . $mangledCode . $suffix
3957 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3958 // Protect against path traversal
3959 if ( !Language
::isValidCode( $code )
3960 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3962 throw new MWException( "Invalid language code \"$code\"" );
3965 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3969 * Get the language code from a file name. Inverse of getFileName()
3970 * @param $filename string $prefix . $languageCode . $suffix
3971 * @param $prefix string Prefix before the language code
3972 * @param $suffix string Suffix after the language code
3973 * @return string Language code, or false if $prefix or $suffix isn't found
3975 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3977 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3978 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3979 if ( !count( $m ) ) {
3982 return str_replace( '_', '-', strtolower( $m[1] ) );
3986 * @param $code string
3989 public static function getMessagesFileName( $code ) {
3991 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3992 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3997 * @param $code string
4000 public static function getClassFileName( $code ) {
4002 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4006 * Get the first fallback for a given language.
4008 * @param $code string
4010 * @return bool|string
4012 public static function getFallbackFor( $code ) {
4013 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4016 $fallbacks = self
::getFallbacksFor( $code );
4017 $first = array_shift( $fallbacks );
4023 * Get the ordered list of fallback languages.
4026 * @param $code string Language code
4029 public static function getFallbacksFor( $code ) {
4030 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4033 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4034 $v = array_map( 'trim', explode( ',', $v ) );
4035 if ( $v[count( $v ) - 1] !== 'en' ) {
4043 * Get all messages for a given language
4044 * WARNING: this may take a long time. If you just need all message *keys*
4045 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4047 * @param $code string
4051 public static function getMessagesFor( $code ) {
4052 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4056 * Get a message for a given language
4058 * @param $key string
4059 * @param $code string
4063 public static function getMessageFor( $key, $code ) {
4064 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4068 * Get all message keys for a given language. This is a faster alternative to
4069 * array_keys( Language::getMessagesFor( $code ) )
4072 * @param $code string Language code
4073 * @return array of message keys (strings)
4075 public static function getMessageKeysFor( $code ) {
4076 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4083 function fixVariableInNamespace( $talk ) {
4084 if ( strpos( $talk, '$1' ) === false ) {
4088 global $wgMetaNamespace;
4089 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4091 # Allow grammar transformations
4092 # Allowing full message-style parsing would make simple requests
4093 # such as action=raw much more expensive than they need to be.
4094 # This will hopefully cover most cases.
4095 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4096 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4097 return str_replace( ' ', '_', $talk );
4104 function replaceGrammarInNamespace( $m ) {
4105 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4109 * @throws MWException
4112 static function getCaseMaps() {
4113 static $wikiUpperChars, $wikiLowerChars;
4114 if ( isset( $wikiUpperChars ) ) {
4115 return array( $wikiUpperChars, $wikiLowerChars );
4118 wfProfileIn( __METHOD__
);
4119 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4120 if ( $arr === false ) {
4121 throw new MWException(
4122 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4124 $wikiUpperChars = $arr['wikiUpperChars'];
4125 $wikiLowerChars = $arr['wikiLowerChars'];
4126 wfProfileOut( __METHOD__
);
4127 return array( $wikiUpperChars, $wikiLowerChars );
4131 * Decode an expiry (block, protection, etc) which has come from the DB
4133 * @todo FIXME: why are we returnings DBMS-dependent strings???
4135 * @param $expiry String: Database expiry String
4136 * @param $format Bool|Int true to process using language functions, or TS_ constant
4137 * to return the expiry in a given timestamp
4141 public function formatExpiry( $expiry, $format = true ) {
4142 static $infinity, $infinityMsg;
4143 if ( $infinity === null ) {
4144 $infinityMsg = wfMessage( 'infiniteblock' );
4145 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4148 if ( $expiry == '' ||
$expiry == $infinity ) {
4149 return $format === true
4153 return $format === true
4154 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4155 : wfTimestamp( $format, $expiry );
4161 * @param $seconds int|float
4162 * @param $format Array Optional
4163 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4164 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4165 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4166 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4169 function formatTimePeriod( $seconds, $format = array() ) {
4170 if ( !is_array( $format ) ) {
4171 $format = array( 'avoid' => $format ); // For backwards compatibility
4173 if ( !isset( $format['avoid'] ) ) {
4174 $format['avoid'] = false;
4176 if ( !isset( $format['noabbrevs' ] ) ) {
4177 $format['noabbrevs'] = false;
4179 $secondsMsg = wfMessage(
4180 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4181 $minutesMsg = wfMessage(
4182 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4183 $hoursMsg = wfMessage(
4184 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4185 $daysMsg = wfMessage(
4186 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4188 if ( round( $seconds * 10 ) < 100 ) {
4189 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4190 $s = $secondsMsg->params( $s )->text();
4191 } elseif ( round( $seconds ) < 60 ) {
4192 $s = $this->formatNum( round( $seconds ) );
4193 $s = $secondsMsg->params( $s )->text();
4194 } elseif ( round( $seconds ) < 3600 ) {
4195 $minutes = floor( $seconds / 60 );
4196 $secondsPart = round( fmod( $seconds, 60 ) );
4197 if ( $secondsPart == 60 ) {
4201 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4203 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4204 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4205 $hours = floor( $seconds / 3600 );
4206 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4207 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4208 if ( $secondsPart == 60 ) {
4212 if ( $minutes == 60 ) {
4216 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4218 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4219 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4220 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4223 $days = floor( $seconds / 86400 );
4224 if ( $format['avoid'] === 'avoidminutes' ) {
4225 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4226 if ( $hours == 24 ) {
4230 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4232 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4233 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4234 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4235 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4236 if ( $minutes == 60 ) {
4240 if ( $hours == 24 ) {
4244 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4246 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4248 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4250 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4252 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4259 * Format a bitrate for output, using an appropriate
4260 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4262 * This use base 1000. For base 1024 use formatSize(), for another base
4263 * see formatComputingNumbers()
4268 function formatBitrate( $bps ) {
4269 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4273 * @param $size int Size of the unit
4274 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4275 * @param $messageKey string Message key to be uesd
4278 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4280 return str_replace( '$1', $this->formatNum( $size ),
4281 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4284 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4287 $maxIndex = count( $sizes ) - 1;
4288 while ( $size >= $boundary && $index < $maxIndex ) {
4293 // For small sizes no decimal places necessary
4296 // For MB and bigger two decimal places are smarter
4299 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4301 $size = round( $size, $round );
4302 $text = $this->getMessageFromDB( $msg );
4303 return str_replace( '$1', $this->formatNum( $size ), $text );
4307 * Format a size in bytes for output, using an appropriate
4308 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4310 * This method use base 1024. For base 1000 use formatBitrate(), for
4311 * another base see formatComputingNumbers()
4313 * @param $size int Size to format
4314 * @return string Plain text (not HTML)
4316 function formatSize( $size ) {
4317 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4321 * Make a list item, used by various special pages
4323 * @param $page String Page link
4324 * @param $details String Text between brackets
4325 * @param $oppositedm Boolean Add the direction mark opposite to your
4326 * language, to display text properly
4329 function specialList( $page, $details, $oppositedm = true ) {
4330 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4331 $this->getDirMark();
4332 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4333 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4334 return $page . $details;
4338 * Generate (prev x| next x) (20|50|100...) type links for paging
4340 * @param $title Title object to link
4341 * @param $offset Integer offset parameter
4342 * @param $limit Integer limit parameter
4343 * @param $query array|String optional URL query parameter string
4344 * @param $atend Bool optional param for specified if this is the last page
4347 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4348 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4350 # Make 'previous' link
4351 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4352 if ( $offset > 0 ) {
4353 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4354 $query, $prev, 'prevn-title', 'mw-prevlink' );
4356 $plink = htmlspecialchars( $prev );
4360 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4362 $nlink = htmlspecialchars( $next );
4364 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4365 $query, $next, 'prevn-title', 'mw-nextlink' );
4368 # Make links to set number of items per page
4369 $numLinks = array();
4370 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4371 $numLinks[] = $this->numLink( $title, $offset, $num,
4372 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4375 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4376 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4380 * Helper function for viewPrevNext() that generates links
4382 * @param $title Title object to link
4383 * @param $offset Integer offset parameter
4384 * @param $limit Integer limit parameter
4385 * @param $query Array extra query parameters
4386 * @param $link String text to use for the link; will be escaped
4387 * @param $tooltipMsg String name of the message to use as tooltip
4388 * @param $class String value of the "class" attribute of the link
4389 * @return String HTML fragment
4391 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4392 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4393 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4394 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4395 'title' => $tooltip, 'class' => $class ), $link );
4399 * Get the conversion rule title, if any.
4403 public function getConvRuleTitle() {
4404 return $this->mConverter
->getConvRuleTitle();
4408 * Get the compiled plural rules for the language
4410 * @return array Associative array with plural form, and plural rule as key-value pairs
4412 public function getCompiledPluralRules() {
4413 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4414 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4415 if ( !$pluralRules ) {
4416 foreach ( $fallbacks as $fallbackCode ) {
4417 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4418 if ( $pluralRules ) {
4423 return $pluralRules;
4427 * Get the plural rules for the language
4429 * @return array Associative array with plural form number and plural rule as key-value pairs
4431 public function getPluralRules() {
4432 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4433 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4434 if ( !$pluralRules ) {
4435 foreach ( $fallbacks as $fallbackCode ) {
4436 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4437 if ( $pluralRules ) {
4442 return $pluralRules;
4446 * Get the plural rule types for the language
4448 * @return array Associative array with plural form number and plural rule type as key-value pairs
4450 public function getPluralRuleTypes() {
4451 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4452 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4453 if ( !$pluralRuleTypes ) {
4454 foreach ( $fallbacks as $fallbackCode ) {
4455 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4456 if ( $pluralRuleTypes ) {
4461 return $pluralRuleTypes;
4465 * Find the index number of the plural rule appropriate for the given number
4466 * @return int The index number of the plural rule
4468 public function getPluralRuleIndexNumber( $number ) {
4469 $pluralRules = $this->getCompiledPluralRules();
4470 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4475 * Find the plural rule type appropriate for the given number
4476 * For example, if the language is set to Arabic, getPluralType(5) should
4479 * @return string The name of the plural rule type, e.g. one, two, few, many
4481 public function getPluralRuleType( $number ) {
4482 $index = $this->getPluralRuleIndexNumber( $number );
4483 $pluralRuleTypes = $this->getPluralRuleTypes();
4484 if ( isset( $pluralRuleTypes[$index] ) ) {
4485 return $pluralRuleTypes[$index];