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";
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
38 * a fake language converter
47 function __construct( $langobj ) { $this->mLang
= $langobj; }
48 function autoConvert( $text, $variant = false ) { return $text; }
49 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
50 function convert( $t ) { return $t; }
51 function convertTo( $text, $variant ) { return $text; }
52 function convertTitle( $t ) { return $t->getPrefixedText(); }
53 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
54 function getVariants() { return array( $this->mLang
->getCode() ); }
55 function getVariantFallbacks( $variant ) { return $this->mLang
->getCode(); }
56 function getPreferredVariant() { return $this->mLang
->getCode(); }
57 function getDefaultVariant() { return $this->mLang
->getCode(); }
58 function getURLVariant() { return ''; }
59 function getConvRuleTitle() { return false; }
60 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
61 function getExtraHashOptions() { return ''; }
62 function getParsedTitle() { return ''; }
63 function markNoConversion( $text, $noParse = false ) { return $text; }
64 function convertCategoryKey( $key ) { return $key; }
65 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
66 function armourMath( $text ) { return $text; }
67 function validateVariant( $variant = null ) { return $variant === $this->mLang
->getCode() ?
$variant : null; }
68 function translate( $text, $variant ) { return $text; }
72 * Internationalisation code
78 * @var LanguageConverter
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null, $mParentLanguage = false;
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 * Cache for language fallbacks.
175 * @see Language::getFallbacksIncludingSiteLanguage
179 static private $fallbackLanguageCache = array();
182 * Get a cached or new language object for a given language code
183 * @param $code String
186 static function factory( $code ) {
187 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
189 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
190 $code = $wgDummyLanguageCodes[$code];
193 // get the language object to process
194 $langObj = isset( self
::$mLangObjCache[$code] )
195 ? self
::$mLangObjCache[$code]
196 : self
::newFromCode( $code );
198 // merge the language object in to get it up front in the cache
199 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
200 // get rid of the oldest ones in case we have an overflow
201 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
207 * Create a language object for a given language code
208 * @param $code String
209 * @throws MWException
212 protected static function newFromCode( $code ) {
213 // Protect against path traversal below
214 if ( !Language
::isValidCode( $code )
215 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
217 throw new MWException( "Invalid language code \"$code\"" );
220 if ( !Language
::isValidBuiltInCode( $code ) ) {
221 // It's not possible to customise this code with class files, so
222 // just return a Language object. This is to support uselang= hacks.
223 $lang = new Language
;
224 $lang->setCode( $code );
228 // Check if there is a language class for the code
229 $class = self
::classFromCode( $code );
230 self
::preloadLanguageClass( $class );
231 if ( class_exists( $class ) ) {
236 // Keep trying the fallback list until we find an existing class
237 $fallbacks = Language
::getFallbacksFor( $code );
238 foreach ( $fallbacks as $fallbackCode ) {
239 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
240 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
243 $class = self
::classFromCode( $fallbackCode );
244 self
::preloadLanguageClass( $class );
245 if ( class_exists( $class ) ) {
246 $lang = Language
::newFromCode( $fallbackCode );
247 $lang->setCode( $code );
252 throw new MWException( "Invalid fallback sequence for language '$code'" );
256 * Checks whether any localisation is available for that language tag
257 * in MediaWiki (MessagesXx.php exists).
259 * @param string $code Language tag (in lower case)
260 * @return bool Whether language is supported
263 public static function isSupportedLanguage( $code ) {
264 return $code === strtolower( $code ) && is_readable( self
::getMessagesFileName( $code ) );
268 * Returns true if a language code string is a well-formed language tag
269 * according to RFC 5646.
270 * This function only checks well-formedness; it doesn't check that
271 * language, script or variant codes actually exist in the repositories.
273 * Based on regexes by Mark Davis of the Unicode Consortium:
274 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
276 * @param $code string
277 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
282 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
285 $alphanum = '[a-z0-9]';
286 $x = 'x'; # private use singleton
287 $singleton = '[a-wy-z]'; # other singleton
288 $s = $lenient ?
'[-_]' : '-';
290 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
291 $script = "$alpha{4}"; # ISO 15924
292 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
293 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
294 $extension = "$singleton(?:$s$alphanum{2,8})+";
295 $privateUse = "$x(?:$s$alphanum{1,8})+";
297 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
298 # Since these are limited, this is safe even later changes to the registry --
299 # the only oddity is that it might change the type of the tag, and thus
300 # the results from the capturing groups.
301 # http://www.iana.org/assignments/language-subtag-registry
303 $grandfathered = "en{$s}GB{$s}oed"
304 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
305 . "|no{$s}(?:bok|nyn)"
306 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
307 . "|zh{$s}min{$s}nan";
309 $variantList = "$variant(?:$s$variant)*";
310 $extensionList = "$extension(?:$s$extension)*";
312 $langtag = "(?:($language)"
315 . "(?:$s$variantList)?"
316 . "(?:$s$extensionList)?"
317 . "(?:$s$privateUse)?)";
319 # The final breakdown, with capturing groups for each of these components
320 # The variants, extensions, grandfathered, and private-use may have interior '-'
322 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
324 return (bool)preg_match( "/$root/", strtolower( $code ) );
328 * Returns true if a language code string is of a valid form, whether or
329 * not it exists. This includes codes which are used solely for
330 * customisation via the MediaWiki namespace.
332 * @param $code string
336 public static function isValidCode( $code ) {
337 static $cache = array();
338 if ( isset( $cache[$code] ) ) {
339 return $cache[$code];
341 // People think language codes are html safe, so enforce it.
342 // Ideally we should only allow a-zA-Z0-9-
343 // but, .+ and other chars are often used for {{int:}} hacks
344 // see bugs 37564, 37587, 36938
346 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
347 && !preg_match( Title
::getTitleInvalidRegex(), $code );
349 return $cache[$code];
353 * Returns true if a language code is of a valid form for the purposes of
354 * internal customisation of MediaWiki, via Messages*.php.
356 * @param $code string
358 * @throws MWException
362 public static function isValidBuiltInCode( $code ) {
364 if ( !is_string( $code ) ) {
365 if ( is_object( $code ) ) {
366 $addmsg = " of class " . get_class( $code );
370 $type = gettype( $code );
371 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
374 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
378 * Returns true if a language code is an IETF tag known to MediaWiki.
380 * @param $code string
385 public static function isKnownLanguageTag( $tag ) {
386 static $coreLanguageNames;
388 // Quick escape for invalid input to avoid exceptions down the line
389 // when code tries to process tags which are not valid at all.
390 if ( !self
::isValidBuiltInCode( $tag ) ) {
394 if ( $coreLanguageNames === null ) {
396 include "$IP/languages/Names.php";
399 if ( isset( $coreLanguageNames[$tag] )
400 || self
::fetchLanguageName( $tag, $tag ) !== ''
410 * @return String Name of the language class
412 public static function classFromCode( $code ) {
413 if ( $code == 'en' ) {
416 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
421 * Includes language class files
423 * @param $class string Name of the language class
425 public static function preloadLanguageClass( $class ) {
428 if ( $class === 'Language' ) {
432 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
433 include_once "$IP/languages/classes/$class.php";
438 * Get the LocalisationCache instance
440 * @return LocalisationCache
442 public static function getLocalisationCache() {
443 if ( is_null( self
::$dataCache ) ) {
444 global $wgLocalisationCacheConf;
445 $class = $wgLocalisationCacheConf['class'];
446 self
::$dataCache = new $class( $wgLocalisationCacheConf );
448 return self
::$dataCache;
451 function __construct() {
452 $this->mConverter
= new FakeConverter( $this );
453 // Set the code to the name of the descendant
454 if ( get_class( $this ) == 'Language' ) {
457 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
459 self
::getLocalisationCache();
463 * Reduce memory usage
465 function __destruct() {
466 foreach ( $this as $name => $value ) {
467 unset( $this->$name );
472 * Hook which will be called if this is the content language.
473 * Descendants can use this to register hook functions or modify globals
475 function initContLang() { }
478 * Same as getFallbacksFor for current language.
480 * @deprecated in 1.19
482 function getFallbackLanguageCode() {
483 wfDeprecated( __METHOD__
, '1.19' );
484 return self
::getFallbackFor( $this->mCode
);
491 function getFallbackLanguages() {
492 return self
::getFallbacksFor( $this->mCode
);
496 * Exports $wgBookstoreListEn
499 function getBookstoreList() {
500 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
504 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
505 * available in localised form, it will be included in English.
509 public function getNamespaces() {
510 if ( is_null( $this->namespaceNames
) ) {
511 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
513 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
514 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
516 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
518 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
519 if ( $wgMetaNamespaceTalk ) {
520 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
522 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
523 $this->namespaceNames
[NS_PROJECT_TALK
] =
524 $this->fixVariableInNamespace( $talk );
527 # Sometimes a language will be localised but not actually exist on this wiki.
528 foreach ( $this->namespaceNames
as $key => $text ) {
529 if ( !isset( $validNamespaces[$key] ) ) {
530 unset( $this->namespaceNames
[$key] );
534 # The above mixing may leave namespaces out of canonical order.
535 # Re-order by namespace ID number...
536 ksort( $this->namespaceNames
);
538 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
540 return $this->namespaceNames
;
544 * Arbitrarily set all of the namespace names at once. Mainly used for testing
545 * @param $namespaces Array of namespaces (id => name)
547 public function setNamespaces( array $namespaces ) {
548 $this->namespaceNames
= $namespaces;
549 $this->mNamespaceIds
= null;
553 * Resets all of the namespace caches. Mainly used for testing
555 public function resetNamespaces() {
556 $this->namespaceNames
= null;
557 $this->mNamespaceIds
= null;
558 $this->namespaceAliases
= null;
562 * A convenience function that returns the same thing as
563 * getNamespaces() except with the array values changed to ' '
564 * where it found '_', useful for producing output to be displayed
565 * e.g. in <select> forms.
569 function getFormattedNamespaces() {
570 $ns = $this->getNamespaces();
571 foreach ( $ns as $k => $v ) {
572 $ns[$k] = strtr( $v, '_', ' ' );
578 * Get a namespace value by key
580 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
581 * echo $mw_ns; // prints 'MediaWiki'
584 * @param $index Int: the array key of the namespace to return
585 * @return mixed, string if the namespace value exists, otherwise false
587 function getNsText( $index ) {
588 $ns = $this->getNamespaces();
589 return isset( $ns[$index] ) ?
$ns[$index] : false;
593 * A convenience function that returns the same thing as
594 * getNsText() except with '_' changed to ' ', useful for
598 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
599 * echo $mw_ns; // prints 'MediaWiki talk'
602 * @param int $index The array key of the namespace to return
603 * @return string Namespace name without underscores (empty string if namespace does not exist)
605 function getFormattedNsText( $index ) {
606 $ns = $this->getNsText( $index );
607 return strtr( $ns, '_', ' ' );
611 * Returns gender-dependent namespace alias if available.
612 * @param $index Int: namespace index
613 * @param $gender String: gender key (male, female... )
617 function getGenderNsText( $index, $gender ) {
618 global $wgExtraGenderNamespaces;
620 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
621 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
625 * Whether this language makes distinguishes genders for example in
630 function needsGenderDistinction() {
631 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
632 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
633 // $wgExtraGenderNamespaces overrides everything
635 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
636 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
637 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
640 // Check what is in i18n files
641 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
642 return count( $aliases ) > 0;
647 * Get a namespace key by value, case insensitive.
648 * Only matches namespace names for the current language, not the
649 * canonical ones defined in Namespace.php.
651 * @param $text String
652 * @return mixed An integer if $text is a valid value otherwise false
654 function getLocalNsIndex( $text ) {
655 $lctext = $this->lc( $text );
656 $ids = $this->getNamespaceIds();
657 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
663 function getNamespaceAliases() {
664 if ( is_null( $this->namespaceAliases
) ) {
665 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
669 foreach ( $aliases as $name => $index ) {
670 if ( $index === NS_PROJECT_TALK
) {
671 unset( $aliases[$name] );
672 $name = $this->fixVariableInNamespace( $name );
673 $aliases[$name] = $index;
678 global $wgExtraGenderNamespaces;
679 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
680 foreach ( $genders as $index => $forms ) {
681 foreach ( $forms as $alias ) {
682 $aliases[$alias] = $index;
686 # Also add converted namespace names as aliases, to avoid confusion.
687 $convertedNames = array();
688 foreach ( $this->getVariants() as $variant ) {
689 if ( $variant === $this->mCode
) {
692 foreach ( $this->getNamespaces() as $ns => $_ ) {
693 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
697 $this->namespaceAliases
= $aliases +
$convertedNames;
699 return $this->namespaceAliases
;
705 function getNamespaceIds() {
706 if ( is_null( $this->mNamespaceIds
) ) {
707 global $wgNamespaceAliases;
708 # Put namespace names and aliases into a hashtable.
709 # If this is too slow, then we should arrange it so that it is done
710 # before caching. The catch is that at pre-cache time, the above
711 # class-specific fixup hasn't been done.
712 $this->mNamespaceIds
= array();
713 foreach ( $this->getNamespaces() as $index => $name ) {
714 $this->mNamespaceIds
[$this->lc( $name )] = $index;
716 foreach ( $this->getNamespaceAliases() as $name => $index ) {
717 $this->mNamespaceIds
[$this->lc( $name )] = $index;
719 if ( $wgNamespaceAliases ) {
720 foreach ( $wgNamespaceAliases as $name => $index ) {
721 $this->mNamespaceIds
[$this->lc( $name )] = $index;
725 return $this->mNamespaceIds
;
729 * Get a namespace key by value, case insensitive. Canonical namespace
730 * names override custom ones defined for the current language.
732 * @param $text String
733 * @return mixed An integer if $text is a valid value otherwise false
735 function getNsIndex( $text ) {
736 $lctext = $this->lc( $text );
737 $ns = MWNamespace
::getCanonicalIndex( $lctext );
738 if ( $ns !== null ) {
741 $ids = $this->getNamespaceIds();
742 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
746 * short names for language variants used for language conversion links.
748 * @param $code String
749 * @param $usemsg bool Use the "variantname-xyz" message if it exists
752 function getVariantname( $code, $usemsg = true ) {
753 $msg = "variantname-$code";
754 if ( $usemsg && wfMessage( $msg )->exists() ) {
755 return $this->getMessageFromDB( $msg );
757 $name = self
::fetchLanguageName( $code );
759 return $name; # if it's defined as a language name, show that
761 # otherwise, output the language code
767 * @param $name string
770 function specialPage( $name ) {
771 $aliases = $this->getSpecialPageAliases();
772 if ( isset( $aliases[$name][0] ) ) {
773 $name = $aliases[$name][0];
775 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
781 function getDatePreferences() {
782 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
788 function getDateFormats() {
789 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
793 * @return array|string
795 function getDefaultDateFormat() {
796 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
797 if ( $df === 'dmy or mdy' ) {
798 global $wgAmericanDates;
799 return $wgAmericanDates ?
'mdy' : 'dmy';
808 function getDatePreferenceMigrationMap() {
809 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
816 function getImageFile( $image ) {
817 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
823 function getExtraUserToggles() {
824 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
831 function getUserToggle( $tog ) {
832 return $this->getMessageFromDB( "tog-$tog" );
836 * Get native language names, indexed by code.
837 * Only those defined in MediaWiki, no other data like CLDR.
838 * If $customisedOnly is true, only returns codes with a messages file
840 * @param $customisedOnly bool
843 * @deprecated in 1.20, use fetchLanguageNames()
845 public static function getLanguageNames( $customisedOnly = false ) {
846 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
850 * Get translated language names. This is done on best effort and
851 * by default this is exactly the same as Language::getLanguageNames.
852 * The CLDR extension provides translated names.
853 * @param $code String Language code.
854 * @return Array language code => language name
856 * @deprecated in 1.20, use fetchLanguageNames()
858 public static function getTranslatedLanguageNames( $code ) {
859 return self
::fetchLanguageNames( $code, 'all' );
863 * Get an array of language names, indexed by code.
864 * @param $inLanguage null|string: Code of language in which to return the names
865 * Use null for autonyms (native names)
866 * @param $include string:
867 * 'all' all available languages
868 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
869 * 'mwfile' only if the language is in 'mw' *and* has a message file
870 * @return array: language code => language name
873 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
874 global $wgExtraLanguageNames;
875 static $coreLanguageNames;
877 if ( $coreLanguageNames === null ) {
879 include "$IP/languages/Names.php";
885 # TODO: also include when $inLanguage is null, when this code is more efficient
886 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
889 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
890 foreach ( $mwNames as $mwCode => $mwName ) {
891 # - Prefer own MediaWiki native name when not using the hook
892 # - For other names just add if not added through the hook
893 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
894 $names[$mwCode] = $mwName;
898 if ( $include === 'all' ) {
903 $coreCodes = array_keys( $mwNames );
904 foreach ( $coreCodes as $coreCode ) {
905 $returnMw[$coreCode] = $names[$coreCode];
908 if ( $include === 'mwfile' ) {
909 $namesMwFile = array();
910 # We do this using a foreach over the codes instead of a directory
911 # loop so that messages files in extensions will work correctly.
912 foreach ( $returnMw as $code => $value ) {
913 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
914 $namesMwFile[$code] = $names[$code];
919 # 'mw' option; default if it's not one of the other two options (all/mwfile)
924 * @param $code string: The code of the language for which to get the name
925 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
926 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
927 * @return string: Language name or empty
930 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
931 $array = self
::fetchLanguageNames( $inLanguage, $include );
932 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
936 * Get a message from the MediaWiki namespace.
938 * @param $msg String: message name
941 function getMessageFromDB( $msg ) {
942 return wfMessage( $msg )->inLanguage( $this )->text();
946 * Get the native language name of $code.
947 * Only if defined in MediaWiki, no other data like CLDR.
948 * @param $code string
950 * @deprecated in 1.20, use fetchLanguageName()
952 function getLanguageName( $code ) {
953 return self
::fetchLanguageName( $code );
960 function getMonthName( $key ) {
961 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
967 function getMonthNamesArray() {
968 $monthNames = array( '' );
969 for ( $i = 1; $i < 13; $i++
) {
970 $monthNames[] = $this->getMonthName( $i );
979 function getMonthNameGen( $key ) {
980 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
987 function getMonthAbbreviation( $key ) {
988 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
994 function getMonthAbbreviationsArray() {
995 $monthNames = array( '' );
996 for ( $i = 1; $i < 13; $i++
) {
997 $monthNames[] = $this->getMonthAbbreviation( $i );
1003 * @param $key string
1006 function getWeekdayName( $key ) {
1007 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1011 * @param $key string
1014 function getWeekdayAbbreviation( $key ) {
1015 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1019 * @param $key string
1022 function getIranianCalendarMonthName( $key ) {
1023 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1027 * @param $key string
1030 function getHebrewCalendarMonthName( $key ) {
1031 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1035 * @param $key string
1038 function getHebrewCalendarMonthNameGen( $key ) {
1039 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1043 * @param $key string
1046 function getHijriCalendarMonthName( $key ) {
1047 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1051 * This is a workalike of PHP's date() function, but with better
1052 * internationalisation, a reduced set of format characters, and a better
1055 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1056 * the PHP manual for definitions. There are a number of extensions, which
1059 * xn Do not translate digits of the next numeric format character
1060 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1061 * xr Use roman numerals for the next numeric format character
1062 * xh Use hebrew numerals for the next numeric format character
1064 * xg Genitive month name
1066 * xij j (day number) in Iranian calendar
1067 * xiF F (month name) in Iranian calendar
1068 * xin n (month number) in Iranian calendar
1069 * xiy y (two digit year) in Iranian calendar
1070 * xiY Y (full year) in Iranian calendar
1072 * xjj j (day number) in Hebrew calendar
1073 * xjF F (month name) in Hebrew calendar
1074 * xjt t (days in month) in Hebrew calendar
1075 * xjx xg (genitive month name) in Hebrew calendar
1076 * xjn n (month number) in Hebrew calendar
1077 * xjY Y (full year) in Hebrew calendar
1079 * xmj j (day number) in Hijri calendar
1080 * xmF F (month name) in Hijri calendar
1081 * xmn n (month number) in Hijri calendar
1082 * xmY Y (full year) in Hijri calendar
1084 * xkY Y (full year) in Thai solar calendar. Months and days are
1085 * identical to the Gregorian calendar
1086 * xoY Y (full year) in Minguo calendar or Juche year.
1087 * Months and days are identical to the
1088 * Gregorian calendar
1089 * xtY Y (full year) in Japanese nengo. Months and days are
1090 * identical to the Gregorian calendar
1092 * Characters enclosed in double quotes will be considered literal (with
1093 * the quotes themselves removed). Unmatched quotes will be considered
1094 * literal quotes. Example:
1096 * "The month is" F => The month is January
1099 * Backslash escaping is also supported.
1101 * Input timestamp is assumed to be pre-normalized to the desired local
1102 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1103 * $ts is UTC if $zone is not given.
1105 * @param $format String
1106 * @param $ts String: 14-character timestamp
1109 * @param $zone DateTimeZone: Timezone of $ts
1110 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1112 * @throws MWException
1115 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1120 $dateTimeObj = false;
1129 if ( strlen( $ts ) !== 14 ) {
1130 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1133 if ( !ctype_digit( $ts ) ) {
1134 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1137 for ( $p = 0; $p < strlen( $format ); $p++
) {
1139 $code = $format[$p];
1140 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1141 $code .= $format[++
$p];
1144 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1145 $code .= $format[++
$p];
1156 $rawToggle = !$rawToggle;
1165 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1169 $hebrew = self
::tsToHebrew( $ts );
1171 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1174 $num = substr( $ts, 6, 2 );
1177 if ( !$dateTimeObj ) {
1178 $dateTimeObj = DateTime
::createFromFormat(
1179 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1182 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1185 $num = intval( substr( $ts, 6, 2 ) );
1189 $iranian = self
::tsToIranian( $ts );
1195 $hijri = self
::tsToHijri( $ts );
1201 $hebrew = self
::tsToHebrew( $ts );
1206 if ( !$dateTimeObj ) {
1207 $dateTimeObj = DateTime
::createFromFormat(
1208 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1211 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1214 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1218 $iranian = self
::tsToIranian( $ts );
1220 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1224 $hijri = self
::tsToHijri( $ts );
1226 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1230 $hebrew = self
::tsToHebrew( $ts );
1232 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1235 $num = substr( $ts, 4, 2 );
1238 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1241 $num = intval( substr( $ts, 4, 2 ) );
1245 $iranian = self
::tsToIranian( $ts );
1251 $hijri = self
::tsToHijri ( $ts );
1257 $hebrew = self
::tsToHebrew( $ts );
1263 $hebrew = self
::tsToHebrew( $ts );
1268 $num = substr( $ts, 0, 4 );
1272 $iranian = self
::tsToIranian( $ts );
1278 $hijri = self
::tsToHijri( $ts );
1284 $hebrew = self
::tsToHebrew( $ts );
1290 $thai = self
::tsToYear( $ts, 'thai' );
1296 $minguo = self
::tsToYear( $ts, 'minguo' );
1302 $tenno = self
::tsToYear( $ts, 'tenno' );
1307 $num = substr( $ts, 2, 2 );
1311 $iranian = self
::tsToIranian( $ts );
1313 $num = substr( $iranian[0], -2 );
1316 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1319 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1322 $h = substr( $ts, 8, 2 );
1323 $num = $h %
12 ?
$h %
12 : 12;
1326 $num = intval( substr( $ts, 8, 2 ) );
1329 $h = substr( $ts, 8, 2 );
1330 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1333 $num = substr( $ts, 8, 2 );
1336 $num = substr( $ts, 10, 2 );
1339 $num = substr( $ts, 12, 2 );
1347 // Pass through string from $dateTimeObj->format()
1348 if ( !$dateTimeObj ) {
1349 $dateTimeObj = DateTime
::createFromFormat(
1350 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1353 $s .= $dateTimeObj->format( $code );
1365 // Pass through number from $dateTimeObj->format()
1366 if ( !$dateTimeObj ) {
1367 $dateTimeObj = DateTime
::createFromFormat(
1368 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1371 $num = $dateTimeObj->format( $code );
1374 # Backslash escaping
1375 if ( $p < strlen( $format ) - 1 ) {
1376 $s .= $format[++
$p];
1383 if ( $p < strlen( $format ) - 1 ) {
1384 $endQuote = strpos( $format, '"', $p +
1 );
1385 if ( $endQuote === false ) {
1386 # No terminating quote, assume literal "
1389 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1393 # Quote at end of string, assume literal "
1400 if ( $num !== false ) {
1401 if ( $rawToggle ||
$raw ) {
1404 } elseif ( $roman ) {
1405 $s .= Language
::romanNumeral( $num );
1407 } elseif ( $hebrewNum ) {
1408 $s .= self
::hebrewNumeral( $num );
1411 $s .= $this->formatNum( $num, true );
1418 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1419 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1422 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1423 * Gregorian dates to Iranian dates. Originally written in C, it
1424 * is released under the terms of GNU Lesser General Public
1425 * License. Conversion to PHP was performed by Niklas Laxström.
1427 * Link: http://www.farsiweb.info/jalali/jalali.c
1433 private static function tsToIranian( $ts ) {
1434 $gy = substr( $ts, 0, 4 ) -1600;
1435 $gm = substr( $ts, 4, 2 ) -1;
1436 $gd = substr( $ts, 6, 2 ) -1;
1438 # Days passed from the beginning (including leap years)
1440 +
floor( ( $gy +
3 ) / 4 )
1441 - floor( ( $gy +
99 ) / 100 )
1442 +
floor( ( $gy +
399 ) / 400 );
1444 // Add days of the past months of this year
1445 for ( $i = 0; $i < $gm; $i++
) {
1446 $gDayNo +
= self
::$GREG_DAYS[$i];
1450 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1454 // Days passed in current month
1455 $gDayNo +
= (int)$gd;
1457 $jDayNo = $gDayNo - 79;
1459 $jNp = floor( $jDayNo / 12053 );
1462 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1465 if ( $jDayNo >= 366 ) {
1466 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1467 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1470 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1471 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1477 return array( $jy, $jm, $jd );
1481 * Converting Gregorian dates to Hijri dates.
1483 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1485 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1491 private static function tsToHijri( $ts ) {
1492 $year = substr( $ts, 0, 4 );
1493 $month = substr( $ts, 4, 2 );
1494 $day = substr( $ts, 6, 2 );
1502 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1503 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1506 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1507 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1508 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1511 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1512 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1515 $zl = $zjd -1948440 +
10632;
1516 $zn = (int)( ( $zl - 1 ) / 10631 );
1517 $zl = $zl - 10631 * $zn +
354;
1518 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1519 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1520 $zm = (int)( ( 24 * $zl ) / 709 );
1521 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1522 $zy = 30 * $zn +
$zj - 30;
1524 return array( $zy, $zm, $zd );
1528 * Converting Gregorian dates to Hebrew dates.
1530 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1531 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1532 * to translate the relevant functions into PHP and release them under
1535 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1536 * and Adar II is 14. In a non-leap year, Adar is 6.
1542 private static function tsToHebrew( $ts ) {
1544 $year = substr( $ts, 0, 4 );
1545 $month = substr( $ts, 4, 2 );
1546 $day = substr( $ts, 6, 2 );
1548 # Calculate Hebrew year
1549 $hebrewYear = $year +
3760;
1551 # Month number when September = 1, August = 12
1553 if ( $month > 12 ) {
1560 # Calculate day of year from 1 September
1562 for ( $i = 1; $i < $month; $i++
) {
1566 # Check if the year is leap
1567 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1570 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1577 # Calculate the start of the Hebrew year
1578 $start = self
::hebrewYearStart( $hebrewYear );
1580 # Calculate next year's start
1581 if ( $dayOfYear <= $start ) {
1582 # Day is before the start of the year - it is the previous year
1584 $nextStart = $start;
1588 # Add days since previous year's 1 September
1590 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1594 # Start of the new (previous) year
1595 $start = self
::hebrewYearStart( $hebrewYear );
1598 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1601 # Calculate Hebrew day of year
1602 $hebrewDayOfYear = $dayOfYear - $start;
1604 # Difference between year's days
1605 $diff = $nextStart - $start;
1606 # Add 12 (or 13 for leap years) days to ignore the difference between
1607 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1608 # difference is only about the year type
1609 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1615 # Check the year pattern, and is leap year
1616 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1617 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1618 # and non-leap years
1619 $yearPattern = $diff %
30;
1620 # Check if leap year
1621 $isLeap = $diff >= 30;
1623 # Calculate day in the month from number of day in the Hebrew year
1624 # Don't check Adar - if the day is not in Adar, we will stop before;
1625 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1626 $hebrewDay = $hebrewDayOfYear;
1629 while ( $hebrewMonth <= 12 ) {
1630 # Calculate days in this month
1631 if ( $isLeap && $hebrewMonth == 6 ) {
1632 # Adar in a leap year
1634 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1636 if ( $hebrewDay <= $days ) {
1640 # Subtract the days of Adar I
1641 $hebrewDay -= $days;
1644 if ( $hebrewDay <= $days ) {
1650 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1651 # Cheshvan in a complete year (otherwise as the rule below)
1653 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1654 # Kislev in an incomplete year (otherwise as the rule below)
1657 # Odd months have 30 days, even have 29
1658 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1660 if ( $hebrewDay <= $days ) {
1661 # In the current month
1664 # Subtract the days of the current month
1665 $hebrewDay -= $days;
1666 # Try in the next month
1671 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1675 * This calculates the Hebrew year start, as days since 1 September.
1676 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1677 * Used for Hebrew date.
1683 private static function hebrewYearStart( $year ) {
1684 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1685 $b = intval( ( $year - 1 ) %
4 );
1686 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1690 $Mar = intval( $m );
1696 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1697 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1699 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1701 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1705 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1710 * Algorithm to convert Gregorian dates to Thai solar dates,
1711 * Minguo dates or Minguo dates.
1713 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1714 * http://en.wikipedia.org/wiki/Minguo_calendar
1715 * http://en.wikipedia.org/wiki/Japanese_era_name
1717 * @param $ts String: 14-character timestamp
1718 * @param $cName String: calender name
1719 * @return Array: converted year, month, day
1721 private static function tsToYear( $ts, $cName ) {
1722 $gy = substr( $ts, 0, 4 );
1723 $gm = substr( $ts, 4, 2 );
1724 $gd = substr( $ts, 6, 2 );
1726 if ( !strcmp( $cName, 'thai' ) ) {
1728 # Add 543 years to the Gregorian calendar
1729 # Months and days are identical
1730 $gy_offset = $gy +
543;
1731 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1733 # Deduct 1911 years from the Gregorian calendar
1734 # Months and days are identical
1735 $gy_offset = $gy - 1911;
1736 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1737 # Nengō dates up to Meiji period
1738 # Deduct years from the Gregorian calendar
1739 # depending on the nengo periods
1740 # Months and days are identical
1741 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1743 $gy_gannen = $gy - 1868 +
1;
1744 $gy_offset = $gy_gannen;
1745 if ( $gy_gannen == 1 ) {
1748 $gy_offset = '明治' . $gy_offset;
1750 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1751 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1752 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1753 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1754 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1758 $gy_gannen = $gy - 1912 +
1;
1759 $gy_offset = $gy_gannen;
1760 if ( $gy_gannen == 1 ) {
1763 $gy_offset = '大正' . $gy_offset;
1765 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1766 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1767 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1771 $gy_gannen = $gy - 1926 +
1;
1772 $gy_offset = $gy_gannen;
1773 if ( $gy_gannen == 1 ) {
1776 $gy_offset = '昭和' . $gy_offset;
1779 $gy_gannen = $gy - 1989 +
1;
1780 $gy_offset = $gy_gannen;
1781 if ( $gy_gannen == 1 ) {
1784 $gy_offset = '平成' . $gy_offset;
1790 return array( $gy_offset, $gm, $gd );
1794 * Roman number formatting up to 10000
1800 static function romanNumeral( $num ) {
1801 static $table = array(
1802 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1803 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1804 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1805 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1808 $num = intval( $num );
1809 if ( $num > 10000 ||
$num <= 0 ) {
1814 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1815 if ( $num >= $pow10 ) {
1816 $s .= $table[$i][(int)floor( $num / $pow10 )];
1818 $num = $num %
$pow10;
1824 * Hebrew Gematria number formatting up to 9999
1830 static function hebrewNumeral( $num ) {
1831 static $table = array(
1832 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1833 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1834 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1835 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1838 $num = intval( $num );
1839 if ( $num > 9999 ||
$num <= 0 ) {
1844 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1845 if ( $num >= $pow10 ) {
1846 if ( $num == 15 ||
$num == 16 ) {
1847 $s .= $table[0][9] . $table[0][$num - 9];
1850 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1851 if ( $pow10 == 1000 ) {
1856 $num = $num %
$pow10;
1858 if ( strlen( $s ) == 2 ) {
1861 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1862 $str .= substr( $s, strlen( $s ) - 2, 2 );
1864 $start = substr( $str, 0, strlen( $str ) - 2 );
1865 $end = substr( $str, strlen( $str ) - 2 );
1868 $str = $start . 'ך';
1871 $str = $start . 'ם';
1874 $str = $start . 'ן';
1877 $str = $start . 'ף';
1880 $str = $start . 'ץ';
1887 * Used by date() and time() to adjust the time output.
1889 * @param $ts Int the time in date('YmdHis') format
1890 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1891 * get user timecorrection setting)
1894 function userAdjust( $ts, $tz = false ) {
1895 global $wgUser, $wgLocalTZoffset;
1897 if ( $tz === false ) {
1898 $tz = $wgUser->getOption( 'timecorrection' );
1901 $data = explode( '|', $tz, 3 );
1903 if ( $data[0] == 'ZoneInfo' ) {
1904 wfSuppressWarnings();
1905 $userTZ = timezone_open( $data[2] );
1906 wfRestoreWarnings();
1907 if ( $userTZ !== false ) {
1908 $date = date_create( $ts, timezone_open( 'UTC' ) );
1909 date_timezone_set( $date, $userTZ );
1910 $date = date_format( $date, 'YmdHis' );
1913 # Unrecognized timezone, default to 'Offset' with the stored offset.
1914 $data[0] = 'Offset';
1918 if ( $data[0] == 'System' ||
$tz == '' ) {
1919 # Global offset in minutes.
1920 if ( isset( $wgLocalTZoffset ) ) {
1921 $minDiff = $wgLocalTZoffset;
1923 } elseif ( $data[0] == 'Offset' ) {
1924 $minDiff = intval( $data[1] );
1926 $data = explode( ':', $tz );
1927 if ( count( $data ) == 2 ) {
1928 $data[0] = intval( $data[0] );
1929 $data[1] = intval( $data[1] );
1930 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1931 if ( $data[0] < 0 ) {
1932 $minDiff = -$minDiff;
1935 $minDiff = intval( $data[0] ) * 60;
1939 # No difference ? Return time unchanged
1940 if ( 0 == $minDiff ) {
1944 wfSuppressWarnings(); // E_STRICT system time bitching
1945 # Generate an adjusted date; take advantage of the fact that mktime
1946 # will normalize out-of-range values so we don't have to split $minDiff
1947 # into hours and minutes.
1949 (int)substr( $ts, 8, 2 ) ), # Hours
1950 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1951 (int)substr( $ts, 12, 2 ), # Seconds
1952 (int)substr( $ts, 4, 2 ), # Month
1953 (int)substr( $ts, 6, 2 ), # Day
1954 (int)substr( $ts, 0, 4 ) ); # Year
1956 $date = date( 'YmdHis', $t );
1957 wfRestoreWarnings();
1963 * This is meant to be used by time(), date(), and timeanddate() to get
1964 * the date preference they're supposed to use, it should be used in
1968 * function timeanddate([...], $format = true) {
1969 * $datePreference = $this->dateFormat($format);
1974 * @param $usePrefs Mixed: if true, the user's preference is used
1975 * if false, the site/language default is used
1976 * if int/string, assumed to be a format.
1979 function dateFormat( $usePrefs = true ) {
1982 if ( is_bool( $usePrefs ) ) {
1984 $datePreference = $wgUser->getDatePreference();
1986 $datePreference = (string)User
::getDefaultOption( 'date' );
1989 $datePreference = (string)$usePrefs;
1993 if ( $datePreference == '' ) {
1997 return $datePreference;
2001 * Get a format string for a given type and preference
2002 * @param $type string May be date, time or both
2003 * @param $pref string The format name as it appears in Messages*.php
2005 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2009 function getDateFormatString( $type, $pref ) {
2010 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2011 if ( $pref == 'default' ) {
2012 $pref = $this->getDefaultDateFormat();
2013 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2015 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2017 if ( $type === 'pretty' && $df === null ) {
2018 $df = $this->getDateFormatString( 'date', $pref );
2021 if ( $df === null ) {
2022 $pref = $this->getDefaultDateFormat();
2023 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2026 $this->dateFormatStrings
[$type][$pref] = $df;
2028 return $this->dateFormatStrings
[$type][$pref];
2032 * @param $ts Mixed: the time format which needs to be turned into a
2033 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2034 * @param $adj Bool: whether to adjust the time output according to the
2035 * user configured offset ($timecorrection)
2036 * @param $format Mixed: true to use user's date format preference
2037 * @param $timecorrection String|bool the time offset as returned by
2038 * validateTimeZone() in Special:Preferences
2041 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2042 $ts = wfTimestamp( TS_MW
, $ts );
2044 $ts = $this->userAdjust( $ts, $timecorrection );
2046 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2047 return $this->sprintfDate( $df, $ts );
2051 * @param $ts Mixed: the time format which needs to be turned into a
2052 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2053 * @param $adj Bool: whether to adjust the time output according to the
2054 * user configured offset ($timecorrection)
2055 * @param $format Mixed: true to use user's date format preference
2056 * @param $timecorrection String|bool the time offset as returned by
2057 * validateTimeZone() in Special:Preferences
2060 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2061 $ts = wfTimestamp( TS_MW
, $ts );
2063 $ts = $this->userAdjust( $ts, $timecorrection );
2065 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2066 return $this->sprintfDate( $df, $ts );
2070 * @param $ts Mixed: the time format which needs to be turned into a
2071 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2072 * @param $adj Bool: whether to adjust the time output according to the
2073 * user configured offset ($timecorrection)
2074 * @param $format Mixed: what format to return, if it's false output the
2075 * default one (default true)
2076 * @param $timecorrection String|bool the time offset as returned by
2077 * validateTimeZone() in Special:Preferences
2080 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2081 $ts = wfTimestamp( TS_MW
, $ts );
2083 $ts = $this->userAdjust( $ts, $timecorrection );
2085 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2086 return $this->sprintfDate( $df, $ts );
2090 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2094 * @param integer $seconds The amount of seconds.
2095 * @param array $chosenIntervals The intervals to enable.
2099 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2100 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2102 $segments = array();
2104 foreach ( $intervals as $intervalName => $intervalValue ) {
2105 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2106 // duration-years, duration-decades, duration-centuries, duration-millennia
2107 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2108 $segments[] = $message->inLanguage( $this )->escaped();
2111 return $this->listToText( $segments );
2115 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2116 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2120 * @param integer $seconds The amount of seconds.
2121 * @param array $chosenIntervals The intervals to enable.
2125 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2126 if ( empty( $chosenIntervals ) ) {
2127 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2130 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2131 $sortedNames = array_keys( $intervals );
2132 $smallestInterval = array_pop( $sortedNames );
2134 $segments = array();
2136 foreach ( $intervals as $name => $length ) {
2137 $value = floor( $seconds / $length );
2139 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2140 $seconds -= $value * $length;
2141 $segments[$name] = $value;
2149 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2151 * @param $type String: can be 'date', 'time' or 'both'
2152 * @param $ts Mixed: the time format which needs to be turned into a
2153 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2154 * @param $user User object used to get preferences for timezone and format
2155 * @param $options Array, can contain the following keys:
2156 * - 'timecorrection': time correction, can have the following values:
2157 * - true: use user's preference
2158 * - false: don't use time correction
2159 * - integer: value of time correction in minutes
2160 * - 'format': format to use, can have the following values:
2161 * - true: use user's preference
2162 * - false: use default preference
2163 * - string: format to use
2167 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2168 $ts = wfTimestamp( TS_MW
, $ts );
2169 $options +
= array( 'timecorrection' => true, 'format' => true );
2170 if ( $options['timecorrection'] !== false ) {
2171 if ( $options['timecorrection'] === true ) {
2172 $offset = $user->getOption( 'timecorrection' );
2174 $offset = $options['timecorrection'];
2176 $ts = $this->userAdjust( $ts, $offset );
2178 if ( $options['format'] === true ) {
2179 $format = $user->getDatePreference();
2181 $format = $options['format'];
2183 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2184 return $this->sprintfDate( $df, $ts );
2188 * Get the formatted date for the given timestamp and formatted for
2191 * @param $ts Mixed: the time format which needs to be turned into a
2192 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2193 * @param $user User object used to get preferences for timezone and format
2194 * @param $options Array, can contain the following keys:
2195 * - 'timecorrection': time correction, can have the following values:
2196 * - true: use user's preference
2197 * - false: don't use time correction
2198 * - integer: value of time correction in minutes
2199 * - 'format': format to use, can have the following values:
2200 * - true: use user's preference
2201 * - false: use default preference
2202 * - string: format to use
2206 public function userDate( $ts, User
$user, array $options = array() ) {
2207 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2211 * Get the formatted time for the given timestamp and formatted for
2214 * @param $ts Mixed: the time format which needs to be turned into a
2215 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2216 * @param $user User object used to get preferences for timezone and format
2217 * @param $options Array, can contain the following keys:
2218 * - 'timecorrection': time correction, can have the following values:
2219 * - true: use user's preference
2220 * - false: don't use time correction
2221 * - integer: value of time correction in minutes
2222 * - 'format': format to use, can have the following values:
2223 * - true: use user's preference
2224 * - false: use default preference
2225 * - string: format to use
2229 public function userTime( $ts, User
$user, array $options = array() ) {
2230 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2234 * Get the formatted date and time for the given timestamp and formatted for
2237 * @param $ts Mixed: the time format which needs to be turned into a
2238 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2239 * @param $user User object used to get preferences for timezone and format
2240 * @param $options Array, can contain the following keys:
2241 * - 'timecorrection': time correction, can have the following values:
2242 * - true: use user's preference
2243 * - false: don't use time correction
2244 * - integer: value of time correction in minutes
2245 * - 'format': format to use, can have the following values:
2246 * - true: use user's preference
2247 * - false: use default preference
2248 * - string: format to use
2252 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2253 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2257 * Convert an MWTimestamp into a pretty human-readable timestamp using
2258 * the given user preferences and relative base time.
2260 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2261 * on your timestamp object, which will then call this function. Calling
2262 * this function directly will cause hooks to be skipped over.
2264 * @see MWTimestamp::getHumanTimestamp
2265 * @param MWTimestamp $ts Timestamp to prettify
2266 * @param MWTimestamp $relativeTo Base timestamp
2267 * @param User $user User preferences to use
2268 * @return string Human timestamp
2271 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2272 $diff = $ts->diff( $relativeTo );
2273 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) - (int)$relativeTo->timestamp
->format( 'w' ) );
2274 $days = $diff->days ?
: (int)$diffDay;
2275 if ( $diff->invert ||
$days > 5 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' ) ) {
2276 // Timestamps are in different years: use full timestamp
2277 // Also do full timestamp for future dates
2279 * @FIXME Add better handling of future timestamps.
2281 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2282 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2283 } elseif ( $days > 5 ) {
2284 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2285 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2286 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2287 } elseif ( $days > 1 ) {
2288 // Timestamp within the past week: show the day of the week and time
2289 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2290 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2291 $ts = wfMessage( "$weekday-at" )
2292 ->inLanguage( $this )
2293 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2295 } elseif ( $days == 1 ) {
2296 // Timestamp was yesterday: say 'yesterday' and the time.
2297 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2298 $ts = wfMessage( 'yesterday-at' )
2299 ->inLanguage( $this )
2300 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2302 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2303 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2304 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2305 $ts = wfMessage( 'today-at' )
2306 ->inLanguage( $this )
2307 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2310 // From here on in, the timestamp was soon enough ago so that we can simply say
2311 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2312 } elseif ( $diff->h
== 1 ) {
2313 // Less than 90 minutes, but more than an hour ago.
2314 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2315 } elseif ( $diff->i
>= 1 ) {
2316 // A few minutes ago.
2317 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2318 } elseif ( $diff->s
>= 30 ) {
2319 // Less than a minute, but more than 30 sec ago.
2320 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2322 // Less than 30 seconds ago.
2323 $ts = wfMessage( 'just-now' )->text();
2330 * @param $key string
2331 * @return array|null
2333 function getMessage( $key ) {
2334 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2340 function getAllMessages() {
2341 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2350 function iconv( $in, $out, $string ) {
2351 # This is a wrapper for iconv in all languages except esperanto,
2352 # which does some nasty x-conversions beforehand
2354 # Even with //IGNORE iconv can whine about illegal characters in
2355 # *input* string. We just ignore those too.
2356 # REF: http://bugs.php.net/bug.php?id=37166
2357 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2358 wfSuppressWarnings();
2359 $text = iconv( $in, $out . '//IGNORE', $string );
2360 wfRestoreWarnings();
2364 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2367 * @param $matches array
2368 * @return mixed|string
2370 function ucwordbreaksCallbackAscii( $matches ) {
2371 return $this->ucfirst( $matches[1] );
2375 * @param $matches array
2378 function ucwordbreaksCallbackMB( $matches ) {
2379 return mb_strtoupper( $matches[0] );
2383 * @param $matches array
2386 function ucCallback( $matches ) {
2387 list( $wikiUpperChars ) = self
::getCaseMaps();
2388 return strtr( $matches[1], $wikiUpperChars );
2392 * @param $matches array
2395 function lcCallback( $matches ) {
2396 list( , $wikiLowerChars ) = self
::getCaseMaps();
2397 return strtr( $matches[1], $wikiLowerChars );
2401 * @param $matches array
2404 function ucwordsCallbackMB( $matches ) {
2405 return mb_strtoupper( $matches[0] );
2409 * @param $matches array
2412 function ucwordsCallbackWiki( $matches ) {
2413 list( $wikiUpperChars ) = self
::getCaseMaps();
2414 return strtr( $matches[0], $wikiUpperChars );
2418 * Make a string's first character uppercase
2420 * @param $str string
2424 function ucfirst( $str ) {
2426 if ( $o < 96 ) { // if already uppercase...
2428 } elseif ( $o < 128 ) {
2429 return ucfirst( $str ); // use PHP's ucfirst()
2431 // fall back to more complex logic in case of multibyte strings
2432 return $this->uc( $str, true );
2437 * Convert a string to uppercase
2439 * @param $str string
2440 * @param $first bool
2444 function uc( $str, $first = false ) {
2445 if ( function_exists( 'mb_strtoupper' ) ) {
2447 if ( $this->isMultibyte( $str ) ) {
2448 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2450 return ucfirst( $str );
2453 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2456 if ( $this->isMultibyte( $str ) ) {
2457 $x = $first ?
'^' : '';
2458 return preg_replace_callback(
2459 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2460 array( $this, 'ucCallback' ),
2464 return $first ?
ucfirst( $str ) : strtoupper( $str );
2470 * @param $str string
2471 * @return mixed|string
2473 function lcfirst( $str ) {
2476 return strval( $str );
2477 } elseif ( $o >= 128 ) {
2478 return $this->lc( $str, true );
2479 } elseif ( $o > 96 ) {
2482 $str[0] = strtolower( $str[0] );
2488 * @param $str string
2489 * @param $first bool
2490 * @return mixed|string
2492 function lc( $str, $first = false ) {
2493 if ( function_exists( 'mb_strtolower' ) ) {
2495 if ( $this->isMultibyte( $str ) ) {
2496 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2498 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2501 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2504 if ( $this->isMultibyte( $str ) ) {
2505 $x = $first ?
'^' : '';
2506 return preg_replace_callback(
2507 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2508 array( $this, 'lcCallback' ),
2512 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2518 * @param $str string
2521 function isMultibyte( $str ) {
2522 return (bool)preg_match( '/[\x80-\xff]/', $str );
2526 * @param $str string
2527 * @return mixed|string
2529 function ucwords( $str ) {
2530 if ( $this->isMultibyte( $str ) ) {
2531 $str = $this->lc( $str );
2533 // regexp to find first letter in each word (i.e. after each space)
2534 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2536 // function to use to capitalize a single char
2537 if ( function_exists( 'mb_strtoupper' ) ) {
2538 return preg_replace_callback(
2540 array( $this, 'ucwordsCallbackMB' ),
2544 return preg_replace_callback(
2546 array( $this, 'ucwordsCallbackWiki' ),
2551 return ucwords( strtolower( $str ) );
2556 * capitalize words at word breaks
2558 * @param $str string
2561 function ucwordbreaks( $str ) {
2562 if ( $this->isMultibyte( $str ) ) {
2563 $str = $this->lc( $str );
2565 // since \b doesn't work for UTF-8, we explicitely define word break chars
2566 $breaks = "[ \-\(\)\}\{\.,\?!]";
2568 // find first letter after word break
2569 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2571 if ( function_exists( 'mb_strtoupper' ) ) {
2572 return preg_replace_callback(
2574 array( $this, 'ucwordbreaksCallbackMB' ),
2578 return preg_replace_callback(
2580 array( $this, 'ucwordsCallbackWiki' ),
2585 return preg_replace_callback(
2586 '/\b([\w\x80-\xff]+)\b/',
2587 array( $this, 'ucwordbreaksCallbackAscii' ),
2594 * Return a case-folded representation of $s
2596 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2597 * and $s2 are the same except for the case of their characters. It is not
2598 * necessary for the value returned to make sense when displayed.
2600 * Do *not* perform any other normalisation in this function. If a caller
2601 * uses this function when it should be using a more general normalisation
2602 * function, then fix the caller.
2608 function caseFold( $s ) {
2609 return $this->uc( $s );
2616 function checkTitleEncoding( $s ) {
2617 if ( is_array( $s ) ) {
2618 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2620 if ( StringUtils
::isUtf8( $s ) ) {
2624 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2630 function fallback8bitEncoding() {
2631 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2635 * Most writing systems use whitespace to break up words.
2636 * Some languages such as Chinese don't conventionally do this,
2637 * which requires special handling when breaking up words for
2642 function hasWordBreaks() {
2647 * Some languages such as Chinese require word segmentation,
2648 * Specify such segmentation when overridden in derived class.
2650 * @param $string String
2653 function segmentByWord( $string ) {
2658 * Some languages have special punctuation need to be normalized.
2659 * Make such changes here.
2661 * @param $string String
2664 function normalizeForSearch( $string ) {
2665 return self
::convertDoubleWidth( $string );
2669 * convert double-width roman characters to single-width.
2670 * range: ff00-ff5f ~= 0020-007f
2672 * @param $string string
2676 protected static function convertDoubleWidth( $string ) {
2677 static $full = null;
2678 static $half = null;
2680 if ( $full === null ) {
2681 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2682 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2683 $full = str_split( $fullWidth, 3 );
2684 $half = str_split( $halfWidth );
2687 $string = str_replace( $full, $half, $string );
2692 * @param $string string
2693 * @param $pattern string
2696 protected static function insertSpace( $string, $pattern ) {
2697 $string = preg_replace( $pattern, " $1 ", $string );
2698 $string = preg_replace( '/ +/', ' ', $string );
2703 * @param $termsArray array
2706 function convertForSearchResult( $termsArray ) {
2707 # some languages, e.g. Chinese, need to do a conversion
2708 # in order for search results to be displayed correctly
2713 * Get the first character of a string.
2718 function firstChar( $s ) {
2721 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2722 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2727 if ( isset( $matches[1] ) ) {
2728 if ( strlen( $matches[1] ) != 3 ) {
2732 // Break down Hangul syllables to grab the first jamo
2733 $code = utf8ToCodepoint( $matches[1] );
2734 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2736 } elseif ( $code < 0xb098 ) {
2737 return "\xe3\x84\xb1";
2738 } elseif ( $code < 0xb2e4 ) {
2739 return "\xe3\x84\xb4";
2740 } elseif ( $code < 0xb77c ) {
2741 return "\xe3\x84\xb7";
2742 } elseif ( $code < 0xb9c8 ) {
2743 return "\xe3\x84\xb9";
2744 } elseif ( $code < 0xbc14 ) {
2745 return "\xe3\x85\x81";
2746 } elseif ( $code < 0xc0ac ) {
2747 return "\xe3\x85\x82";
2748 } elseif ( $code < 0xc544 ) {
2749 return "\xe3\x85\x85";
2750 } elseif ( $code < 0xc790 ) {
2751 return "\xe3\x85\x87";
2752 } elseif ( $code < 0xcc28 ) {
2753 return "\xe3\x85\x88";
2754 } elseif ( $code < 0xce74 ) {
2755 return "\xe3\x85\x8a";
2756 } elseif ( $code < 0xd0c0 ) {
2757 return "\xe3\x85\x8b";
2758 } elseif ( $code < 0xd30c ) {
2759 return "\xe3\x85\x8c";
2760 } elseif ( $code < 0xd558 ) {
2761 return "\xe3\x85\x8d";
2763 return "\xe3\x85\x8e";
2770 function initEncoding() {
2771 # Some languages may have an alternate char encoding option
2772 # (Esperanto X-coding, Japanese furigana conversion, etc)
2773 # If this language is used as the primary content language,
2774 # an override to the defaults can be set here on startup.
2781 function recodeForEdit( $s ) {
2782 # For some languages we'll want to explicitly specify
2783 # which characters make it into the edit box raw
2784 # or are converted in some way or another.
2785 global $wgEditEncoding;
2786 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2789 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2797 function recodeInput( $s ) {
2798 # Take the previous into account.
2799 global $wgEditEncoding;
2800 if ( $wgEditEncoding != '' ) {
2801 $enc = $wgEditEncoding;
2805 if ( $enc == 'UTF-8' ) {
2808 return $this->iconv( $enc, 'UTF-8', $s );
2813 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2814 * also cleans up certain backwards-compatible sequences, converting them
2815 * to the modern Unicode equivalent.
2817 * This is language-specific for performance reasons only.
2823 function normalize( $s ) {
2824 global $wgAllUnicodeFixes;
2825 $s = UtfNormal
::cleanUp( $s );
2826 if ( $wgAllUnicodeFixes ) {
2827 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2828 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2835 * Transform a string using serialized data stored in the given file (which
2836 * must be in the serialized subdirectory of $IP). The file contains pairs
2837 * mapping source characters to destination characters.
2839 * The data is cached in process memory. This will go faster if you have the
2840 * FastStringSearch extension.
2842 * @param $file string
2843 * @param $string string
2845 * @throws MWException
2848 function transformUsingPairFile( $file, $string ) {
2849 if ( !isset( $this->transformData
[$file] ) ) {
2850 $data = wfGetPrecompiledData( $file );
2851 if ( $data === false ) {
2852 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2854 $this->transformData
[$file] = new ReplacementArray( $data );
2856 return $this->transformData
[$file]->replace( $string );
2860 * For right-to-left language support
2865 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2869 * Return the correct HTML 'dir' attribute value for this language.
2873 return $this->isRTL() ?
'rtl' : 'ltr';
2877 * Return 'left' or 'right' as appropriate alignment for line-start
2878 * for this language's text direction.
2880 * Should be equivalent to CSS3 'start' text-align value....
2884 function alignStart() {
2885 return $this->isRTL() ?
'right' : 'left';
2889 * Return 'right' or 'left' as appropriate alignment for line-end
2890 * for this language's text direction.
2892 * Should be equivalent to CSS3 'end' text-align value....
2896 function alignEnd() {
2897 return $this->isRTL() ?
'left' : 'right';
2901 * A hidden direction mark (LRM or RLM), depending on the language direction.
2902 * Unlike getDirMark(), this function returns the character as an HTML entity.
2903 * This function should be used when the output is guaranteed to be HTML,
2904 * because it makes the output HTML source code more readable. When
2905 * the output is plain text or can be escaped, getDirMark() should be used.
2907 * @param $opposite Boolean Get the direction mark opposite to your language
2911 function getDirMarkEntity( $opposite = false ) {
2913 return $this->isRTL() ?
'‎' : '‏';
2915 return $this->isRTL() ?
'‏' : '‎';
2919 * A hidden direction mark (LRM or RLM), depending on the language direction.
2920 * This function produces them as invisible Unicode characters and
2921 * the output may be hard to read and debug, so it should only be used
2922 * when the output is plain text or can be escaped. When the output is
2923 * HTML, use getDirMarkEntity() instead.
2925 * @param $opposite Boolean Get the direction mark opposite to your language
2928 function getDirMark( $opposite = false ) {
2929 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2930 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2932 return $this->isRTL() ?
$lrm : $rlm;
2934 return $this->isRTL() ?
$rlm : $lrm;
2940 function capitalizeAllNouns() {
2941 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2945 * An arrow, depending on the language direction.
2947 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2950 function getArrow( $direction = 'forwards' ) {
2951 switch ( $direction ) {
2953 return $this->isRTL() ?
'←' : '→';
2955 return $this->isRTL() ?
'→' : '←';
2968 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2972 function linkPrefixExtension() {
2973 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2977 * Get all magic words from cache.
2980 function getMagicWords() {
2981 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2985 * Run the LanguageGetMagic hook once.
2987 protected function doMagicHook() {
2988 if ( $this->mMagicHookDone
) {
2991 $this->mMagicHookDone
= true;
2992 wfProfileIn( 'LanguageGetMagic' );
2993 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2994 wfProfileOut( 'LanguageGetMagic' );
2998 * Fill a MagicWord object with data from here
3002 function getMagic( $mw ) {
3003 // Saves a function call
3004 if ( ! $this->mMagicHookDone
) {
3005 $this->doMagicHook();
3008 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3009 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3011 $rawEntry = self
::$dataCache->getSubitem(
3012 $this->mCode
, 'magicWords', $mw->mId
);
3015 if ( !is_array( $rawEntry ) ) {
3016 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3018 $mw->mCaseSensitive
= $rawEntry[0];
3019 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3024 * Add magic words to the extension array
3026 * @param $newWords array
3028 function addMagicWordsByLang( $newWords ) {
3029 $fallbackChain = $this->getFallbackLanguages();
3030 $fallbackChain = array_reverse( $fallbackChain );
3031 foreach ( $fallbackChain as $code ) {
3032 if ( isset( $newWords[$code] ) ) {
3033 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3039 * Get special page names, as an associative array
3040 * case folded alias => real name
3042 function getSpecialPageAliases() {
3043 // Cache aliases because it may be slow to load them
3044 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3046 $this->mExtendedSpecialPageAliases
=
3047 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3048 wfRunHooks( 'LanguageGetSpecialPageAliases',
3049 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3052 return $this->mExtendedSpecialPageAliases
;
3056 * Italic is unsuitable for some languages
3058 * @param $text String: the text to be emphasized.
3061 function emphasize( $text ) {
3062 return "<em>$text</em>";
3066 * Normally we output all numbers in plain en_US style, that is
3067 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3068 * point twohundredthirtyfive. However this is not suitable for all
3069 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3070 * Icelandic just want to use commas instead of dots, and dots instead
3071 * of commas like "293.291,235".
3073 * An example of this function being called:
3075 * wfMessage( 'message' )->numParams( $num )->text()
3078 * See LanguageGu.php for the Gujarati implementation and
3079 * $separatorTransformTable on MessageIs.php for
3080 * the , => . and . => , implementation.
3082 * @todo check if it's viable to use localeconv() for the decimal
3084 * @param $number Mixed: the string to be formatted, should be an integer
3085 * or a floating point number.
3086 * @param $nocommafy Bool: set to true for special numbers like dates
3089 public function formatNum( $number, $nocommafy = false ) {
3090 global $wgTranslateNumerals;
3091 if ( !$nocommafy ) {
3092 $number = $this->commafy( $number );
3093 $s = $this->separatorTransformTable();
3095 $number = strtr( $number, $s );
3099 if ( $wgTranslateNumerals ) {
3100 $s = $this->digitTransformTable();
3102 $number = strtr( $number, $s );
3110 * Front-end for non-commafied formatNum
3112 * @param mixed $number the string to be formatted, should be an integer
3113 * or a floating point number.
3117 public function formatNumNoSeparators( $number ) {
3118 return $this->formatNum( $number, true );
3122 * @param $number string
3125 function parseFormattedNumber( $number ) {
3126 $s = $this->digitTransformTable();
3128 $number = strtr( $number, array_flip( $s ) );
3131 $s = $this->separatorTransformTable();
3133 $number = strtr( $number, array_flip( $s ) );
3136 $number = strtr( $number, array( ',' => '' ) );
3141 * Adds commas to a given number
3143 * @param $number mixed
3146 function commafy( $number ) {
3147 $digitGroupingPattern = $this->digitGroupingPattern();
3148 if ( $number === null ) {
3152 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3153 // default grouping is at thousands, use the same for ###,###,### pattern too.
3154 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3156 // Ref: http://cldr.unicode.org/translation/number-patterns
3158 if ( intval( $number ) < 0 ) {
3159 // For negative numbers apply the algorithm like positive number and add sign.
3161 $number = substr( $number, 1 );
3163 $integerPart = array();
3164 $decimalPart = array();
3165 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3166 preg_match( "/\d+/", $number, $integerPart );
3167 preg_match( "/\.\d*/", $number, $decimalPart );
3168 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3169 if ( $groupedNumber === $number ) {
3170 // the string does not have any number part. Eg: .12345
3171 return $sign . $groupedNumber;
3173 $start = $end = strlen( $integerPart[0] );
3174 while ( $start > 0 ) {
3175 $match = $matches[0][$numMatches - 1];
3176 $matchLen = strlen( $match );
3177 $start = $end - $matchLen;
3181 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3183 if ( $numMatches > 1 ) {
3184 // use the last pattern for the rest of the number
3188 $groupedNumber = "," . $groupedNumber;
3191 return $sign . $groupedNumber;
3198 function digitGroupingPattern() {
3199 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3205 function digitTransformTable() {
3206 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3212 function separatorTransformTable() {
3213 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3217 * Take a list of strings and build a locale-friendly comma-separated
3218 * list, using the local comma-separator message.
3219 * The last two strings are chained with an "and".
3220 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3225 function listToText( array $l ) {
3226 $m = count( $l ) - 1;
3231 $and = $this->getMessageFromDB( 'and' );
3232 $space = $this->getMessageFromDB( 'word-separator' );
3234 $comma = $this->getMessageFromDB( 'comma-separator' );
3238 for ( $i = $m - 1; $i >= 0; $i-- ) {
3239 if ( $i == $m - 1 ) {
3240 $s = $l[$i] . $and . $space . $s;
3242 $s = $l[$i] . $comma . $s;
3249 * Take a list of strings and build a locale-friendly comma-separated
3250 * list, using the local comma-separator message.
3251 * @param $list array of strings to put in a comma list
3254 function commaList( array $list ) {
3256 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3262 * Take a list of strings and build a locale-friendly semicolon-separated
3263 * list, using the local semicolon-separator message.
3264 * @param $list array of strings to put in a semicolon list
3267 function semicolonList( array $list ) {
3269 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3275 * Same as commaList, but separate it with the pipe instead.
3276 * @param $list array of strings to put in a pipe list
3279 function pipeList( array $list ) {
3281 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3287 * Truncate a string to a specified length in bytes, appending an optional
3288 * string (e.g. for ellipses)
3290 * The database offers limited byte lengths for some columns in the database;
3291 * multi-byte character sets mean we need to ensure that only whole characters
3292 * are included, otherwise broken characters can be passed to the user
3294 * If $length is negative, the string will be truncated from the beginning
3296 * @param $string String to truncate
3297 * @param $length Int: maximum length (including ellipses)
3298 * @param $ellipsis String to append to the truncated text
3299 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3300 * $adjustLength was introduced in 1.18, before that behaved as if false.
3303 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3304 # Use the localized ellipsis character
3305 if ( $ellipsis == '...' ) {
3306 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3308 # Check if there is no need to truncate
3309 if ( $length == 0 ) {
3310 return $ellipsis; // convention
3311 } elseif ( strlen( $string ) <= abs( $length ) ) {
3312 return $string; // no need to truncate
3314 $stringOriginal = $string;
3315 # If ellipsis length is >= $length then we can't apply $adjustLength
3316 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3317 $string = $ellipsis; // this can be slightly unexpected
3318 # Otherwise, truncate and add ellipsis...
3320 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3321 if ( $length > 0 ) {
3322 $length -= $eLength;
3323 $string = substr( $string, 0, $length ); // xyz...
3324 $string = $this->removeBadCharLast( $string );
3325 $string = $string . $ellipsis;
3327 $length +
= $eLength;
3328 $string = substr( $string, $length ); // ...xyz
3329 $string = $this->removeBadCharFirst( $string );
3330 $string = $ellipsis . $string;
3333 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3334 # This check is *not* redundant if $adjustLength, due to the single case where
3335 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3336 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3339 return $stringOriginal;
3344 * Remove bytes that represent an incomplete Unicode character
3345 * at the end of string (e.g. bytes of the char are missing)
3347 * @param $string String
3350 protected function removeBadCharLast( $string ) {
3351 if ( $string != '' ) {
3352 $char = ord( $string[strlen( $string ) - 1] );
3354 if ( $char >= 0xc0 ) {
3355 # We got the first byte only of a multibyte char; remove it.
3356 $string = substr( $string, 0, -1 );
3357 } elseif ( $char >= 0x80 &&
3358 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3359 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3361 # We chopped in the middle of a character; remove it
3369 * Remove bytes that represent an incomplete Unicode character
3370 * at the start of string (e.g. bytes of the char are missing)
3372 * @param $string String
3375 protected function removeBadCharFirst( $string ) {
3376 if ( $string != '' ) {
3377 $char = ord( $string[0] );
3378 if ( $char >= 0x80 && $char < 0xc0 ) {
3379 # We chopped in the middle of a character; remove the whole thing
3380 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3387 * Truncate a string of valid HTML to a specified length in bytes,
3388 * appending an optional string (e.g. for ellipses), and return valid HTML
3390 * This is only intended for styled/linked text, such as HTML with
3391 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3392 * Also, this will not detect things like "display:none" CSS.
3394 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3396 * @param string $text HTML string to truncate
3397 * @param int $length (zero/positive) Maximum length (including ellipses)
3398 * @param string $ellipsis String to append to the truncated text
3401 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3402 # Use the localized ellipsis character
3403 if ( $ellipsis == '...' ) {
3404 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3406 # Check if there is clearly no need to truncate
3407 if ( $length <= 0 ) {
3408 return $ellipsis; // no text shown, nothing to format (convention)
3409 } elseif ( strlen( $text ) <= $length ) {
3410 return $text; // string short enough even *with* HTML (short-circuit)
3413 $dispLen = 0; // innerHTML legth so far
3414 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3415 $tagType = 0; // 0-open, 1-close
3416 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3417 $entityState = 0; // 0-not entity, 1-entity
3418 $tag = $ret = ''; // accumulated tag name, accumulated result string
3419 $openTags = array(); // open tag stack
3420 $maybeState = null; // possible truncation state
3422 $textLen = strlen( $text );
3423 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3424 for ( $pos = 0; true; ++
$pos ) {
3425 # Consider truncation once the display length has reached the maximim.
3426 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3427 # Check that we're not in the middle of a bracket/entity...
3428 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3429 if ( !$testingEllipsis ) {
3430 $testingEllipsis = true;
3431 # Save where we are; we will truncate here unless there turn out to
3432 # be so few remaining characters that truncation is not necessary.
3433 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3434 $maybeState = array( $ret, $openTags ); // save state
3436 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3437 # String in fact does need truncation, the truncation point was OK.
3438 list( $ret, $openTags ) = $maybeState; // reload state
3439 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3440 $ret .= $ellipsis; // add ellipsis
3444 if ( $pos >= $textLen ) {
3445 break; // extra iteration just for above checks
3448 # Read the next char...
3450 $lastCh = $pos ?
$text[$pos - 1] : '';
3451 $ret .= $ch; // add to result string
3453 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3454 $entityState = 0; // for bad HTML
3455 $bracketState = 1; // tag started (checking for backslash)
3456 } elseif ( $ch == '>' ) {
3457 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3458 $entityState = 0; // for bad HTML
3459 $bracketState = 0; // out of brackets
3460 } elseif ( $bracketState == 1 ) {
3462 $tagType = 1; // close tag (e.g. "</span>")
3464 $tagType = 0; // open tag (e.g. "<span>")
3467 $bracketState = 2; // building tag name
3468 } elseif ( $bracketState == 2 ) {
3472 // Name found (e.g. "<a href=..."), add on tag attributes...
3473 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3475 } elseif ( $bracketState == 0 ) {
3476 if ( $entityState ) {
3479 $dispLen++
; // entity is one displayed char
3482 if ( $neLength == 0 && !$maybeState ) {
3483 // Save state without $ch. We want to *hit* the first
3484 // display char (to get tags) but not *use* it if truncating.
3485 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3488 $entityState = 1; // entity found, (e.g. " ")
3490 $dispLen++
; // this char is displayed
3491 // Add the next $max display text chars after this in one swoop...
3492 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3493 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3494 $dispLen +
= $skipped;
3500 // Close the last tag if left unclosed by bad HTML
3501 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3502 while ( count( $openTags ) > 0 ) {
3503 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3509 * truncateHtml() helper function
3510 * like strcspn() but adds the skipped chars to $ret
3519 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3520 if ( $len === null ) {
3521 $len = -1; // -1 means "no limit" for strcspn
3522 } elseif ( $len < 0 ) {
3526 if ( $start < strlen( $text ) ) {
3527 $skipCount = strcspn( $text, $search, $start, $len );
3528 $ret .= substr( $text, $start, $skipCount );
3534 * truncateHtml() helper function
3535 * (a) push or pop $tag from $openTags as needed
3536 * (b) clear $tag value
3537 * @param &$tag string Current HTML tag name we are looking at
3538 * @param $tagType int (0-open tag, 1-close tag)
3539 * @param $lastCh string Character before the '>' that ended this tag
3540 * @param &$openTags array Open tag stack (not accounting for $tag)
3542 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3543 $tag = ltrim( $tag );
3545 if ( $tagType == 0 && $lastCh != '/' ) {
3546 $openTags[] = $tag; // tag opened (didn't close itself)
3547 } elseif ( $tagType == 1 ) {
3548 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3549 array_pop( $openTags ); // tag closed
3557 * Grammatical transformations, needed for inflected languages
3558 * Invoked by putting {{grammar:case|word}} in a message
3560 * @param $word string
3561 * @param $case string
3564 function convertGrammar( $word, $case ) {
3565 global $wgGrammarForms;
3566 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3567 return $wgGrammarForms[$this->getCode()][$case][$word];
3572 * Get the grammar forms for the content language
3573 * @return array of grammar forms
3576 function getGrammarForms() {
3577 global $wgGrammarForms;
3578 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3579 return $wgGrammarForms[$this->getCode()];
3584 * Provides an alternative text depending on specified gender.
3585 * Usage {{gender:username|masculine|feminine|neutral}}.
3586 * username is optional, in which case the gender of current user is used,
3587 * but only in (some) interface messages; otherwise default gender is used.
3589 * If no forms are given, an empty string is returned. If only one form is
3590 * given, it will be returned unconditionally. These details are implied by
3591 * the caller and cannot be overridden in subclasses.
3593 * If more than one form is given, the default is to use the neutral one
3594 * if it is specified, and to use the masculine one otherwise. These
3595 * details can be overridden in subclasses.
3597 * @param $gender string
3598 * @param $forms array
3602 function gender( $gender, $forms ) {
3603 if ( !count( $forms ) ) {
3606 $forms = $this->preConvertPlural( $forms, 2 );
3607 if ( $gender === 'male' ) {
3610 if ( $gender === 'female' ) {
3613 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3617 * Plural form transformations, needed for some languages.
3618 * For example, there are 3 form of plural in Russian and Polish,
3619 * depending on "count mod 10". See [[w:Plural]]
3620 * For English it is pretty simple.
3622 * Invoked by putting {{plural:count|wordform1|wordform2}}
3623 * or {{plural:count|wordform1|wordform2|wordform3}}
3625 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3627 * @param $count Integer: non-localized number
3628 * @param $forms Array: different plural forms
3629 * @return string Correct form of plural for $count in this language
3631 function convertPlural( $count, $forms ) {
3632 // Handle explicit n=pluralform cases
3633 foreach ( $forms as $index => $form ) {
3634 if ( preg_match( '/^\d+=/i', $form ) ) {
3635 $pos = strpos( $form, '=' );
3636 if ( substr( $form, 0, $pos ) === (string)$count ) {
3637 return substr( $form, $pos +
1 );
3639 unset( $forms[$index] );
3643 $forms = array_values( $forms );
3644 if ( !count( $forms ) ) {
3648 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3649 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3650 return $forms[$pluralForm];
3654 * Checks that convertPlural was given an array and pads it to requested
3655 * amount of forms by copying the last one.
3657 * @param $count Integer: How many forms should there be at least
3658 * @param $forms Array of forms given to convertPlural
3659 * @return array Padded array of forms or an exception if not an array
3661 protected function preConvertPlural( /* Array */ $forms, $count ) {
3662 while ( count( $forms ) < $count ) {
3663 $forms[] = $forms[count( $forms ) - 1];
3669 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3670 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3671 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3672 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3675 * @param $str String: the validated block duration in English
3676 * @return string Somehow translated block duration
3677 * @see LanguageFi.php for example implementation
3679 function translateBlockExpiry( $str ) {
3680 $duration = SpecialBlock
::getSuggestedDurations( $this );
3681 foreach ( $duration as $show => $value ) {
3682 if ( strcmp( $str, $value ) == 0 ) {
3683 return htmlspecialchars( trim( $show ) );
3687 // Since usually only infinite or indefinite is only on list, so try
3688 // equivalents if still here.
3689 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3690 if ( in_array( $str, $indefs ) ) {
3691 foreach ( $indefs as $val ) {
3692 $show = array_search( $val, $duration, true );
3693 if ( $show !== false ) {
3694 return htmlspecialchars( trim( $show ) );
3699 // If all else fails, return a standard duration or timestamp description.
3700 $time = strtotime( $str, 0 );
3701 if ( $time === false ) { // Unknown format. Return it as-is in case.
3703 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3704 // $time is relative to 0 so it's a duration length.
3705 return $this->formatDuration( $time );
3706 } else { // It's an absolute timestamp.
3707 if ( $time === 0 ) {
3708 // wfTimestamp() handles 0 as current time instead of epoch.
3709 return $this->timeanddate( '19700101000000' );
3711 return $this->timeanddate( $time );
3717 * languages like Chinese need to be segmented in order for the diff
3720 * @param $text String
3723 public function segmentForDiff( $text ) {
3728 * and unsegment to show the result
3730 * @param $text String
3733 public function unsegmentForDiff( $text ) {
3738 * Return the LanguageConverter used in the Language
3741 * @return LanguageConverter
3743 public function getConverter() {
3744 return $this->mConverter
;
3748 * convert text to all supported variants
3750 * @param $text string
3753 public function autoConvertToAllVariants( $text ) {
3754 return $this->mConverter
->autoConvertToAllVariants( $text );
3758 * convert text to different variants of a language.
3760 * @param $text string
3763 public function convert( $text ) {
3764 return $this->mConverter
->convert( $text );
3768 * Convert a Title object to a string in the preferred variant
3770 * @param $title Title
3773 public function convertTitle( $title ) {
3774 return $this->mConverter
->convertTitle( $title );
3778 * Convert a namespace index to a string in the preferred variant
3783 public function convertNamespace( $ns ) {
3784 return $this->mConverter
->convertNamespace( $ns );
3788 * Check if this is a language with variants
3792 public function hasVariants() {
3793 return count( $this->getVariants() ) > 1;
3797 * Check if the language has the specific variant
3800 * @param $variant string
3803 public function hasVariant( $variant ) {
3804 return (bool)$this->mConverter
->validateVariant( $variant );
3808 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3810 * @param $text string
3813 public function armourMath( $text ) {
3814 return $this->mConverter
->armourMath( $text );
3818 * Perform output conversion on a string, and encode for safe HTML output.
3819 * @param $text String text to be converted
3820 * @param $isTitle Bool whether this conversion is for the article title
3822 * @todo this should get integrated somewhere sane
3824 public function convertHtml( $text, $isTitle = false ) {
3825 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3829 * @param $key string
3832 public function convertCategoryKey( $key ) {
3833 return $this->mConverter
->convertCategoryKey( $key );
3837 * Get the list of variants supported by this language
3838 * see sample implementation in LanguageZh.php
3840 * @return array an array of language codes
3842 public function getVariants() {
3843 return $this->mConverter
->getVariants();
3849 public function getPreferredVariant() {
3850 return $this->mConverter
->getPreferredVariant();
3856 public function getDefaultVariant() {
3857 return $this->mConverter
->getDefaultVariant();
3863 public function getURLVariant() {
3864 return $this->mConverter
->getURLVariant();
3868 * If a language supports multiple variants, it is
3869 * possible that non-existing link in one variant
3870 * actually exists in another variant. this function
3871 * tries to find it. See e.g. LanguageZh.php
3873 * @param $link String: the name of the link
3874 * @param $nt Mixed: the title object of the link
3875 * @param $ignoreOtherCond Boolean: to disable other conditions when
3876 * we need to transclude a template or update a category's link
3877 * @return null the input parameters may be modified upon return
3879 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3880 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3884 * If a language supports multiple variants, converts text
3885 * into an array of all possible variants of the text:
3886 * 'variant' => text in that variant
3888 * @deprecated since 1.17 Use autoConvertToAllVariants()
3890 * @param $text string
3894 public function convertLinkToAllVariants( $text ) {
3895 return $this->mConverter
->convertLinkToAllVariants( $text );
3899 * returns language specific options used by User::getPageRenderHash()
3900 * for example, the preferred language variant
3904 function getExtraHashOptions() {
3905 return $this->mConverter
->getExtraHashOptions();
3909 * For languages that support multiple variants, the title of an
3910 * article may be displayed differently in different variants. this
3911 * function returns the apporiate title defined in the body of the article.
3915 public function getParsedTitle() {
3916 return $this->mConverter
->getParsedTitle();
3920 * Prepare external link text for conversion. When the text is
3921 * a URL, it shouldn't be converted, and it'll be wrapped in
3922 * the "raw" tag (-{R| }-) to prevent conversion.
3924 * This function is called "markNoConversion" for historical
3927 * @param $text String: text to be used for external link
3928 * @param $noParse bool: wrap it without confirming it's a real URL first
3929 * @return string the tagged text
3931 public function markNoConversion( $text, $noParse = false ) {
3932 // Excluding protocal-relative URLs may avoid many false positives.
3933 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3934 return $this->mConverter
->markNoConversion( $text );
3941 * A regular expression to match legal word-trailing characters
3942 * which should be merged onto a link of the form [[foo]]bar.
3946 public function linkTrail() {
3947 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3953 function getLangObj() {
3958 * Get the "parent" language which has a converter to convert a "compatible" language
3959 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
3961 * @return Language|null
3964 public function getParentLanguage() {
3965 if ( $this->mParentLanguage
!== false ) {
3966 return $this->mParentLanguage
;
3969 $pieces = explode( '-', $this->getCode() );
3971 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
3972 $this->mParentLanguage
= null;
3975 $lang = Language
::factory( $code );
3976 if ( !$lang->hasVariant( $this->getCode() ) ) {
3977 $this->mParentLanguage
= null;
3981 $this->mParentLanguage
= $lang;
3986 * Get the RFC 3066 code for this language object
3988 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3989 * htmlspecialchars() or similar
3993 public function getCode() {
3994 return $this->mCode
;
3998 * Get the code in Bcp47 format which we can use
3999 * inside of html lang="" tags.
4001 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4002 * htmlspecialchars() or similar.
4007 public function getHtmlCode() {
4008 if ( is_null( $this->mHtmlCode
) ) {
4009 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4011 return $this->mHtmlCode
;
4015 * @param $code string
4017 public function setCode( $code ) {
4018 $this->mCode
= $code;
4019 // Ensure we don't leave incorrect cached data lying around
4020 $this->mHtmlCode
= null;
4021 $this->mParentLanguage
= false;
4025 * Get the name of a file for a certain language code
4026 * @param $prefix string Prepend this to the filename
4027 * @param $code string Language code
4028 * @param $suffix string Append this to the filename
4029 * @throws MWException
4030 * @return string $prefix . $mangledCode . $suffix
4032 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4033 // Protect against path traversal
4034 if ( !Language
::isValidCode( $code )
4035 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
4037 throw new MWException( "Invalid language code \"$code\"" );
4040 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4044 * Get the language code from a file name. Inverse of getFileName()
4045 * @param $filename string $prefix . $languageCode . $suffix
4046 * @param $prefix string Prefix before the language code
4047 * @param $suffix string Suffix after the language code
4048 * @return string Language code, or false if $prefix or $suffix isn't found
4050 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4052 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4053 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4054 if ( !count( $m ) ) {
4057 return str_replace( '_', '-', strtolower( $m[1] ) );
4061 * @param $code string
4064 public static function getMessagesFileName( $code ) {
4066 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4067 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4072 * @param $code string
4075 public static function getClassFileName( $code ) {
4077 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4081 * Get the first fallback for a given language.
4083 * @param $code string
4085 * @return bool|string
4087 public static function getFallbackFor( $code ) {
4088 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4091 $fallbacks = self
::getFallbacksFor( $code );
4092 $first = array_shift( $fallbacks );
4098 * Get the ordered list of fallback languages.
4101 * @param $code string Language code
4104 public static function getFallbacksFor( $code ) {
4105 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4108 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4109 $v = array_map( 'trim', explode( ',', $v ) );
4110 if ( $v[count( $v ) - 1] !== 'en' ) {
4118 * Get the ordered list of fallback languages, ending with the fallback
4119 * language chain for the site language.
4122 * @param string $code Language code
4123 * @return array array( fallbacks, site fallbacks )
4125 public static function getFallbacksIncludingSiteLanguage( $code ) {
4126 global $wgLanguageCode;
4128 // Usually, we will only store a tiny number of fallback chains, so we
4129 // keep them in static memory.
4130 $cacheKey = "{$code}-{$wgLanguageCode}";
4132 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4133 $fallbacks = self
::getFallbacksFor( $code );
4135 // Append the site's fallback chain, including the site language itself
4136 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4137 array_unshift( $siteFallbacks, $wgLanguageCode );
4139 // Eliminate any languages already included in the chain
4140 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4142 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4144 return self
::$fallbackLanguageCache[$cacheKey];
4148 * Get all messages for a given language
4149 * WARNING: this may take a long time. If you just need all message *keys*
4150 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4152 * @param $code string
4156 public static function getMessagesFor( $code ) {
4157 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4161 * Get a message for a given language
4163 * @param $key string
4164 * @param $code string
4168 public static function getMessageFor( $key, $code ) {
4169 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4173 * Get all message keys for a given language. This is a faster alternative to
4174 * array_keys( Language::getMessagesFor( $code ) )
4177 * @param $code string Language code
4178 * @return array of message keys (strings)
4180 public static function getMessageKeysFor( $code ) {
4181 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4188 function fixVariableInNamespace( $talk ) {
4189 if ( strpos( $talk, '$1' ) === false ) {
4193 global $wgMetaNamespace;
4194 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4196 # Allow grammar transformations
4197 # Allowing full message-style parsing would make simple requests
4198 # such as action=raw much more expensive than they need to be.
4199 # This will hopefully cover most cases.
4200 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4201 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4202 return str_replace( ' ', '_', $talk );
4209 function replaceGrammarInNamespace( $m ) {
4210 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4214 * @throws MWException
4217 static function getCaseMaps() {
4218 static $wikiUpperChars, $wikiLowerChars;
4219 if ( isset( $wikiUpperChars ) ) {
4220 return array( $wikiUpperChars, $wikiLowerChars );
4223 wfProfileIn( __METHOD__
);
4224 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4225 if ( $arr === false ) {
4226 throw new MWException(
4227 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4229 $wikiUpperChars = $arr['wikiUpperChars'];
4230 $wikiLowerChars = $arr['wikiLowerChars'];
4231 wfProfileOut( __METHOD__
);
4232 return array( $wikiUpperChars, $wikiLowerChars );
4236 * Decode an expiry (block, protection, etc) which has come from the DB
4238 * @todo FIXME: why are we returnings DBMS-dependent strings???
4240 * @param $expiry String: Database expiry String
4241 * @param $format Bool|Int true to process using language functions, or TS_ constant
4242 * to return the expiry in a given timestamp
4246 public function formatExpiry( $expiry, $format = true ) {
4248 if ( $infinity === null ) {
4249 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4252 if ( $expiry == '' ||
$expiry == $infinity ) {
4253 return $format === true
4254 ?
$this->getMessageFromDB( 'infiniteblock' )
4257 return $format === true
4258 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4259 : wfTimestamp( $format, $expiry );
4265 * @param $seconds int|float
4266 * @param $format Array Optional
4267 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4268 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4269 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4270 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4273 function formatTimePeriod( $seconds, $format = array() ) {
4274 if ( !is_array( $format ) ) {
4275 $format = array( 'avoid' => $format ); // For backwards compatibility
4277 if ( !isset( $format['avoid'] ) ) {
4278 $format['avoid'] = false;
4280 if ( !isset( $format['noabbrevs' ] ) ) {
4281 $format['noabbrevs'] = false;
4283 $secondsMsg = wfMessage(
4284 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4285 $minutesMsg = wfMessage(
4286 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4287 $hoursMsg = wfMessage(
4288 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4289 $daysMsg = wfMessage(
4290 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4292 if ( round( $seconds * 10 ) < 100 ) {
4293 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4294 $s = $secondsMsg->params( $s )->text();
4295 } elseif ( round( $seconds ) < 60 ) {
4296 $s = $this->formatNum( round( $seconds ) );
4297 $s = $secondsMsg->params( $s )->text();
4298 } elseif ( round( $seconds ) < 3600 ) {
4299 $minutes = floor( $seconds / 60 );
4300 $secondsPart = round( fmod( $seconds, 60 ) );
4301 if ( $secondsPart == 60 ) {
4305 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4307 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4308 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4309 $hours = floor( $seconds / 3600 );
4310 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4311 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4312 if ( $secondsPart == 60 ) {
4316 if ( $minutes == 60 ) {
4320 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4322 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4323 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4324 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4327 $days = floor( $seconds / 86400 );
4328 if ( $format['avoid'] === 'avoidminutes' ) {
4329 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4330 if ( $hours == 24 ) {
4334 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4336 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4337 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4338 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4339 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4340 if ( $minutes == 60 ) {
4344 if ( $hours == 24 ) {
4348 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4350 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4352 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4354 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4356 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4363 * Format a bitrate for output, using an appropriate
4364 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4366 * This use base 1000. For base 1024 use formatSize(), for another base
4367 * see formatComputingNumbers()
4372 function formatBitrate( $bps ) {
4373 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4377 * @param $size int Size of the unit
4378 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4379 * @param $messageKey string Message key to be uesd
4382 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4384 return str_replace( '$1', $this->formatNum( $size ),
4385 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4388 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4391 $maxIndex = count( $sizes ) - 1;
4392 while ( $size >= $boundary && $index < $maxIndex ) {
4397 // For small sizes no decimal places necessary
4400 // For MB and bigger two decimal places are smarter
4403 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4405 $size = round( $size, $round );
4406 $text = $this->getMessageFromDB( $msg );
4407 return str_replace( '$1', $this->formatNum( $size ), $text );
4411 * Format a size in bytes for output, using an appropriate
4412 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4414 * This method use base 1024. For base 1000 use formatBitrate(), for
4415 * another base see formatComputingNumbers()
4417 * @param $size int Size to format
4418 * @return string Plain text (not HTML)
4420 function formatSize( $size ) {
4421 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4425 * Make a list item, used by various special pages
4427 * @param $page String Page link
4428 * @param $details String Text between brackets
4429 * @param $oppositedm Boolean Add the direction mark opposite to your
4430 * language, to display text properly
4433 function specialList( $page, $details, $oppositedm = true ) {
4434 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4435 $this->getDirMark();
4436 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4437 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4438 return $page . $details;
4442 * Generate (prev x| next x) (20|50|100...) type links for paging
4444 * @param $title Title object to link
4445 * @param $offset Integer offset parameter
4446 * @param $limit Integer limit parameter
4447 * @param $query array|String optional URL query parameter string
4448 * @param $atend Bool optional param for specified if this is the last page
4451 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4452 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4454 # Make 'previous' link
4455 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4456 if ( $offset > 0 ) {
4457 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4458 $query, $prev, 'prevn-title', 'mw-prevlink' );
4460 $plink = htmlspecialchars( $prev );
4464 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4466 $nlink = htmlspecialchars( $next );
4468 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4469 $query, $next, 'prevn-title', 'mw-nextlink' );
4472 # Make links to set number of items per page
4473 $numLinks = array();
4474 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4475 $numLinks[] = $this->numLink( $title, $offset, $num,
4476 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4479 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4480 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4484 * Helper function for viewPrevNext() that generates links
4486 * @param $title Title object to link
4487 * @param $offset Integer offset parameter
4488 * @param $limit Integer limit parameter
4489 * @param $query Array extra query parameters
4490 * @param $link String text to use for the link; will be escaped
4491 * @param $tooltipMsg String name of the message to use as tooltip
4492 * @param $class String value of the "class" attribute of the link
4493 * @return String HTML fragment
4495 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4496 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4497 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4498 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4499 'title' => $tooltip, 'class' => $class ), $link );
4503 * Get the conversion rule title, if any.
4507 public function getConvRuleTitle() {
4508 return $this->mConverter
->getConvRuleTitle();
4512 * Get the compiled plural rules for the language
4514 * @return array Associative array with plural form, and plural rule as key-value pairs
4516 public function getCompiledPluralRules() {
4517 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4518 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4519 if ( !$pluralRules ) {
4520 foreach ( $fallbacks as $fallbackCode ) {
4521 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4522 if ( $pluralRules ) {
4527 return $pluralRules;
4531 * Get the plural rules for the language
4533 * @return array Associative array with plural form number and plural rule as key-value pairs
4535 public function getPluralRules() {
4536 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4537 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4538 if ( !$pluralRules ) {
4539 foreach ( $fallbacks as $fallbackCode ) {
4540 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4541 if ( $pluralRules ) {
4546 return $pluralRules;
4550 * Get the plural rule types for the language
4552 * @return array Associative array with plural form number and plural rule type as key-value pairs
4554 public function getPluralRuleTypes() {
4555 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4556 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4557 if ( !$pluralRuleTypes ) {
4558 foreach ( $fallbacks as $fallbackCode ) {
4559 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4560 if ( $pluralRuleTypes ) {
4565 return $pluralRuleTypes;
4569 * Find the index number of the plural rule appropriate for the given number
4570 * @return int The index number of the plural rule
4572 public function getPluralRuleIndexNumber( $number ) {
4573 $pluralRules = $this->getCompiledPluralRules();
4574 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4579 * Find the plural rule type appropriate for the given number
4580 * For example, if the language is set to Arabic, getPluralType(5) should
4583 * @return string The name of the plural rule type, e.g. one, two, few, many
4585 public function getPluralRuleType( $number ) {
4586 $index = $this->getPluralRuleIndexNumber( $number );
4587 $pluralRuleTypes = $this->getPluralRuleTypes();
4588 if ( isset( $pluralRuleTypes[$index] ) ) {
4589 return $pluralRuleTypes[$index];