3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once __DIR__
. '/Names.php';
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
51 function __construct( $langobj ) { $this->mLang
= $langobj; }
52 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
53 function convert( $t ) { return $t; }
54 function convertTo( $text, $variant ) { return $text; }
55 function convertTitle( $t ) { return $t->getPrefixedText(); }
56 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
57 function getVariants() { return array( $this->mLang
->getCode() ); }
58 function getPreferredVariant() { return $this->mLang
->getCode(); }
59 function getDefaultVariant() { return $this->mLang
->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
72 * Internationalisation code
78 * @var LanguageConverter
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 public $dateFormatStrings = array();
87 public $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
92 * ReplacementArray object caches
94 public $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
174 * 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 ( MWInit
::classExists( $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 ( MWInit
::classExists( $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 if ( $coreLanguageNames === null ) {
389 include MWInit
::compiledPath( 'languages/Names.php' );
392 if ( isset( $coreLanguageNames[$tag] )
393 || self
::fetchLanguageName( $tag, $tag ) !== ''
403 * @return String Name of the language class
405 public static function classFromCode( $code ) {
406 if ( $code == 'en' ) {
409 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
414 * Includes language class files
416 * @param $class string Name of the language class
418 public static function preloadLanguageClass( $class ) {
421 if ( $class === 'Language' ) {
425 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
426 include_once "$IP/languages/classes/$class.php";
431 * Get the LocalisationCache instance
433 * @return LocalisationCache
435 public static function getLocalisationCache() {
436 if ( is_null( self
::$dataCache ) ) {
437 global $wgLocalisationCacheConf;
438 $class = $wgLocalisationCacheConf['class'];
439 self
::$dataCache = new $class( $wgLocalisationCacheConf );
441 return self
::$dataCache;
444 function __construct() {
445 $this->mConverter
= new FakeConverter( $this );
446 // Set the code to the name of the descendant
447 if ( get_class( $this ) == 'Language' ) {
450 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
452 self
::getLocalisationCache();
456 * Reduce memory usage
458 function __destruct() {
459 foreach ( $this as $name => $value ) {
460 unset( $this->$name );
465 * Hook which will be called if this is the content language.
466 * Descendants can use this to register hook functions or modify globals
468 function initContLang() { }
471 * Same as getFallbacksFor for current language.
473 * @deprecated in 1.19
475 function getFallbackLanguageCode() {
476 wfDeprecated( __METHOD__
, '1.19' );
477 return self
::getFallbackFor( $this->mCode
);
484 function getFallbackLanguages() {
485 return self
::getFallbacksFor( $this->mCode
);
489 * Exports $wgBookstoreListEn
492 function getBookstoreList() {
493 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
497 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
498 * available in localised form, it will be included in English.
502 public function getNamespaces() {
503 if ( is_null( $this->namespaceNames
) ) {
504 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
506 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
507 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
509 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
511 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
512 if ( $wgMetaNamespaceTalk ) {
513 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
515 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
516 $this->namespaceNames
[NS_PROJECT_TALK
] =
517 $this->fixVariableInNamespace( $talk );
520 # Sometimes a language will be localised but not actually exist on this wiki.
521 foreach ( $this->namespaceNames
as $key => $text ) {
522 if ( !isset( $validNamespaces[$key] ) ) {
523 unset( $this->namespaceNames
[$key] );
527 # The above mixing may leave namespaces out of canonical order.
528 # Re-order by namespace ID number...
529 ksort( $this->namespaceNames
);
531 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
533 return $this->namespaceNames
;
537 * Arbitrarily set all of the namespace names at once. Mainly used for testing
538 * @param $namespaces Array of namespaces (id => name)
540 public function setNamespaces( array $namespaces ) {
541 $this->namespaceNames
= $namespaces;
542 $this->mNamespaceIds
= null;
546 * Resets all of the namespace caches. Mainly used for testing
548 public function resetNamespaces() {
549 $this->namespaceNames
= null;
550 $this->mNamespaceIds
= null;
551 $this->namespaceAliases
= null;
555 * A convenience function that returns the same thing as
556 * getNamespaces() except with the array values changed to ' '
557 * where it found '_', useful for producing output to be displayed
558 * e.g. in <select> forms.
562 function getFormattedNamespaces() {
563 $ns = $this->getNamespaces();
564 foreach ( $ns as $k => $v ) {
565 $ns[$k] = strtr( $v, '_', ' ' );
571 * Get a namespace value by key
573 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
574 * echo $mw_ns; // prints 'MediaWiki'
577 * @param $index Int: the array key of the namespace to return
578 * @return mixed, string if the namespace value exists, otherwise false
580 function getNsText( $index ) {
581 $ns = $this->getNamespaces();
582 return isset( $ns[$index] ) ?
$ns[$index] : false;
586 * A convenience function that returns the same thing as
587 * getNsText() except with '_' changed to ' ', useful for
591 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
592 * echo $mw_ns; // prints 'MediaWiki talk'
595 * @param int $index The array key of the namespace to return
596 * @return string Namespace name without underscores (empty string if namespace does not exist)
598 function getFormattedNsText( $index ) {
599 $ns = $this->getNsText( $index );
600 return strtr( $ns, '_', ' ' );
604 * Returns gender-dependent namespace alias if available.
605 * @param $index Int: namespace index
606 * @param $gender String: gender key (male, female... )
610 function getGenderNsText( $index, $gender ) {
611 global $wgExtraGenderNamespaces;
613 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
614 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
618 * Whether this language makes distinguishes genders for example in
623 function needsGenderDistinction() {
624 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
625 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
626 // $wgExtraGenderNamespaces overrides everything
628 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
629 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
630 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
633 // Check what is in i18n files
634 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
635 return count( $aliases ) > 0;
640 * Get a namespace key by value, case insensitive.
641 * Only matches namespace names for the current language, not the
642 * canonical ones defined in Namespace.php.
644 * @param $text String
645 * @return mixed An integer if $text is a valid value otherwise false
647 function getLocalNsIndex( $text ) {
648 $lctext = $this->lc( $text );
649 $ids = $this->getNamespaceIds();
650 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
656 function getNamespaceAliases() {
657 if ( is_null( $this->namespaceAliases
) ) {
658 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
662 foreach ( $aliases as $name => $index ) {
663 if ( $index === NS_PROJECT_TALK
) {
664 unset( $aliases[$name] );
665 $name = $this->fixVariableInNamespace( $name );
666 $aliases[$name] = $index;
671 global $wgExtraGenderNamespaces;
672 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
673 foreach ( $genders as $index => $forms ) {
674 foreach ( $forms as $alias ) {
675 $aliases[$alias] = $index;
679 $this->namespaceAliases
= $aliases;
681 return $this->namespaceAliases
;
687 function getNamespaceIds() {
688 if ( is_null( $this->mNamespaceIds
) ) {
689 global $wgNamespaceAliases;
690 # Put namespace names and aliases into a hashtable.
691 # If this is too slow, then we should arrange it so that it is done
692 # before caching. The catch is that at pre-cache time, the above
693 # class-specific fixup hasn't been done.
694 $this->mNamespaceIds
= array();
695 foreach ( $this->getNamespaces() as $index => $name ) {
696 $this->mNamespaceIds
[$this->lc( $name )] = $index;
698 foreach ( $this->getNamespaceAliases() as $name => $index ) {
699 $this->mNamespaceIds
[$this->lc( $name )] = $index;
701 if ( $wgNamespaceAliases ) {
702 foreach ( $wgNamespaceAliases as $name => $index ) {
703 $this->mNamespaceIds
[$this->lc( $name )] = $index;
707 return $this->mNamespaceIds
;
711 * Get a namespace key by value, case insensitive. Canonical namespace
712 * names override custom ones defined for the current language.
714 * @param $text String
715 * @return mixed An integer if $text is a valid value otherwise false
717 function getNsIndex( $text ) {
718 $lctext = $this->lc( $text );
719 $ns = MWNamespace
::getCanonicalIndex( $lctext );
720 if ( $ns !== null ) {
723 $ids = $this->getNamespaceIds();
724 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
728 * short names for language variants used for language conversion links.
730 * @param $code String
731 * @param $usemsg bool Use the "variantname-xyz" message if it exists
734 function getVariantname( $code, $usemsg = true ) {
735 $msg = "variantname-$code";
736 if ( $usemsg && wfMessage( $msg )->exists() ) {
737 return $this->getMessageFromDB( $msg );
739 $name = self
::fetchLanguageName( $code );
741 return $name; # if it's defined as a language name, show that
743 # otherwise, output the language code
749 * @param $name string
752 function specialPage( $name ) {
753 $aliases = $this->getSpecialPageAliases();
754 if ( isset( $aliases[$name][0] ) ) {
755 $name = $aliases[$name][0];
757 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
763 function getDatePreferences() {
764 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
770 function getDateFormats() {
771 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
775 * @return array|string
777 function getDefaultDateFormat() {
778 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
779 if ( $df === 'dmy or mdy' ) {
780 global $wgAmericanDates;
781 return $wgAmericanDates ?
'mdy' : 'dmy';
790 function getDatePreferenceMigrationMap() {
791 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
798 function getImageFile( $image ) {
799 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
805 function getExtraUserToggles() {
806 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
813 function getUserToggle( $tog ) {
814 return $this->getMessageFromDB( "tog-$tog" );
818 * Get native language names, indexed by code.
819 * Only those defined in MediaWiki, no other data like CLDR.
820 * If $customisedOnly is true, only returns codes with a messages file
822 * @param $customisedOnly bool
825 * @deprecated in 1.20, use fetchLanguageNames()
827 public static function getLanguageNames( $customisedOnly = false ) {
828 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
832 * Get translated language names. This is done on best effort and
833 * by default this is exactly the same as Language::getLanguageNames.
834 * The CLDR extension provides translated names.
835 * @param $code String Language code.
836 * @return Array language code => language name
838 * @deprecated in 1.20, use fetchLanguageNames()
840 public static function getTranslatedLanguageNames( $code ) {
841 return self
::fetchLanguageNames( $code, 'all' );
845 * Get an array of language names, indexed by code.
846 * @param $inLanguage null|string: Code of language in which to return the names
847 * Use null for autonyms (native names)
848 * @param $include string:
849 * 'all' all available languages
850 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
851 * 'mwfile' only if the language is in 'mw' *and* has a message file
852 * @return array: language code => language name
855 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
856 global $wgExtraLanguageNames;
857 static $coreLanguageNames;
859 if ( $coreLanguageNames === null ) {
860 include MWInit
::compiledPath( 'languages/Names.php' );
866 # TODO: also include when $inLanguage is null, when this code is more efficient
867 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
870 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
871 foreach ( $mwNames as $mwCode => $mwName ) {
872 # - Prefer own MediaWiki native name when not using the hook
873 # - For other names just add if not added through the hook
874 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
875 $names[$mwCode] = $mwName;
879 if ( $include === 'all' ) {
884 $coreCodes = array_keys( $mwNames );
885 foreach ( $coreCodes as $coreCode ) {
886 $returnMw[$coreCode] = $names[$coreCode];
889 if ( $include === 'mwfile' ) {
890 $namesMwFile = array();
891 # We do this using a foreach over the codes instead of a directory
892 # loop so that messages files in extensions will work correctly.
893 foreach ( $returnMw as $code => $value ) {
894 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
895 $namesMwFile[$code] = $names[$code];
900 # 'mw' option; default if it's not one of the other two options (all/mwfile)
905 * @param $code string: The code of the language for which to get the name
906 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
907 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
908 * @return string: Language name or empty
911 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
912 $array = self
::fetchLanguageNames( $inLanguage, $include );
913 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
917 * Get a message from the MediaWiki namespace.
919 * @param $msg String: message name
922 function getMessageFromDB( $msg ) {
923 return wfMessage( $msg )->inLanguage( $this )->text();
927 * Get the native language name of $code.
928 * Only if defined in MediaWiki, no other data like CLDR.
929 * @param $code string
931 * @deprecated in 1.20, use fetchLanguageName()
933 function getLanguageName( $code ) {
934 return self
::fetchLanguageName( $code );
941 function getMonthName( $key ) {
942 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
948 function getMonthNamesArray() {
949 $monthNames = array( '' );
950 for ( $i = 1; $i < 13; $i++
) {
951 $monthNames[] = $this->getMonthName( $i );
960 function getMonthNameGen( $key ) {
961 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
968 function getMonthAbbreviation( $key ) {
969 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
975 function getMonthAbbreviationsArray() {
976 $monthNames = array( '' );
977 for ( $i = 1; $i < 13; $i++
) {
978 $monthNames[] = $this->getMonthAbbreviation( $i );
987 function getWeekdayName( $key ) {
988 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
995 function getWeekdayAbbreviation( $key ) {
996 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1000 * @param $key string
1003 function getIranianCalendarMonthName( $key ) {
1004 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1008 * @param $key string
1011 function getHebrewCalendarMonthName( $key ) {
1012 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1016 * @param $key string
1019 function getHebrewCalendarMonthNameGen( $key ) {
1020 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1024 * @param $key string
1027 function getHijriCalendarMonthName( $key ) {
1028 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1032 * This is a workalike of PHP's date() function, but with better
1033 * internationalisation, a reduced set of format characters, and a better
1036 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1037 * the PHP manual for definitions. There are a number of extensions, which
1040 * xn Do not translate digits of the next numeric format character
1041 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1042 * xr Use roman numerals for the next numeric format character
1043 * xh Use hebrew numerals for the next numeric format character
1045 * xg Genitive month name
1047 * xij j (day number) in Iranian calendar
1048 * xiF F (month name) in Iranian calendar
1049 * xin n (month number) in Iranian calendar
1050 * xiy y (two digit year) in Iranian calendar
1051 * xiY Y (full year) in Iranian calendar
1053 * xjj j (day number) in Hebrew calendar
1054 * xjF F (month name) in Hebrew calendar
1055 * xjt t (days in month) in Hebrew calendar
1056 * xjx xg (genitive month name) in Hebrew calendar
1057 * xjn n (month number) in Hebrew calendar
1058 * xjY Y (full year) in Hebrew calendar
1060 * xmj j (day number) in Hijri calendar
1061 * xmF F (month name) in Hijri calendar
1062 * xmn n (month number) in Hijri calendar
1063 * xmY Y (full year) in Hijri calendar
1065 * xkY Y (full year) in Thai solar calendar. Months and days are
1066 * identical to the Gregorian calendar
1067 * xoY Y (full year) in Minguo calendar or Juche year.
1068 * Months and days are identical to the
1069 * Gregorian calendar
1070 * xtY Y (full year) in Japanese nengo. Months and days are
1071 * identical to the Gregorian calendar
1073 * Characters enclosed in double quotes will be considered literal (with
1074 * the quotes themselves removed). Unmatched quotes will be considered
1075 * literal quotes. Example:
1077 * "The month is" F => The month is January
1080 * Backslash escaping is also supported.
1082 * Input timestamp is assumed to be pre-normalized to the desired local
1083 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1084 * $ts is UTC if $zone is not given.
1086 * @param $format String
1087 * @param $ts String: 14-character timestamp
1090 * @param $zone DateTimeZone: Timezone of $ts
1091 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1093 * @throws MWException
1096 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1101 $dateTimeObj = false;
1110 if ( strlen( $ts ) !== 14 ) {
1111 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1114 if ( !ctype_digit( $ts ) ) {
1115 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1118 for ( $p = 0; $p < strlen( $format ); $p++
) {
1120 $code = $format[$p];
1121 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1122 $code .= $format[++
$p];
1125 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1126 $code .= $format[++
$p];
1137 $rawToggle = !$rawToggle;
1146 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1150 $hebrew = self
::tsToHebrew( $ts );
1152 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1155 $num = substr( $ts, 6, 2 );
1158 if ( !$dateTimeObj ) {
1159 $dateTimeObj = DateTime
::createFromFormat(
1160 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1163 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1166 $num = intval( substr( $ts, 6, 2 ) );
1170 $iranian = self
::tsToIranian( $ts );
1176 $hijri = self
::tsToHijri( $ts );
1182 $hebrew = self
::tsToHebrew( $ts );
1187 if ( !$dateTimeObj ) {
1188 $dateTimeObj = DateTime
::createFromFormat(
1189 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1192 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1195 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1199 $iranian = self
::tsToIranian( $ts );
1201 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1205 $hijri = self
::tsToHijri( $ts );
1207 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1211 $hebrew = self
::tsToHebrew( $ts );
1213 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1216 $num = substr( $ts, 4, 2 );
1219 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1222 $num = intval( substr( $ts, 4, 2 ) );
1226 $iranian = self
::tsToIranian( $ts );
1232 $hijri = self
::tsToHijri ( $ts );
1238 $hebrew = self
::tsToHebrew( $ts );
1244 $hebrew = self
::tsToHebrew( $ts );
1249 $num = substr( $ts, 0, 4 );
1253 $iranian = self
::tsToIranian( $ts );
1259 $hijri = self
::tsToHijri( $ts );
1265 $hebrew = self
::tsToHebrew( $ts );
1271 $thai = self
::tsToYear( $ts, 'thai' );
1277 $minguo = self
::tsToYear( $ts, 'minguo' );
1283 $tenno = self
::tsToYear( $ts, 'tenno' );
1288 $num = substr( $ts, 2, 2 );
1292 $iranian = self
::tsToIranian( $ts );
1294 $num = substr( $iranian[0], -2 );
1297 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1300 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1303 $h = substr( $ts, 8, 2 );
1304 $num = $h %
12 ?
$h %
12 : 12;
1307 $num = intval( substr( $ts, 8, 2 ) );
1310 $h = substr( $ts, 8, 2 );
1311 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1314 $num = substr( $ts, 8, 2 );
1317 $num = substr( $ts, 10, 2 );
1320 $num = substr( $ts, 12, 2 );
1328 // Pass through string from $dateTimeObj->format()
1329 if ( !$dateTimeObj ) {
1330 $dateTimeObj = DateTime
::createFromFormat(
1331 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1334 $s .= $dateTimeObj->format( $code );
1346 // Pass through number from $dateTimeObj->format()
1347 if ( !$dateTimeObj ) {
1348 $dateTimeObj = DateTime
::createFromFormat(
1349 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1352 $num = $dateTimeObj->format( $code );
1355 # Backslash escaping
1356 if ( $p < strlen( $format ) - 1 ) {
1357 $s .= $format[++
$p];
1364 if ( $p < strlen( $format ) - 1 ) {
1365 $endQuote = strpos( $format, '"', $p +
1 );
1366 if ( $endQuote === false ) {
1367 # No terminating quote, assume literal "
1370 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1374 # Quote at end of string, assume literal "
1381 if ( $num !== false ) {
1382 if ( $rawToggle ||
$raw ) {
1385 } elseif ( $roman ) {
1386 $s .= Language
::romanNumeral( $num );
1388 } elseif ( $hebrewNum ) {
1389 $s .= self
::hebrewNumeral( $num );
1392 $s .= $this->formatNum( $num, true );
1399 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1400 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1403 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1404 * Gregorian dates to Iranian dates. Originally written in C, it
1405 * is released under the terms of GNU Lesser General Public
1406 * License. Conversion to PHP was performed by Niklas Laxström.
1408 * Link: http://www.farsiweb.info/jalali/jalali.c
1414 private static function tsToIranian( $ts ) {
1415 $gy = substr( $ts, 0, 4 ) -1600;
1416 $gm = substr( $ts, 4, 2 ) -1;
1417 $gd = substr( $ts, 6, 2 ) -1;
1419 # Days passed from the beginning (including leap years)
1421 +
floor( ( $gy +
3 ) / 4 )
1422 - floor( ( $gy +
99 ) / 100 )
1423 +
floor( ( $gy +
399 ) / 400 );
1425 // Add days of the past months of this year
1426 for ( $i = 0; $i < $gm; $i++
) {
1427 $gDayNo +
= self
::$GREG_DAYS[$i];
1431 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1435 // Days passed in current month
1436 $gDayNo +
= (int)$gd;
1438 $jDayNo = $gDayNo - 79;
1440 $jNp = floor( $jDayNo / 12053 );
1443 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1446 if ( $jDayNo >= 366 ) {
1447 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1448 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1451 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1452 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1458 return array( $jy, $jm, $jd );
1462 * Converting Gregorian dates to Hijri dates.
1464 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1466 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1472 private static function tsToHijri( $ts ) {
1473 $year = substr( $ts, 0, 4 );
1474 $month = substr( $ts, 4, 2 );
1475 $day = substr( $ts, 6, 2 );
1483 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1484 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1487 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1488 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1489 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1492 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1493 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1496 $zl = $zjd -1948440 +
10632;
1497 $zn = (int)( ( $zl - 1 ) / 10631 );
1498 $zl = $zl - 10631 * $zn +
354;
1499 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1500 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1501 $zm = (int)( ( 24 * $zl ) / 709 );
1502 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1503 $zy = 30 * $zn +
$zj - 30;
1505 return array( $zy, $zm, $zd );
1509 * Converting Gregorian dates to Hebrew dates.
1511 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1512 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1513 * to translate the relevant functions into PHP and release them under
1516 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1517 * and Adar II is 14. In a non-leap year, Adar is 6.
1523 private static function tsToHebrew( $ts ) {
1525 $year = substr( $ts, 0, 4 );
1526 $month = substr( $ts, 4, 2 );
1527 $day = substr( $ts, 6, 2 );
1529 # Calculate Hebrew year
1530 $hebrewYear = $year +
3760;
1532 # Month number when September = 1, August = 12
1534 if ( $month > 12 ) {
1541 # Calculate day of year from 1 September
1543 for ( $i = 1; $i < $month; $i++
) {
1547 # Check if the year is leap
1548 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1551 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1558 # Calculate the start of the Hebrew year
1559 $start = self
::hebrewYearStart( $hebrewYear );
1561 # Calculate next year's start
1562 if ( $dayOfYear <= $start ) {
1563 # Day is before the start of the year - it is the previous year
1565 $nextStart = $start;
1569 # Add days since previous year's 1 September
1571 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1575 # Start of the new (previous) year
1576 $start = self
::hebrewYearStart( $hebrewYear );
1579 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1582 # Calculate Hebrew day of year
1583 $hebrewDayOfYear = $dayOfYear - $start;
1585 # Difference between year's days
1586 $diff = $nextStart - $start;
1587 # Add 12 (or 13 for leap years) days to ignore the difference between
1588 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1589 # difference is only about the year type
1590 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1596 # Check the year pattern, and is leap year
1597 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1598 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1599 # and non-leap years
1600 $yearPattern = $diff %
30;
1601 # Check if leap year
1602 $isLeap = $diff >= 30;
1604 # Calculate day in the month from number of day in the Hebrew year
1605 # Don't check Adar - if the day is not in Adar, we will stop before;
1606 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1607 $hebrewDay = $hebrewDayOfYear;
1610 while ( $hebrewMonth <= 12 ) {
1611 # Calculate days in this month
1612 if ( $isLeap && $hebrewMonth == 6 ) {
1613 # Adar in a leap year
1615 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1617 if ( $hebrewDay <= $days ) {
1621 # Subtract the days of Adar I
1622 $hebrewDay -= $days;
1625 if ( $hebrewDay <= $days ) {
1631 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1632 # Cheshvan in a complete year (otherwise as the rule below)
1634 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1635 # Kislev in an incomplete year (otherwise as the rule below)
1638 # Odd months have 30 days, even have 29
1639 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1641 if ( $hebrewDay <= $days ) {
1642 # In the current month
1645 # Subtract the days of the current month
1646 $hebrewDay -= $days;
1647 # Try in the next month
1652 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1656 * This calculates the Hebrew year start, as days since 1 September.
1657 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1658 * Used for Hebrew date.
1664 private static function hebrewYearStart( $year ) {
1665 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1666 $b = intval( ( $year - 1 ) %
4 );
1667 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1671 $Mar = intval( $m );
1677 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1678 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1680 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1682 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1686 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1691 * Algorithm to convert Gregorian dates to Thai solar dates,
1692 * Minguo dates or Minguo dates.
1694 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1695 * http://en.wikipedia.org/wiki/Minguo_calendar
1696 * http://en.wikipedia.org/wiki/Japanese_era_name
1698 * @param $ts String: 14-character timestamp
1699 * @param $cName String: calender name
1700 * @return Array: converted year, month, day
1702 private static function tsToYear( $ts, $cName ) {
1703 $gy = substr( $ts, 0, 4 );
1704 $gm = substr( $ts, 4, 2 );
1705 $gd = substr( $ts, 6, 2 );
1707 if ( !strcmp( $cName, 'thai' ) ) {
1709 # Add 543 years to the Gregorian calendar
1710 # Months and days are identical
1711 $gy_offset = $gy +
543;
1712 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1714 # Deduct 1911 years from the Gregorian calendar
1715 # Months and days are identical
1716 $gy_offset = $gy - 1911;
1717 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1718 # Nengō dates up to Meiji period
1719 # Deduct years from the Gregorian calendar
1720 # depending on the nengo periods
1721 # Months and days are identical
1722 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1724 $gy_gannen = $gy - 1868 +
1;
1725 $gy_offset = $gy_gannen;
1726 if ( $gy_gannen == 1 ) {
1729 $gy_offset = '明治' . $gy_offset;
1731 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1732 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1733 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1734 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1735 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1739 $gy_gannen = $gy - 1912 +
1;
1740 $gy_offset = $gy_gannen;
1741 if ( $gy_gannen == 1 ) {
1744 $gy_offset = '大正' . $gy_offset;
1746 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1747 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1748 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1752 $gy_gannen = $gy - 1926 +
1;
1753 $gy_offset = $gy_gannen;
1754 if ( $gy_gannen == 1 ) {
1757 $gy_offset = '昭和' . $gy_offset;
1760 $gy_gannen = $gy - 1989 +
1;
1761 $gy_offset = $gy_gannen;
1762 if ( $gy_gannen == 1 ) {
1765 $gy_offset = '平成' . $gy_offset;
1771 return array( $gy_offset, $gm, $gd );
1775 * Roman number formatting up to 10000
1781 static function romanNumeral( $num ) {
1782 static $table = array(
1783 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1784 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1785 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1786 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1789 $num = intval( $num );
1790 if ( $num > 10000 ||
$num <= 0 ) {
1795 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1796 if ( $num >= $pow10 ) {
1797 $s .= $table[$i][(int)floor( $num / $pow10 )];
1799 $num = $num %
$pow10;
1805 * Hebrew Gematria number formatting up to 9999
1811 static function hebrewNumeral( $num ) {
1812 static $table = array(
1813 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1814 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1815 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1816 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1819 $num = intval( $num );
1820 if ( $num > 9999 ||
$num <= 0 ) {
1825 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1826 if ( $num >= $pow10 ) {
1827 if ( $num == 15 ||
$num == 16 ) {
1828 $s .= $table[0][9] . $table[0][$num - 9];
1831 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1832 if ( $pow10 == 1000 ) {
1837 $num = $num %
$pow10;
1839 if ( strlen( $s ) == 2 ) {
1842 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1843 $str .= substr( $s, strlen( $s ) - 2, 2 );
1845 $start = substr( $str, 0, strlen( $str ) - 2 );
1846 $end = substr( $str, strlen( $str ) - 2 );
1849 $str = $start . 'ך';
1852 $str = $start . 'ם';
1855 $str = $start . 'ן';
1858 $str = $start . 'ף';
1861 $str = $start . 'ץ';
1868 * Used by date() and time() to adjust the time output.
1870 * @param $ts Int the time in date('YmdHis') format
1871 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1872 * get user timecorrection setting)
1875 function userAdjust( $ts, $tz = false ) {
1876 global $wgUser, $wgLocalTZoffset;
1878 if ( $tz === false ) {
1879 $tz = $wgUser->getOption( 'timecorrection' );
1882 $data = explode( '|', $tz, 3 );
1884 if ( $data[0] == 'ZoneInfo' ) {
1885 wfSuppressWarnings();
1886 $userTZ = timezone_open( $data[2] );
1887 wfRestoreWarnings();
1888 if ( $userTZ !== false ) {
1889 $date = date_create( $ts, timezone_open( 'UTC' ) );
1890 date_timezone_set( $date, $userTZ );
1891 $date = date_format( $date, 'YmdHis' );
1894 # Unrecognized timezone, default to 'Offset' with the stored offset.
1895 $data[0] = 'Offset';
1899 if ( $data[0] == 'System' ||
$tz == '' ) {
1900 # Global offset in minutes.
1901 if ( isset( $wgLocalTZoffset ) ) {
1902 $minDiff = $wgLocalTZoffset;
1904 } elseif ( $data[0] == 'Offset' ) {
1905 $minDiff = intval( $data[1] );
1907 $data = explode( ':', $tz );
1908 if ( count( $data ) == 2 ) {
1909 $data[0] = intval( $data[0] );
1910 $data[1] = intval( $data[1] );
1911 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1912 if ( $data[0] < 0 ) {
1913 $minDiff = -$minDiff;
1916 $minDiff = intval( $data[0] ) * 60;
1920 # No difference ? Return time unchanged
1921 if ( 0 == $minDiff ) {
1925 wfSuppressWarnings(); // E_STRICT system time bitching
1926 # Generate an adjusted date; take advantage of the fact that mktime
1927 # will normalize out-of-range values so we don't have to split $minDiff
1928 # into hours and minutes.
1930 (int)substr( $ts, 8, 2 ) ), # Hours
1931 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1932 (int)substr( $ts, 12, 2 ), # Seconds
1933 (int)substr( $ts, 4, 2 ), # Month
1934 (int)substr( $ts, 6, 2 ), # Day
1935 (int)substr( $ts, 0, 4 ) ); # Year
1937 $date = date( 'YmdHis', $t );
1938 wfRestoreWarnings();
1944 * This is meant to be used by time(), date(), and timeanddate() to get
1945 * the date preference they're supposed to use, it should be used in
1949 * function timeanddate([...], $format = true) {
1950 * $datePreference = $this->dateFormat($format);
1955 * @param $usePrefs Mixed: if true, the user's preference is used
1956 * if false, the site/language default is used
1957 * if int/string, assumed to be a format.
1960 function dateFormat( $usePrefs = true ) {
1963 if ( is_bool( $usePrefs ) ) {
1965 $datePreference = $wgUser->getDatePreference();
1967 $datePreference = (string)User
::getDefaultOption( 'date' );
1970 $datePreference = (string)$usePrefs;
1974 if ( $datePreference == '' ) {
1978 return $datePreference;
1982 * Get a format string for a given type and preference
1983 * @param $type string May be date, time or both
1984 * @param $pref string The format name as it appears in Messages*.php
1986 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1990 function getDateFormatString( $type, $pref ) {
1991 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1992 if ( $pref == 'default' ) {
1993 $pref = $this->getDefaultDateFormat();
1994 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1996 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1998 if ( $type === 'pretty' && $df === null ) {
1999 $df = $this->getDateFormatString( 'date', $pref );
2002 if ( $df === null ) {
2003 $pref = $this->getDefaultDateFormat();
2004 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2007 $this->dateFormatStrings
[$type][$pref] = $df;
2009 return $this->dateFormatStrings
[$type][$pref];
2013 * @param $ts Mixed: the time format which needs to be turned into a
2014 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2015 * @param $adj Bool: whether to adjust the time output according to the
2016 * user configured offset ($timecorrection)
2017 * @param $format Mixed: true to use user's date format preference
2018 * @param $timecorrection String|bool the time offset as returned by
2019 * validateTimeZone() in Special:Preferences
2022 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2023 $ts = wfTimestamp( TS_MW
, $ts );
2025 $ts = $this->userAdjust( $ts, $timecorrection );
2027 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2028 return $this->sprintfDate( $df, $ts );
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 time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2042 $ts = wfTimestamp( TS_MW
, $ts );
2044 $ts = $this->userAdjust( $ts, $timecorrection );
2046 $df = $this->getDateFormatString( 'time', $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: what format to return, if it's false output the
2056 * default one (default true)
2057 * @param $timecorrection String|bool the time offset as returned by
2058 * validateTimeZone() in Special:Preferences
2061 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2062 $ts = wfTimestamp( TS_MW
, $ts );
2064 $ts = $this->userAdjust( $ts, $timecorrection );
2066 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2067 return $this->sprintfDate( $df, $ts );
2071 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2075 * @param integer $seconds The amount of seconds.
2076 * @param array $chosenIntervals The intervals to enable.
2080 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2081 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2083 $segments = array();
2085 foreach ( $intervals as $intervalName => $intervalValue ) {
2086 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2087 $segments[] = $message->inLanguage( $this )->escaped();
2090 return $this->listToText( $segments );
2094 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2095 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2099 * @param integer $seconds The amount of seconds.
2100 * @param array $chosenIntervals The intervals to enable.
2104 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2105 if ( empty( $chosenIntervals ) ) {
2106 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2109 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2110 $sortedNames = array_keys( $intervals );
2111 $smallestInterval = array_pop( $sortedNames );
2113 $segments = array();
2115 foreach ( $intervals as $name => $length ) {
2116 $value = floor( $seconds / $length );
2118 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2119 $seconds -= $value * $length;
2120 $segments[$name] = $value;
2128 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2130 * @param $type String: can be 'date', 'time' or 'both'
2131 * @param $ts Mixed: the time format which needs to be turned into a
2132 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2133 * @param $user User object used to get preferences for timezone and format
2134 * @param $options Array, can contain the following keys:
2135 * - 'timecorrection': time correction, can have the following values:
2136 * - true: use user's preference
2137 * - false: don't use time correction
2138 * - integer: value of time correction in minutes
2139 * - 'format': format to use, can have the following values:
2140 * - true: use user's preference
2141 * - false: use default preference
2142 * - string: format to use
2146 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2147 $ts = wfTimestamp( TS_MW
, $ts );
2148 $options +
= array( 'timecorrection' => true, 'format' => true );
2149 if ( $options['timecorrection'] !== false ) {
2150 if ( $options['timecorrection'] === true ) {
2151 $offset = $user->getOption( 'timecorrection' );
2153 $offset = $options['timecorrection'];
2155 $ts = $this->userAdjust( $ts, $offset );
2157 if ( $options['format'] === true ) {
2158 $format = $user->getDatePreference();
2160 $format = $options['format'];
2162 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2163 return $this->sprintfDate( $df, $ts );
2167 * Get the formatted date for the given timestamp and formatted for
2170 * @param $ts Mixed: the time format which needs to be turned into a
2171 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2172 * @param $user User object used to get preferences for timezone and format
2173 * @param $options Array, can contain the following keys:
2174 * - 'timecorrection': time correction, can have the following values:
2175 * - true: use user's preference
2176 * - false: don't use time correction
2177 * - integer: value of time correction in minutes
2178 * - 'format': format to use, can have the following values:
2179 * - true: use user's preference
2180 * - false: use default preference
2181 * - string: format to use
2185 public function userDate( $ts, User
$user, array $options = array() ) {
2186 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2190 * Get the formatted time for the given timestamp and formatted for
2193 * @param $ts Mixed: the time format which needs to be turned into a
2194 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2195 * @param $user User object used to get preferences for timezone and format
2196 * @param $options Array, can contain the following keys:
2197 * - 'timecorrection': time correction, can have the following values:
2198 * - true: use user's preference
2199 * - false: don't use time correction
2200 * - integer: value of time correction in minutes
2201 * - 'format': format to use, can have the following values:
2202 * - true: use user's preference
2203 * - false: use default preference
2204 * - string: format to use
2208 public function userTime( $ts, User
$user, array $options = array() ) {
2209 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2213 * Get the formatted date and time for the given timestamp and formatted for
2216 * @param $ts Mixed: the time format which needs to be turned into a
2217 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2218 * @param $user User object used to get preferences for timezone and format
2219 * @param $options Array, can contain the following keys:
2220 * - 'timecorrection': time correction, can have the following values:
2221 * - true: use user's preference
2222 * - false: don't use time correction
2223 * - integer: value of time correction in minutes
2224 * - 'format': format to use, can have the following values:
2225 * - true: use user's preference
2226 * - false: use default preference
2227 * - string: format to use
2231 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2232 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2236 * Convert an MWTimestamp into a pretty human-readable timestamp using
2237 * the given user preferences and relative base time.
2239 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2240 * on your timestamp object, which will then call this function. Calling
2241 * this function directly will cause hooks to be skipped over.
2243 * @see MWTimestamp::getHumanTimestamp
2244 * @param MWTimestamp $ts Timestamp to prettify
2245 * @param MWTimestamp $relativeTo Base timestamp
2246 * @param User $user User preferences to use
2247 * @return string Human timestamp
2250 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2251 $diff = $ts->diff( $relativeTo );
2252 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) - (int)$relativeTo->timestamp
->format( 'w' ) );
2253 $days = $diff->days ?
: (int)$diffDay;
2254 if ( $diff->invert ||
$days > 5 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' ) ) {
2255 // Timestamps are in different years: use full timestamp
2256 // Also do full timestamp for future dates
2258 * @FIXME Add better handling of future timestamps.
2260 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2261 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2262 } elseif ( $days > 5 ) {
2263 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2264 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2265 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2266 } elseif ( $days > 1 ) {
2267 // Timestamp within the past week: show the day of the week and time
2268 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2269 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2270 $ts = wfMessage( "$weekday-at" )
2271 ->inLanguage( $this )
2272 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2274 } elseif ( $days == 1 ) {
2275 // Timestamp was yesterday: say 'yesterday' and the time.
2276 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2277 $ts = wfMessage( 'yesterday-at' )
2278 ->inLanguage( $this )
2279 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2281 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2282 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2283 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2284 $ts = wfMessage( 'today-at' )
2285 ->inLanguage( $this )
2286 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2289 // From here on in, the timestamp was soon enough ago so that we can simply say
2290 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2291 } elseif ( $diff->h
== 1 ) {
2292 // Less than 90 minutes, but more than an hour ago.
2293 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2294 } elseif ( $diff->i
>= 1 ) {
2295 // A few minutes ago.
2296 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2297 } elseif ( $diff->s
>= 30 ) {
2298 // Less than a minute, but more than 30 sec ago.
2299 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2301 // Less than 30 seconds ago.
2302 $ts = wfMessage( 'just-now' )->text();
2309 * @param $key string
2310 * @return array|null
2312 function getMessage( $key ) {
2313 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2319 function getAllMessages() {
2320 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2329 function iconv( $in, $out, $string ) {
2330 # This is a wrapper for iconv in all languages except esperanto,
2331 # which does some nasty x-conversions beforehand
2333 # Even with //IGNORE iconv can whine about illegal characters in
2334 # *input* string. We just ignore those too.
2335 # REF: http://bugs.php.net/bug.php?id=37166
2336 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2337 wfSuppressWarnings();
2338 $text = iconv( $in, $out . '//IGNORE', $string );
2339 wfRestoreWarnings();
2343 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2346 * @param $matches array
2347 * @return mixed|string
2349 function ucwordbreaksCallbackAscii( $matches ) {
2350 return $this->ucfirst( $matches[1] );
2354 * @param $matches array
2357 function ucwordbreaksCallbackMB( $matches ) {
2358 return mb_strtoupper( $matches[0] );
2362 * @param $matches array
2365 function ucCallback( $matches ) {
2366 list( $wikiUpperChars ) = self
::getCaseMaps();
2367 return strtr( $matches[1], $wikiUpperChars );
2371 * @param $matches array
2374 function lcCallback( $matches ) {
2375 list( , $wikiLowerChars ) = self
::getCaseMaps();
2376 return strtr( $matches[1], $wikiLowerChars );
2380 * @param $matches array
2383 function ucwordsCallbackMB( $matches ) {
2384 return mb_strtoupper( $matches[0] );
2388 * @param $matches array
2391 function ucwordsCallbackWiki( $matches ) {
2392 list( $wikiUpperChars ) = self
::getCaseMaps();
2393 return strtr( $matches[0], $wikiUpperChars );
2397 * Make a string's first character uppercase
2399 * @param $str string
2403 function ucfirst( $str ) {
2405 if ( $o < 96 ) { // if already uppercase...
2407 } elseif ( $o < 128 ) {
2408 return ucfirst( $str ); // use PHP's ucfirst()
2410 // fall back to more complex logic in case of multibyte strings
2411 return $this->uc( $str, true );
2416 * Convert a string to uppercase
2418 * @param $str string
2419 * @param $first bool
2423 function uc( $str, $first = false ) {
2424 if ( function_exists( 'mb_strtoupper' ) ) {
2426 if ( $this->isMultibyte( $str ) ) {
2427 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2429 return ucfirst( $str );
2432 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2435 if ( $this->isMultibyte( $str ) ) {
2436 $x = $first ?
'^' : '';
2437 return preg_replace_callback(
2438 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2439 array( $this, 'ucCallback' ),
2443 return $first ?
ucfirst( $str ) : strtoupper( $str );
2449 * @param $str string
2450 * @return mixed|string
2452 function lcfirst( $str ) {
2455 return strval( $str );
2456 } elseif ( $o >= 128 ) {
2457 return $this->lc( $str, true );
2458 } elseif ( $o > 96 ) {
2461 $str[0] = strtolower( $str[0] );
2467 * @param $str string
2468 * @param $first bool
2469 * @return mixed|string
2471 function lc( $str, $first = false ) {
2472 if ( function_exists( 'mb_strtolower' ) ) {
2474 if ( $this->isMultibyte( $str ) ) {
2475 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2477 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2480 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2483 if ( $this->isMultibyte( $str ) ) {
2484 $x = $first ?
'^' : '';
2485 return preg_replace_callback(
2486 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2487 array( $this, 'lcCallback' ),
2491 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2497 * @param $str string
2500 function isMultibyte( $str ) {
2501 return (bool)preg_match( '/[\x80-\xff]/', $str );
2505 * @param $str string
2506 * @return mixed|string
2508 function ucwords( $str ) {
2509 if ( $this->isMultibyte( $str ) ) {
2510 $str = $this->lc( $str );
2512 // regexp to find first letter in each word (i.e. after each space)
2513 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2515 // function to use to capitalize a single char
2516 if ( function_exists( 'mb_strtoupper' ) ) {
2517 return preg_replace_callback(
2519 array( $this, 'ucwordsCallbackMB' ),
2523 return preg_replace_callback(
2525 array( $this, 'ucwordsCallbackWiki' ),
2530 return ucwords( strtolower( $str ) );
2535 * capitalize words at word breaks
2537 * @param $str string
2540 function ucwordbreaks( $str ) {
2541 if ( $this->isMultibyte( $str ) ) {
2542 $str = $this->lc( $str );
2544 // since \b doesn't work for UTF-8, we explicitely define word break chars
2545 $breaks = "[ \-\(\)\}\{\.,\?!]";
2547 // find first letter after word break
2548 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2550 if ( function_exists( 'mb_strtoupper' ) ) {
2551 return preg_replace_callback(
2553 array( $this, 'ucwordbreaksCallbackMB' ),
2557 return preg_replace_callback(
2559 array( $this, 'ucwordsCallbackWiki' ),
2564 return preg_replace_callback(
2565 '/\b([\w\x80-\xff]+)\b/',
2566 array( $this, 'ucwordbreaksCallbackAscii' ),
2573 * Return a case-folded representation of $s
2575 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2576 * and $s2 are the same except for the case of their characters. It is not
2577 * necessary for the value returned to make sense when displayed.
2579 * Do *not* perform any other normalisation in this function. If a caller
2580 * uses this function when it should be using a more general normalisation
2581 * function, then fix the caller.
2587 function caseFold( $s ) {
2588 return $this->uc( $s );
2595 function checkTitleEncoding( $s ) {
2596 if ( is_array( $s ) ) {
2597 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2599 if ( StringUtils
::isUtf8( $s ) ) {
2603 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2609 function fallback8bitEncoding() {
2610 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2614 * Most writing systems use whitespace to break up words.
2615 * Some languages such as Chinese don't conventionally do this,
2616 * which requires special handling when breaking up words for
2621 function hasWordBreaks() {
2626 * Some languages such as Chinese require word segmentation,
2627 * Specify such segmentation when overridden in derived class.
2629 * @param $string String
2632 function segmentByWord( $string ) {
2637 * Some languages have special punctuation need to be normalized.
2638 * Make such changes here.
2640 * @param $string String
2643 function normalizeForSearch( $string ) {
2644 return self
::convertDoubleWidth( $string );
2648 * convert double-width roman characters to single-width.
2649 * range: ff00-ff5f ~= 0020-007f
2651 * @param $string string
2655 protected static function convertDoubleWidth( $string ) {
2656 static $full = null;
2657 static $half = null;
2659 if ( $full === null ) {
2660 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2661 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2662 $full = str_split( $fullWidth, 3 );
2663 $half = str_split( $halfWidth );
2666 $string = str_replace( $full, $half, $string );
2671 * @param $string string
2672 * @param $pattern string
2675 protected static function insertSpace( $string, $pattern ) {
2676 $string = preg_replace( $pattern, " $1 ", $string );
2677 $string = preg_replace( '/ +/', ' ', $string );
2682 * @param $termsArray array
2685 function convertForSearchResult( $termsArray ) {
2686 # some languages, e.g. Chinese, need to do a conversion
2687 # in order for search results to be displayed correctly
2692 * Get the first character of a string.
2697 function firstChar( $s ) {
2700 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2701 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2706 if ( isset( $matches[1] ) ) {
2707 if ( strlen( $matches[1] ) != 3 ) {
2711 // Break down Hangul syllables to grab the first jamo
2712 $code = utf8ToCodepoint( $matches[1] );
2713 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2715 } elseif ( $code < 0xb098 ) {
2716 return "\xe3\x84\xb1";
2717 } elseif ( $code < 0xb2e4 ) {
2718 return "\xe3\x84\xb4";
2719 } elseif ( $code < 0xb77c ) {
2720 return "\xe3\x84\xb7";
2721 } elseif ( $code < 0xb9c8 ) {
2722 return "\xe3\x84\xb9";
2723 } elseif ( $code < 0xbc14 ) {
2724 return "\xe3\x85\x81";
2725 } elseif ( $code < 0xc0ac ) {
2726 return "\xe3\x85\x82";
2727 } elseif ( $code < 0xc544 ) {
2728 return "\xe3\x85\x85";
2729 } elseif ( $code < 0xc790 ) {
2730 return "\xe3\x85\x87";
2731 } elseif ( $code < 0xcc28 ) {
2732 return "\xe3\x85\x88";
2733 } elseif ( $code < 0xce74 ) {
2734 return "\xe3\x85\x8a";
2735 } elseif ( $code < 0xd0c0 ) {
2736 return "\xe3\x85\x8b";
2737 } elseif ( $code < 0xd30c ) {
2738 return "\xe3\x85\x8c";
2739 } elseif ( $code < 0xd558 ) {
2740 return "\xe3\x85\x8d";
2742 return "\xe3\x85\x8e";
2749 function initEncoding() {
2750 # Some languages may have an alternate char encoding option
2751 # (Esperanto X-coding, Japanese furigana conversion, etc)
2752 # If this language is used as the primary content language,
2753 # an override to the defaults can be set here on startup.
2760 function recodeForEdit( $s ) {
2761 # For some languages we'll want to explicitly specify
2762 # which characters make it into the edit box raw
2763 # or are converted in some way or another.
2764 global $wgEditEncoding;
2765 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2768 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2776 function recodeInput( $s ) {
2777 # Take the previous into account.
2778 global $wgEditEncoding;
2779 if ( $wgEditEncoding != '' ) {
2780 $enc = $wgEditEncoding;
2784 if ( $enc == 'UTF-8' ) {
2787 return $this->iconv( $enc, 'UTF-8', $s );
2792 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2793 * also cleans up certain backwards-compatible sequences, converting them
2794 * to the modern Unicode equivalent.
2796 * This is language-specific for performance reasons only.
2802 function normalize( $s ) {
2803 global $wgAllUnicodeFixes;
2804 $s = UtfNormal
::cleanUp( $s );
2805 if ( $wgAllUnicodeFixes ) {
2806 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2807 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2814 * Transform a string using serialized data stored in the given file (which
2815 * must be in the serialized subdirectory of $IP). The file contains pairs
2816 * mapping source characters to destination characters.
2818 * The data is cached in process memory. This will go faster if you have the
2819 * FastStringSearch extension.
2821 * @param $file string
2822 * @param $string string
2824 * @throws MWException
2827 function transformUsingPairFile( $file, $string ) {
2828 if ( !isset( $this->transformData
[$file] ) ) {
2829 $data = wfGetPrecompiledData( $file );
2830 if ( $data === false ) {
2831 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2833 $this->transformData
[$file] = new ReplacementArray( $data );
2835 return $this->transformData
[$file]->replace( $string );
2839 * For right-to-left language support
2844 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2848 * Return the correct HTML 'dir' attribute value for this language.
2852 return $this->isRTL() ?
'rtl' : 'ltr';
2856 * Return 'left' or 'right' as appropriate alignment for line-start
2857 * for this language's text direction.
2859 * Should be equivalent to CSS3 'start' text-align value....
2863 function alignStart() {
2864 return $this->isRTL() ?
'right' : 'left';
2868 * Return 'right' or 'left' as appropriate alignment for line-end
2869 * for this language's text direction.
2871 * Should be equivalent to CSS3 'end' text-align value....
2875 function alignEnd() {
2876 return $this->isRTL() ?
'left' : 'right';
2880 * A hidden direction mark (LRM or RLM), depending on the language direction.
2881 * Unlike getDirMark(), this function returns the character as an HTML entity.
2882 * This function should be used when the output is guaranteed to be HTML,
2883 * because it makes the output HTML source code more readable. When
2884 * the output is plain text or can be escaped, getDirMark() should be used.
2886 * @param $opposite Boolean Get the direction mark opposite to your language
2890 function getDirMarkEntity( $opposite = false ) {
2892 return $this->isRTL() ?
'‎' : '‏';
2894 return $this->isRTL() ?
'‏' : '‎';
2898 * A hidden direction mark (LRM or RLM), depending on the language direction.
2899 * This function produces them as invisible Unicode characters and
2900 * the output may be hard to read and debug, so it should only be used
2901 * when the output is plain text or can be escaped. When the output is
2902 * HTML, use getDirMarkEntity() instead.
2904 * @param $opposite Boolean Get the direction mark opposite to your language
2907 function getDirMark( $opposite = false ) {
2908 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2909 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2911 return $this->isRTL() ?
$lrm : $rlm;
2913 return $this->isRTL() ?
$rlm : $lrm;
2919 function capitalizeAllNouns() {
2920 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2924 * An arrow, depending on the language direction.
2926 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2929 function getArrow( $direction = 'forwards' ) {
2930 switch ( $direction ) {
2932 return $this->isRTL() ?
'←' : '→';
2934 return $this->isRTL() ?
'→' : '←';
2947 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2951 function linkPrefixExtension() {
2952 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2956 * Get all magic words from cache.
2959 function getMagicWords() {
2960 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2964 * Run the LanguageGetMagic hook once.
2966 protected function doMagicHook() {
2967 if ( $this->mMagicHookDone
) {
2970 $this->mMagicHookDone
= true;
2971 wfProfileIn( 'LanguageGetMagic' );
2972 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2973 wfProfileOut( 'LanguageGetMagic' );
2977 * Fill a MagicWord object with data from here
2981 function getMagic( $mw ) {
2982 // Saves a function call
2983 if ( ! $this->mMagicHookDone
) {
2984 $this->doMagicHook();
2987 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2988 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2990 $rawEntry = self
::$dataCache->getSubitem(
2991 $this->mCode
, 'magicWords', $mw->mId
);
2994 if ( !is_array( $rawEntry ) ) {
2995 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2997 $mw->mCaseSensitive
= $rawEntry[0];
2998 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3003 * Add magic words to the extension array
3005 * @param $newWords array
3007 function addMagicWordsByLang( $newWords ) {
3008 $fallbackChain = $this->getFallbackLanguages();
3009 $fallbackChain = array_reverse( $fallbackChain );
3010 foreach ( $fallbackChain as $code ) {
3011 if ( isset( $newWords[$code] ) ) {
3012 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3018 * Get special page names, as an associative array
3019 * case folded alias => real name
3021 function getSpecialPageAliases() {
3022 // Cache aliases because it may be slow to load them
3023 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3025 $this->mExtendedSpecialPageAliases
=
3026 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3027 wfRunHooks( 'LanguageGetSpecialPageAliases',
3028 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3031 return $this->mExtendedSpecialPageAliases
;
3035 * Italic is unsuitable for some languages
3037 * @param $text String: the text to be emphasized.
3040 function emphasize( $text ) {
3041 return "<em>$text</em>";
3045 * Normally we output all numbers in plain en_US style, that is
3046 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3047 * point twohundredthirtyfive. However this is not suitable for all
3048 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3049 * Icelandic just want to use commas instead of dots, and dots instead
3050 * of commas like "293.291,235".
3052 * An example of this function being called:
3054 * wfMessage( 'message' )->numParams( $num )->text()
3057 * See LanguageGu.php for the Gujarati implementation and
3058 * $separatorTransformTable on MessageIs.php for
3059 * the , => . and . => , implementation.
3061 * @todo check if it's viable to use localeconv() for the decimal
3063 * @param $number Mixed: the string to be formatted, should be an integer
3064 * or a floating point number.
3065 * @param $nocommafy Bool: set to true for special numbers like dates
3068 public function formatNum( $number, $nocommafy = false ) {
3069 global $wgTranslateNumerals;
3070 if ( !$nocommafy ) {
3071 $number = $this->commafy( $number );
3072 $s = $this->separatorTransformTable();
3074 $number = strtr( $number, $s );
3078 if ( $wgTranslateNumerals ) {
3079 $s = $this->digitTransformTable();
3081 $number = strtr( $number, $s );
3089 * Front-end for non-commafied formatNum
3091 * @param mixed $number the string to be formatted, should be an integer
3092 * or a floating point number.
3096 public function formatNumNoSeparators( $number ) {
3097 return $this->formatNum( $number, true );
3101 * @param $number string
3104 function parseFormattedNumber( $number ) {
3105 $s = $this->digitTransformTable();
3107 $number = strtr( $number, array_flip( $s ) );
3110 $s = $this->separatorTransformTable();
3112 $number = strtr( $number, array_flip( $s ) );
3115 $number = strtr( $number, array( ',' => '' ) );
3120 * Adds commas to a given number
3122 * @param $number mixed
3125 function commafy( $number ) {
3126 $digitGroupingPattern = $this->digitGroupingPattern();
3127 if ( $number === null ) {
3131 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3132 // default grouping is at thousands, use the same for ###,###,### pattern too.
3133 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3135 // Ref: http://cldr.unicode.org/translation/number-patterns
3137 if ( intval( $number ) < 0 ) {
3138 // For negative numbers apply the algorithm like positive number and add sign.
3140 $number = substr( $number, 1 );
3142 $integerPart = array();
3143 $decimalPart = array();
3144 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3145 preg_match( "/\d+/", $number, $integerPart );
3146 preg_match( "/\.\d*/", $number, $decimalPart );
3147 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3148 if ( $groupedNumber === $number ) {
3149 // the string does not have any number part. Eg: .12345
3150 return $sign . $groupedNumber;
3152 $start = $end = strlen( $integerPart[0] );
3153 while ( $start > 0 ) {
3154 $match = $matches[0][$numMatches - 1];
3155 $matchLen = strlen( $match );
3156 $start = $end - $matchLen;
3160 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3162 if ( $numMatches > 1 ) {
3163 // use the last pattern for the rest of the number
3167 $groupedNumber = "," . $groupedNumber;
3170 return $sign . $groupedNumber;
3177 function digitGroupingPattern() {
3178 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3184 function digitTransformTable() {
3185 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3191 function separatorTransformTable() {
3192 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3196 * Take a list of strings and build a locale-friendly comma-separated
3197 * list, using the local comma-separator message.
3198 * The last two strings are chained with an "and".
3199 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3204 function listToText( array $l ) {
3205 $m = count( $l ) - 1;
3210 $and = $this->getMessageFromDB( 'and' );
3211 $space = $this->getMessageFromDB( 'word-separator' );
3213 $comma = $this->getMessageFromDB( 'comma-separator' );
3217 for ( $i = $m - 1; $i >= 0; $i-- ) {
3218 if ( $i == $m - 1 ) {
3219 $s = $l[$i] . $and . $space . $s;
3221 $s = $l[$i] . $comma . $s;
3228 * Take a list of strings and build a locale-friendly comma-separated
3229 * list, using the local comma-separator message.
3230 * @param $list array of strings to put in a comma list
3233 function commaList( array $list ) {
3235 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3241 * Take a list of strings and build a locale-friendly semicolon-separated
3242 * list, using the local semicolon-separator message.
3243 * @param $list array of strings to put in a semicolon list
3246 function semicolonList( array $list ) {
3248 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3254 * Same as commaList, but separate it with the pipe instead.
3255 * @param $list array of strings to put in a pipe list
3258 function pipeList( array $list ) {
3260 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3266 * Truncate a string to a specified length in bytes, appending an optional
3267 * string (e.g. for ellipses)
3269 * The database offers limited byte lengths for some columns in the database;
3270 * multi-byte character sets mean we need to ensure that only whole characters
3271 * are included, otherwise broken characters can be passed to the user
3273 * If $length is negative, the string will be truncated from the beginning
3275 * @param $string String to truncate
3276 * @param $length Int: maximum length (including ellipses)
3277 * @param $ellipsis String to append to the truncated text
3278 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3279 * $adjustLength was introduced in 1.18, before that behaved as if false.
3282 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3283 # Use the localized ellipsis character
3284 if ( $ellipsis == '...' ) {
3285 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3287 # Check if there is no need to truncate
3288 if ( $length == 0 ) {
3289 return $ellipsis; // convention
3290 } elseif ( strlen( $string ) <= abs( $length ) ) {
3291 return $string; // no need to truncate
3293 $stringOriginal = $string;
3294 # If ellipsis length is >= $length then we can't apply $adjustLength
3295 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3296 $string = $ellipsis; // this can be slightly unexpected
3297 # Otherwise, truncate and add ellipsis...
3299 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3300 if ( $length > 0 ) {
3301 $length -= $eLength;
3302 $string = substr( $string, 0, $length ); // xyz...
3303 $string = $this->removeBadCharLast( $string );
3304 $string = $string . $ellipsis;
3306 $length +
= $eLength;
3307 $string = substr( $string, $length ); // ...xyz
3308 $string = $this->removeBadCharFirst( $string );
3309 $string = $ellipsis . $string;
3312 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3313 # This check is *not* redundant if $adjustLength, due to the single case where
3314 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3315 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3318 return $stringOriginal;
3323 * Remove bytes that represent an incomplete Unicode character
3324 * at the end of string (e.g. bytes of the char are missing)
3326 * @param $string String
3329 protected function removeBadCharLast( $string ) {
3330 if ( $string != '' ) {
3331 $char = ord( $string[strlen( $string ) - 1] );
3333 if ( $char >= 0xc0 ) {
3334 # We got the first byte only of a multibyte char; remove it.
3335 $string = substr( $string, 0, -1 );
3336 } elseif ( $char >= 0x80 &&
3337 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3338 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3340 # We chopped in the middle of a character; remove it
3348 * Remove bytes that represent an incomplete Unicode character
3349 * at the start of string (e.g. bytes of the char are missing)
3351 * @param $string String
3354 protected function removeBadCharFirst( $string ) {
3355 if ( $string != '' ) {
3356 $char = ord( $string[0] );
3357 if ( $char >= 0x80 && $char < 0xc0 ) {
3358 # We chopped in the middle of a character; remove the whole thing
3359 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3366 * Truncate a string of valid HTML to a specified length in bytes,
3367 * appending an optional string (e.g. for ellipses), and return valid HTML
3369 * This is only intended for styled/linked text, such as HTML with
3370 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3371 * Also, this will not detect things like "display:none" CSS.
3373 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3375 * @param string $text HTML string to truncate
3376 * @param int $length (zero/positive) Maximum length (including ellipses)
3377 * @param string $ellipsis String to append to the truncated text
3380 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3381 # Use the localized ellipsis character
3382 if ( $ellipsis == '...' ) {
3383 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3385 # Check if there is clearly no need to truncate
3386 if ( $length <= 0 ) {
3387 return $ellipsis; // no text shown, nothing to format (convention)
3388 } elseif ( strlen( $text ) <= $length ) {
3389 return $text; // string short enough even *with* HTML (short-circuit)
3392 $dispLen = 0; // innerHTML legth so far
3393 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3394 $tagType = 0; // 0-open, 1-close
3395 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3396 $entityState = 0; // 0-not entity, 1-entity
3397 $tag = $ret = ''; // accumulated tag name, accumulated result string
3398 $openTags = array(); // open tag stack
3399 $maybeState = null; // possible truncation state
3401 $textLen = strlen( $text );
3402 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3403 for ( $pos = 0; true; ++
$pos ) {
3404 # Consider truncation once the display length has reached the maximim.
3405 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3406 # Check that we're not in the middle of a bracket/entity...
3407 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3408 if ( !$testingEllipsis ) {
3409 $testingEllipsis = true;
3410 # Save where we are; we will truncate here unless there turn out to
3411 # be so few remaining characters that truncation is not necessary.
3412 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3413 $maybeState = array( $ret, $openTags ); // save state
3415 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3416 # String in fact does need truncation, the truncation point was OK.
3417 list( $ret, $openTags ) = $maybeState; // reload state
3418 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3419 $ret .= $ellipsis; // add ellipsis
3423 if ( $pos >= $textLen ) {
3424 break; // extra iteration just for above checks
3427 # Read the next char...
3429 $lastCh = $pos ?
$text[$pos - 1] : '';
3430 $ret .= $ch; // add to result string
3432 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3433 $entityState = 0; // for bad HTML
3434 $bracketState = 1; // tag started (checking for backslash)
3435 } elseif ( $ch == '>' ) {
3436 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3437 $entityState = 0; // for bad HTML
3438 $bracketState = 0; // out of brackets
3439 } elseif ( $bracketState == 1 ) {
3441 $tagType = 1; // close tag (e.g. "</span>")
3443 $tagType = 0; // open tag (e.g. "<span>")
3446 $bracketState = 2; // building tag name
3447 } elseif ( $bracketState == 2 ) {
3451 // Name found (e.g. "<a href=..."), add on tag attributes...
3452 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3454 } elseif ( $bracketState == 0 ) {
3455 if ( $entityState ) {
3458 $dispLen++
; // entity is one displayed char
3461 if ( $neLength == 0 && !$maybeState ) {
3462 // Save state without $ch. We want to *hit* the first
3463 // display char (to get tags) but not *use* it if truncating.
3464 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3467 $entityState = 1; // entity found, (e.g. " ")
3469 $dispLen++
; // this char is displayed
3470 // Add the next $max display text chars after this in one swoop...
3471 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3472 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3473 $dispLen +
= $skipped;
3479 // Close the last tag if left unclosed by bad HTML
3480 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3481 while ( count( $openTags ) > 0 ) {
3482 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3488 * truncateHtml() helper function
3489 * like strcspn() but adds the skipped chars to $ret
3498 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3499 if ( $len === null ) {
3500 $len = -1; // -1 means "no limit" for strcspn
3501 } elseif ( $len < 0 ) {
3505 if ( $start < strlen( $text ) ) {
3506 $skipCount = strcspn( $text, $search, $start, $len );
3507 $ret .= substr( $text, $start, $skipCount );
3513 * truncateHtml() helper function
3514 * (a) push or pop $tag from $openTags as needed
3515 * (b) clear $tag value
3516 * @param &$tag string Current HTML tag name we are looking at
3517 * @param $tagType int (0-open tag, 1-close tag)
3518 * @param $lastCh string Character before the '>' that ended this tag
3519 * @param &$openTags array Open tag stack (not accounting for $tag)
3521 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3522 $tag = ltrim( $tag );
3524 if ( $tagType == 0 && $lastCh != '/' ) {
3525 $openTags[] = $tag; // tag opened (didn't close itself)
3526 } elseif ( $tagType == 1 ) {
3527 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3528 array_pop( $openTags ); // tag closed
3536 * Grammatical transformations, needed for inflected languages
3537 * Invoked by putting {{grammar:case|word}} in a message
3539 * @param $word string
3540 * @param $case string
3543 function convertGrammar( $word, $case ) {
3544 global $wgGrammarForms;
3545 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3546 return $wgGrammarForms[$this->getCode()][$case][$word];
3551 * Get the grammar forms for the content language
3552 * @return array of grammar forms
3555 function getGrammarForms() {
3556 global $wgGrammarForms;
3557 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3558 return $wgGrammarForms[$this->getCode()];
3563 * Provides an alternative text depending on specified gender.
3564 * Usage {{gender:username|masculine|feminine|neutral}}.
3565 * username is optional, in which case the gender of current user is used,
3566 * but only in (some) interface messages; otherwise default gender is used.
3568 * If no forms are given, an empty string is returned. If only one form is
3569 * given, it will be returned unconditionally. These details are implied by
3570 * the caller and cannot be overridden in subclasses.
3572 * If more than one form is given, the default is to use the neutral one
3573 * if it is specified, and to use the masculine one otherwise. These
3574 * details can be overridden in subclasses.
3576 * @param $gender string
3577 * @param $forms array
3581 function gender( $gender, $forms ) {
3582 if ( !count( $forms ) ) {
3585 $forms = $this->preConvertPlural( $forms, 2 );
3586 if ( $gender === 'male' ) {
3589 if ( $gender === 'female' ) {
3592 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3596 * Plural form transformations, needed for some languages.
3597 * For example, there are 3 form of plural in Russian and Polish,
3598 * depending on "count mod 10". See [[w:Plural]]
3599 * For English it is pretty simple.
3601 * Invoked by putting {{plural:count|wordform1|wordform2}}
3602 * or {{plural:count|wordform1|wordform2|wordform3}}
3604 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3606 * @param $count Integer: non-localized number
3607 * @param $forms Array: different plural forms
3608 * @return string Correct form of plural for $count in this language
3610 function convertPlural( $count, $forms ) {
3611 // Handle explicit n=pluralform cases
3612 foreach ( $forms as $index => $form ) {
3613 if ( preg_match( '/\d+=/i', $form ) ) {
3614 $pos = strpos( $form, '=' );
3615 if ( substr( $form, 0, $pos ) === (string) $count ) {
3616 return substr( $form, $pos +
1 );
3618 unset( $forms[$index] );
3622 $forms = array_values( $forms );
3623 if ( !count( $forms ) ) {
3627 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3628 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3629 return $forms[$pluralForm];
3633 * Checks that convertPlural was given an array and pads it to requested
3634 * amount of forms by copying the last one.
3636 * @param $count Integer: How many forms should there be at least
3637 * @param $forms Array of forms given to convertPlural
3638 * @return array Padded array of forms or an exception if not an array
3640 protected function preConvertPlural( /* Array */ $forms, $count ) {
3641 while ( count( $forms ) < $count ) {
3642 $forms[] = $forms[count( $forms ) - 1];
3648 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3649 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3650 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3651 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3654 * @param $str String: the validated block duration in English
3655 * @return string Somehow translated block duration
3656 * @see LanguageFi.php for example implementation
3658 function translateBlockExpiry( $str ) {
3659 $duration = SpecialBlock
::getSuggestedDurations( $this );
3660 foreach ( $duration as $show => $value ) {
3661 if ( strcmp( $str, $value ) == 0 ) {
3662 return htmlspecialchars( trim( $show ) );
3666 // Since usually only infinite or indefinite is only on list, so try
3667 // equivalents if still here.
3668 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3669 if ( in_array( $str, $indefs ) ) {
3670 foreach ( $indefs as $val ) {
3671 $show = array_search( $val, $duration, true );
3672 if ( $show !== false ) {
3673 return htmlspecialchars( trim( $show ) );
3678 // If all else fails, return a standard duration or timestamp description.
3679 $time = strtotime( $str, 0 );
3680 if ( $time === false ) { // Unknown format. Return it as-is in case.
3682 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3683 // $time is relative to 0 so it's a duration length.
3684 return $this->formatDuration( $time );
3685 } else { // It's an absolute timestamp.
3686 if ( $time === 0 ) {
3687 // wfTimestamp() handles 0 as current time instead of epoch.
3688 return $this->timeanddate( '19700101000000' );
3690 return $this->timeanddate( $time );
3696 * languages like Chinese need to be segmented in order for the diff
3699 * @param $text String
3702 public function segmentForDiff( $text ) {
3707 * and unsegment to show the result
3709 * @param $text String
3712 public function unsegmentForDiff( $text ) {
3717 * Return the LanguageConverter used in the Language
3720 * @return LanguageConverter
3722 public function getConverter() {
3723 return $this->mConverter
;
3727 * convert text to all supported variants
3729 * @param $text string
3732 public function autoConvertToAllVariants( $text ) {
3733 return $this->mConverter
->autoConvertToAllVariants( $text );
3737 * convert text to different variants of a language.
3739 * @param $text string
3742 public function convert( $text ) {
3743 return $this->mConverter
->convert( $text );
3747 * Convert a Title object to a string in the preferred variant
3749 * @param $title Title
3752 public function convertTitle( $title ) {
3753 return $this->mConverter
->convertTitle( $title );
3757 * Convert a namespace index to a string in the preferred variant
3762 public function convertNamespace( $ns ) {
3763 return $this->mConverter
->convertNamespace( $ns );
3767 * Check if this is a language with variants
3771 public function hasVariants() {
3772 return count( $this->getVariants() ) > 1;
3776 * Check if the language has the specific variant
3779 * @param $variant string
3782 public function hasVariant( $variant ) {
3783 return (bool)$this->mConverter
->validateVariant( $variant );
3787 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3789 * @param $text string
3792 public function armourMath( $text ) {
3793 return $this->mConverter
->armourMath( $text );
3797 * Perform output conversion on a string, and encode for safe HTML output.
3798 * @param $text String text to be converted
3799 * @param $isTitle Bool whether this conversion is for the article title
3801 * @todo this should get integrated somewhere sane
3803 public function convertHtml( $text, $isTitle = false ) {
3804 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3808 * @param $key string
3811 public function convertCategoryKey( $key ) {
3812 return $this->mConverter
->convertCategoryKey( $key );
3816 * Get the list of variants supported by this language
3817 * see sample implementation in LanguageZh.php
3819 * @return array an array of language codes
3821 public function getVariants() {
3822 return $this->mConverter
->getVariants();
3828 public function getPreferredVariant() {
3829 return $this->mConverter
->getPreferredVariant();
3835 public function getDefaultVariant() {
3836 return $this->mConverter
->getDefaultVariant();
3842 public function getURLVariant() {
3843 return $this->mConverter
->getURLVariant();
3847 * If a language supports multiple variants, it is
3848 * possible that non-existing link in one variant
3849 * actually exists in another variant. this function
3850 * tries to find it. See e.g. LanguageZh.php
3852 * @param $link String: the name of the link
3853 * @param $nt Mixed: the title object of the link
3854 * @param $ignoreOtherCond Boolean: to disable other conditions when
3855 * we need to transclude a template or update a category's link
3856 * @return null the input parameters may be modified upon return
3858 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3859 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3863 * If a language supports multiple variants, converts text
3864 * into an array of all possible variants of the text:
3865 * 'variant' => text in that variant
3867 * @deprecated since 1.17 Use autoConvertToAllVariants()
3869 * @param $text string
3873 public function convertLinkToAllVariants( $text ) {
3874 return $this->mConverter
->convertLinkToAllVariants( $text );
3878 * returns language specific options used by User::getPageRenderHash()
3879 * for example, the preferred language variant
3883 function getExtraHashOptions() {
3884 return $this->mConverter
->getExtraHashOptions();
3888 * For languages that support multiple variants, the title of an
3889 * article may be displayed differently in different variants. this
3890 * function returns the apporiate title defined in the body of the article.
3894 public function getParsedTitle() {
3895 return $this->mConverter
->getParsedTitle();
3899 * Prepare external link text for conversion. When the text is
3900 * a URL, it shouldn't be converted, and it'll be wrapped in
3901 * the "raw" tag (-{R| }-) to prevent conversion.
3903 * This function is called "markNoConversion" for historical
3906 * @param $text String: text to be used for external link
3907 * @param $noParse bool: wrap it without confirming it's a real URL first
3908 * @return string the tagged text
3910 public function markNoConversion( $text, $noParse = false ) {
3911 // Excluding protocal-relative URLs may avoid many false positives.
3912 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3913 return $this->mConverter
->markNoConversion( $text );
3920 * A regular expression to match legal word-trailing characters
3921 * which should be merged onto a link of the form [[foo]]bar.
3925 public function linkTrail() {
3926 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3932 function getLangObj() {
3937 * Get the RFC 3066 code for this language object
3939 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3940 * htmlspecialchars() or similar
3944 public function getCode() {
3945 return $this->mCode
;
3949 * Get the code in Bcp47 format which we can use
3950 * inside of html lang="" tags.
3952 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3953 * htmlspecialchars() or similar.
3958 public function getHtmlCode() {
3959 if ( is_null( $this->mHtmlCode
) ) {
3960 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3962 return $this->mHtmlCode
;
3966 * @param $code string
3968 public function setCode( $code ) {
3969 $this->mCode
= $code;
3970 // Ensure we don't leave an incorrect html code lying around
3971 $this->mHtmlCode
= null;
3975 * Get the name of a file for a certain language code
3976 * @param $prefix string Prepend this to the filename
3977 * @param $code string Language code
3978 * @param $suffix string Append this to the filename
3979 * @throws MWException
3980 * @return string $prefix . $mangledCode . $suffix
3982 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3983 // Protect against path traversal
3984 if ( !Language
::isValidCode( $code )
3985 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3987 throw new MWException( "Invalid language code \"$code\"" );
3990 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3994 * Get the language code from a file name. Inverse of getFileName()
3995 * @param $filename string $prefix . $languageCode . $suffix
3996 * @param $prefix string Prefix before the language code
3997 * @param $suffix string Suffix after the language code
3998 * @return string Language code, or false if $prefix or $suffix isn't found
4000 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4002 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4003 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4004 if ( !count( $m ) ) {
4007 return str_replace( '_', '-', strtolower( $m[1] ) );
4011 * @param $code string
4014 public static function getMessagesFileName( $code ) {
4016 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4017 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4022 * @param $code string
4025 public static function getClassFileName( $code ) {
4027 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4031 * Get the first fallback for a given language.
4033 * @param $code string
4035 * @return bool|string
4037 public static function getFallbackFor( $code ) {
4038 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4041 $fallbacks = self
::getFallbacksFor( $code );
4042 $first = array_shift( $fallbacks );
4048 * Get the ordered list of fallback languages.
4051 * @param $code string Language code
4054 public static function getFallbacksFor( $code ) {
4055 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4058 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4059 $v = array_map( 'trim', explode( ',', $v ) );
4060 if ( $v[count( $v ) - 1] !== 'en' ) {
4068 * Get the ordered list of fallback languages, ending with the fallback
4069 * language chain for the site language.
4072 * @param string $code Language code
4073 * @return array array( fallbacks, site fallbacks )
4075 public static function getFallbacksIncludingSiteLanguage( $code ) {
4076 global $wgLanguageCode;
4078 // Usually, we will only store a tiny number of fallback chains, so we
4079 // keep them in static memory.
4080 $cacheKey = "{$code}-{$wgLanguageCode}";
4082 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4083 $fallbacks = self
::getFallbacksFor( $code );
4085 // Append the site's fallback chain, including the site language itself
4086 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4087 array_unshift( $siteFallbacks, $wgLanguageCode );
4089 // Eliminate any languages already included in the chain
4090 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4092 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4094 return self
::$fallbackLanguageCache[$cacheKey];
4098 * Get all messages for a given language
4099 * WARNING: this may take a long time. If you just need all message *keys*
4100 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4102 * @param $code string
4106 public static function getMessagesFor( $code ) {
4107 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4111 * Get a message for a given language
4113 * @param $key string
4114 * @param $code string
4118 public static function getMessageFor( $key, $code ) {
4119 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4123 * Get all message keys for a given language. This is a faster alternative to
4124 * array_keys( Language::getMessagesFor( $code ) )
4127 * @param $code string Language code
4128 * @return array of message keys (strings)
4130 public static function getMessageKeysFor( $code ) {
4131 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4138 function fixVariableInNamespace( $talk ) {
4139 if ( strpos( $talk, '$1' ) === false ) {
4143 global $wgMetaNamespace;
4144 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4146 # Allow grammar transformations
4147 # Allowing full message-style parsing would make simple requests
4148 # such as action=raw much more expensive than they need to be.
4149 # This will hopefully cover most cases.
4150 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4151 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4152 return str_replace( ' ', '_', $talk );
4159 function replaceGrammarInNamespace( $m ) {
4160 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4164 * @throws MWException
4167 static function getCaseMaps() {
4168 static $wikiUpperChars, $wikiLowerChars;
4169 if ( isset( $wikiUpperChars ) ) {
4170 return array( $wikiUpperChars, $wikiLowerChars );
4173 wfProfileIn( __METHOD__
);
4174 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4175 if ( $arr === false ) {
4176 throw new MWException(
4177 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4179 $wikiUpperChars = $arr['wikiUpperChars'];
4180 $wikiLowerChars = $arr['wikiLowerChars'];
4181 wfProfileOut( __METHOD__
);
4182 return array( $wikiUpperChars, $wikiLowerChars );
4186 * Decode an expiry (block, protection, etc) which has come from the DB
4188 * @todo FIXME: why are we returnings DBMS-dependent strings???
4190 * @param $expiry String: Database expiry String
4191 * @param $format Bool|Int true to process using language functions, or TS_ constant
4192 * to return the expiry in a given timestamp
4196 public function formatExpiry( $expiry, $format = true ) {
4198 if ( $infinity === null ) {
4199 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4202 if ( $expiry == '' ||
$expiry == $infinity ) {
4203 return $format === true
4204 ?
$this->getMessageFromDB( 'infiniteblock' )
4207 return $format === true
4208 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4209 : wfTimestamp( $format, $expiry );
4215 * @param $seconds int|float
4216 * @param $format Array Optional
4217 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4218 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4219 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4220 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4223 function formatTimePeriod( $seconds, $format = array() ) {
4224 if ( !is_array( $format ) ) {
4225 $format = array( 'avoid' => $format ); // For backwards compatibility
4227 if ( !isset( $format['avoid'] ) ) {
4228 $format['avoid'] = false;
4230 if ( !isset( $format['noabbrevs' ] ) ) {
4231 $format['noabbrevs'] = false;
4233 $secondsMsg = wfMessage(
4234 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4235 $minutesMsg = wfMessage(
4236 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4237 $hoursMsg = wfMessage(
4238 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4239 $daysMsg = wfMessage(
4240 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4242 if ( round( $seconds * 10 ) < 100 ) {
4243 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4244 $s = $secondsMsg->params( $s )->text();
4245 } elseif ( round( $seconds ) < 60 ) {
4246 $s = $this->formatNum( round( $seconds ) );
4247 $s = $secondsMsg->params( $s )->text();
4248 } elseif ( round( $seconds ) < 3600 ) {
4249 $minutes = floor( $seconds / 60 );
4250 $secondsPart = round( fmod( $seconds, 60 ) );
4251 if ( $secondsPart == 60 ) {
4255 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4257 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4258 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4259 $hours = floor( $seconds / 3600 );
4260 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4261 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4262 if ( $secondsPart == 60 ) {
4266 if ( $minutes == 60 ) {
4270 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4272 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4273 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4274 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4277 $days = floor( $seconds / 86400 );
4278 if ( $format['avoid'] === 'avoidminutes' ) {
4279 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4280 if ( $hours == 24 ) {
4284 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4286 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4287 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4288 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4289 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4290 if ( $minutes == 60 ) {
4294 if ( $hours == 24 ) {
4298 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4300 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4302 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4304 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4306 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4313 * Format a bitrate for output, using an appropriate
4314 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4316 * This use base 1000. For base 1024 use formatSize(), for another base
4317 * see formatComputingNumbers()
4322 function formatBitrate( $bps ) {
4323 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4327 * @param $size int Size of the unit
4328 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4329 * @param $messageKey string Message key to be uesd
4332 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4334 return str_replace( '$1', $this->formatNum( $size ),
4335 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4338 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4341 $maxIndex = count( $sizes ) - 1;
4342 while ( $size >= $boundary && $index < $maxIndex ) {
4347 // For small sizes no decimal places necessary
4350 // For MB and bigger two decimal places are smarter
4353 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4355 $size = round( $size, $round );
4356 $text = $this->getMessageFromDB( $msg );
4357 return str_replace( '$1', $this->formatNum( $size ), $text );
4361 * Format a size in bytes for output, using an appropriate
4362 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4364 * This method use base 1024. For base 1000 use formatBitrate(), for
4365 * another base see formatComputingNumbers()
4367 * @param $size int Size to format
4368 * @return string Plain text (not HTML)
4370 function formatSize( $size ) {
4371 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4375 * Make a list item, used by various special pages
4377 * @param $page String Page link
4378 * @param $details String Text between brackets
4379 * @param $oppositedm Boolean Add the direction mark opposite to your
4380 * language, to display text properly
4383 function specialList( $page, $details, $oppositedm = true ) {
4384 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4385 $this->getDirMark();
4386 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4387 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4388 return $page . $details;
4392 * Generate (prev x| next x) (20|50|100...) type links for paging
4394 * @param $title Title object to link
4395 * @param $offset Integer offset parameter
4396 * @param $limit Integer limit parameter
4397 * @param $query array|String optional URL query parameter string
4398 * @param $atend Bool optional param for specified if this is the last page
4401 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4402 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4404 # Make 'previous' link
4405 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4406 if ( $offset > 0 ) {
4407 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4408 $query, $prev, 'prevn-title', 'mw-prevlink' );
4410 $plink = htmlspecialchars( $prev );
4414 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4416 $nlink = htmlspecialchars( $next );
4418 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4419 $query, $next, 'prevn-title', 'mw-nextlink' );
4422 # Make links to set number of items per page
4423 $numLinks = array();
4424 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4425 $numLinks[] = $this->numLink( $title, $offset, $num,
4426 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4429 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4430 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4434 * Helper function for viewPrevNext() that generates links
4436 * @param $title Title object to link
4437 * @param $offset Integer offset parameter
4438 * @param $limit Integer limit parameter
4439 * @param $query Array extra query parameters
4440 * @param $link String text to use for the link; will be escaped
4441 * @param $tooltipMsg String name of the message to use as tooltip
4442 * @param $class String value of the "class" attribute of the link
4443 * @return String HTML fragment
4445 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4446 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4447 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4448 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4449 'title' => $tooltip, 'class' => $class ), $link );
4453 * Get the conversion rule title, if any.
4457 public function getConvRuleTitle() {
4458 return $this->mConverter
->getConvRuleTitle();
4462 * Get the compiled plural rules for the language
4464 * @return array Associative array with plural form, and plural rule as key-value pairs
4466 public function getCompiledPluralRules() {
4467 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4468 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4469 if ( !$pluralRules ) {
4470 foreach ( $fallbacks as $fallbackCode ) {
4471 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4472 if ( $pluralRules ) {
4477 return $pluralRules;
4481 * Get the plural rules for the language
4483 * @return array Associative array with plural form number and plural rule as key-value pairs
4485 public function getPluralRules() {
4486 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4487 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4488 if ( !$pluralRules ) {
4489 foreach ( $fallbacks as $fallbackCode ) {
4490 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4491 if ( $pluralRules ) {
4496 return $pluralRules;
4500 * Get the plural rule types for the language
4502 * @return array Associative array with plural form number and plural rule type as key-value pairs
4504 public function getPluralRuleTypes() {
4505 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4506 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4507 if ( !$pluralRuleTypes ) {
4508 foreach ( $fallbacks as $fallbackCode ) {
4509 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4510 if ( $pluralRuleTypes ) {
4515 return $pluralRuleTypes;
4519 * Find the index number of the plural rule appropriate for the given number
4520 * @return int The index number of the plural rule
4522 public function getPluralRuleIndexNumber( $number ) {
4523 $pluralRules = $this->getCompiledPluralRules();
4524 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4529 * Find the plural rule type appropriate for the given number
4530 * For example, if the language is set to Arabic, getPluralType(5) should
4533 * @return string The name of the plural rule type, e.g. one, two, few, many
4535 public function getPluralRuleType( $number ) {
4536 $index = $this->getPluralRuleIndexNumber( $number );
4537 $pluralRuleTypes = $this->getPluralRuleTypes();
4538 if ( isset( $pluralRuleTypes[$index] ) ) {
4539 return $pluralRuleTypes[$index];