3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
38 * a fake language converter
47 function __construct( $langobj ) { $this->mLang
= $langobj; }
48 function autoConvert( $text, $variant = false ) { return $text; }
49 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
50 function convert( $t ) { return $t; }
51 function convertTo( $text, $variant ) { return $text; }
52 function convertTitle( $t ) { return $t->getPrefixedText(); }
53 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
54 function getVariants() { return array( $this->mLang
->getCode() ); }
55 function getVariantFallbacks( $variant ) { return $this->mLang
->getCode(); }
56 function getPreferredVariant() { return $this->mLang
->getCode(); }
57 function getDefaultVariant() { return $this->mLang
->getCode(); }
58 function getURLVariant() { return ''; }
59 function getConvRuleTitle() { return false; }
60 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
61 function getExtraHashOptions() { return ''; }
62 function getParsedTitle() { return ''; }
63 function markNoConversion( $text, $noParse = false ) { return $text; }
64 function convertCategoryKey( $key ) { return $key; }
65 /** @deprecated since 1.22 is no longer used */
66 function armourMath( $text ) { return $text; }
67 function validateVariant( $variant = null ) { return $variant === $this->mLang
->getCode() ?
$variant : null; }
68 function translate( $text, $variant ) { return $text; }
72 * Internationalisation code
78 * @var LanguageConverter
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null, $mParentLanguage = false;
86 public $dateFormatStrings = array();
87 public $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
92 * ReplacementArray object caches
94 public $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
174 * Cache for language fallbacks.
175 * @see Language::getFallbacksIncludingSiteLanguage
179 static private $fallbackLanguageCache = array();
182 * Get a cached or new language object for a given language code
183 * @param $code String
186 static function factory( $code ) {
187 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
189 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
190 $code = $wgDummyLanguageCodes[$code];
193 // get the language object to process
194 $langObj = isset( self
::$mLangObjCache[$code] )
195 ? self
::$mLangObjCache[$code]
196 : self
::newFromCode( $code );
198 // merge the language object in to get it up front in the cache
199 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
200 // get rid of the oldest ones in case we have an overflow
201 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
207 * Create a language object for a given language code
208 * @param $code String
209 * @throws MWException
212 protected static function newFromCode( $code ) {
213 // Protect against path traversal below
214 if ( !Language
::isValidCode( $code )
215 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code )
217 throw new MWException( "Invalid language code \"$code\"" );
220 if ( !Language
::isValidBuiltInCode( $code ) ) {
221 // It's not possible to customise this code with class files, so
222 // just return a Language object. This is to support uselang= hacks.
223 $lang = new Language
;
224 $lang->setCode( $code );
228 // Check if there is a language class for the code
229 $class = self
::classFromCode( $code );
230 self
::preloadLanguageClass( $class );
231 if ( class_exists( $class ) ) {
236 // Keep trying the fallback list until we find an existing class
237 $fallbacks = Language
::getFallbacksFor( $code );
238 foreach ( $fallbacks as $fallbackCode ) {
239 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
240 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
243 $class = self
::classFromCode( $fallbackCode );
244 self
::preloadLanguageClass( $class );
245 if ( class_exists( $class ) ) {
246 $lang = Language
::newFromCode( $fallbackCode );
247 $lang->setCode( $code );
252 throw new MWException( "Invalid fallback sequence for language '$code'" );
256 * Checks whether any localisation is available for that language tag
257 * in MediaWiki (MessagesXx.php exists).
259 * @param string $code Language tag (in lower case)
260 * @return bool Whether language is supported
263 public static function isSupportedLanguage( $code ) {
264 return self
::isValidBuiltInCode( $code )
265 && ( is_readable( self
::getMessagesFileName( $code ) )
266 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
271 * Returns true if a language code string is a well-formed language tag
272 * according to RFC 5646.
273 * This function only checks well-formedness; it doesn't check that
274 * language, script or variant codes actually exist in the repositories.
276 * Based on regexes by Mark Davis of the Unicode Consortium:
277 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
279 * @param $code string
280 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
285 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
288 $alphanum = '[a-z0-9]';
289 $x = 'x'; # private use singleton
290 $singleton = '[a-wy-z]'; # other singleton
291 $s = $lenient ?
'[-_]' : '-';
293 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
294 $script = "$alpha{4}"; # ISO 15924
295 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
296 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
297 $extension = "$singleton(?:$s$alphanum{2,8})+";
298 $privateUse = "$x(?:$s$alphanum{1,8})+";
300 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
301 # Since these are limited, this is safe even later changes to the registry --
302 # the only oddity is that it might change the type of the tag, and thus
303 # the results from the capturing groups.
304 # http://www.iana.org/assignments/language-subtag-registry
306 $grandfathered = "en{$s}GB{$s}oed"
307 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
308 . "|no{$s}(?:bok|nyn)"
309 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
310 . "|zh{$s}min{$s}nan";
312 $variantList = "$variant(?:$s$variant)*";
313 $extensionList = "$extension(?:$s$extension)*";
315 $langtag = "(?:($language)"
318 . "(?:$s$variantList)?"
319 . "(?:$s$extensionList)?"
320 . "(?:$s$privateUse)?)";
322 # The final breakdown, with capturing groups for each of these components
323 # The variants, extensions, grandfathered, and private-use may have interior '-'
325 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
327 return (bool)preg_match( "/$root/", strtolower( $code ) );
331 * Returns true if a language code string is of a valid form, whether or
332 * not it exists. This includes codes which are used solely for
333 * customisation via the MediaWiki namespace.
335 * @param $code string
339 public static function isValidCode( $code ) {
340 static $cache = array();
341 if ( isset( $cache[$code] ) ) {
342 return $cache[$code];
344 // People think language codes are html safe, so enforce it.
345 // Ideally we should only allow a-zA-Z0-9-
346 // but, .+ and other chars are often used for {{int:}} hacks
347 // see bugs 37564, 37587, 36938
349 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
350 && !preg_match( Title
::getTitleInvalidRegex(), $code );
352 return $cache[$code];
356 * Returns true if a language code is of a valid form for the purposes of
357 * internal customisation of MediaWiki, via Messages*.php or *.json.
359 * @param $code string
361 * @throws MWException
365 public static function isValidBuiltInCode( $code ) {
367 if ( !is_string( $code ) ) {
368 if ( is_object( $code ) ) {
369 $addmsg = " of class " . get_class( $code );
373 $type = gettype( $code );
374 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
377 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
381 * Returns true if a language code is an IETF tag known to MediaWiki.
383 * @param $code string
388 public static function isKnownLanguageTag( $tag ) {
389 static $coreLanguageNames;
391 // Quick escape for invalid input to avoid exceptions down the line
392 // when code tries to process tags which are not valid at all.
393 if ( !self
::isValidBuiltInCode( $tag ) ) {
397 if ( $coreLanguageNames === null ) {
399 include "$IP/languages/Names.php";
402 if ( isset( $coreLanguageNames[$tag] )
403 || self
::fetchLanguageName( $tag, $tag ) !== ''
413 * @return String Name of the language class
415 public static function classFromCode( $code ) {
416 if ( $code == 'en' ) {
419 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
424 * Includes language class files
426 * @param $class string Name of the language class
428 public static function preloadLanguageClass( $class ) {
431 if ( $class === 'Language' ) {
435 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
436 include_once "$IP/languages/classes/$class.php";
441 * Get the LocalisationCache instance
443 * @return LocalisationCache
445 public static function getLocalisationCache() {
446 if ( is_null( self
::$dataCache ) ) {
447 global $wgLocalisationCacheConf;
448 $class = $wgLocalisationCacheConf['class'];
449 self
::$dataCache = new $class( $wgLocalisationCacheConf );
451 return self
::$dataCache;
454 function __construct() {
455 $this->mConverter
= new FakeConverter( $this );
456 // Set the code to the name of the descendant
457 if ( get_class( $this ) == 'Language' ) {
460 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
462 self
::getLocalisationCache();
466 * Reduce memory usage
468 function __destruct() {
469 foreach ( $this as $name => $value ) {
470 unset( $this->$name );
475 * Hook which will be called if this is the content language.
476 * Descendants can use this to register hook functions or modify globals
478 function initContLang() { }
481 * Same as getFallbacksFor for current language.
483 * @deprecated in 1.19
485 function getFallbackLanguageCode() {
486 wfDeprecated( __METHOD__
, '1.19' );
487 return self
::getFallbackFor( $this->mCode
);
494 function getFallbackLanguages() {
495 return self
::getFallbacksFor( $this->mCode
);
499 * Exports $wgBookstoreListEn
502 function getBookstoreList() {
503 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
507 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
508 * available in localised form, it will be included in English.
512 public function getNamespaces() {
513 if ( is_null( $this->namespaceNames
) ) {
514 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
516 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
517 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
519 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
521 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
522 if ( $wgMetaNamespaceTalk ) {
523 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
525 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
526 $this->namespaceNames
[NS_PROJECT_TALK
] =
527 $this->fixVariableInNamespace( $talk );
530 # Sometimes a language will be localised but not actually exist on this wiki.
531 foreach ( $this->namespaceNames
as $key => $text ) {
532 if ( !isset( $validNamespaces[$key] ) ) {
533 unset( $this->namespaceNames
[$key] );
537 # The above mixing may leave namespaces out of canonical order.
538 # Re-order by namespace ID number...
539 ksort( $this->namespaceNames
);
541 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
543 return $this->namespaceNames
;
547 * Arbitrarily set all of the namespace names at once. Mainly used for testing
548 * @param $namespaces Array of namespaces (id => name)
550 public function setNamespaces( array $namespaces ) {
551 $this->namespaceNames
= $namespaces;
552 $this->mNamespaceIds
= null;
556 * Resets all of the namespace caches. Mainly used for testing
558 public function resetNamespaces() {
559 $this->namespaceNames
= null;
560 $this->mNamespaceIds
= null;
561 $this->namespaceAliases
= null;
565 * A convenience function that returns the same thing as
566 * getNamespaces() except with the array values changed to ' '
567 * where it found '_', useful for producing output to be displayed
568 * e.g. in <select> forms.
572 function getFormattedNamespaces() {
573 $ns = $this->getNamespaces();
574 foreach ( $ns as $k => $v ) {
575 $ns[$k] = strtr( $v, '_', ' ' );
581 * Get a namespace value by key
583 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
584 * echo $mw_ns; // prints 'MediaWiki'
587 * @param $index Int: the array key of the namespace to return
588 * @return mixed, string if the namespace value exists, otherwise false
590 function getNsText( $index ) {
591 $ns = $this->getNamespaces();
592 return isset( $ns[$index] ) ?
$ns[$index] : false;
596 * A convenience function that returns the same thing as
597 * getNsText() except with '_' changed to ' ', useful for
601 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
602 * echo $mw_ns; // prints 'MediaWiki talk'
605 * @param int $index The array key of the namespace to return
606 * @return string Namespace name without underscores (empty string if namespace does not exist)
608 function getFormattedNsText( $index ) {
609 $ns = $this->getNsText( $index );
610 return strtr( $ns, '_', ' ' );
614 * Returns gender-dependent namespace alias if available.
615 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
616 * @param $index Int: namespace index
617 * @param $gender String: gender key (male, female... )
621 function getGenderNsText( $index, $gender ) {
622 global $wgExtraGenderNamespaces;
624 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
625 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
629 * Whether this language uses gender-dependent namespace aliases.
630 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
634 function needsGenderDistinction() {
635 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
636 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
637 // $wgExtraGenderNamespaces overrides everything
639 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
640 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
641 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
644 // Check what is in i18n files
645 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
646 return count( $aliases ) > 0;
651 * Get a namespace key by value, case insensitive.
652 * Only matches namespace names for the current language, not the
653 * canonical ones defined in Namespace.php.
655 * @param $text String
656 * @return mixed An integer if $text is a valid value otherwise false
658 function getLocalNsIndex( $text ) {
659 $lctext = $this->lc( $text );
660 $ids = $this->getNamespaceIds();
661 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
667 function getNamespaceAliases() {
668 if ( is_null( $this->namespaceAliases
) ) {
669 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
673 foreach ( $aliases as $name => $index ) {
674 if ( $index === NS_PROJECT_TALK
) {
675 unset( $aliases[$name] );
676 $name = $this->fixVariableInNamespace( $name );
677 $aliases[$name] = $index;
682 global $wgExtraGenderNamespaces;
683 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
684 foreach ( $genders as $index => $forms ) {
685 foreach ( $forms as $alias ) {
686 $aliases[$alias] = $index;
690 # Also add converted namespace names as aliases, to avoid confusion.
691 $convertedNames = array();
692 foreach ( $this->getVariants() as $variant ) {
693 if ( $variant === $this->mCode
) {
696 foreach ( $this->getNamespaces() as $ns => $_ ) {
697 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
701 $this->namespaceAliases
= $aliases +
$convertedNames;
703 return $this->namespaceAliases
;
709 function getNamespaceIds() {
710 if ( is_null( $this->mNamespaceIds
) ) {
711 global $wgNamespaceAliases;
712 # Put namespace names and aliases into a hashtable.
713 # If this is too slow, then we should arrange it so that it is done
714 # before caching. The catch is that at pre-cache time, the above
715 # class-specific fixup hasn't been done.
716 $this->mNamespaceIds
= array();
717 foreach ( $this->getNamespaces() as $index => $name ) {
718 $this->mNamespaceIds
[$this->lc( $name )] = $index;
720 foreach ( $this->getNamespaceAliases() as $name => $index ) {
721 $this->mNamespaceIds
[$this->lc( $name )] = $index;
723 if ( $wgNamespaceAliases ) {
724 foreach ( $wgNamespaceAliases as $name => $index ) {
725 $this->mNamespaceIds
[$this->lc( $name )] = $index;
729 return $this->mNamespaceIds
;
733 * Get a namespace key by value, case insensitive. Canonical namespace
734 * names override custom ones defined for the current language.
736 * @param $text String
737 * @return mixed An integer if $text is a valid value otherwise false
739 function getNsIndex( $text ) {
740 $lctext = $this->lc( $text );
741 $ns = MWNamespace
::getCanonicalIndex( $lctext );
742 if ( $ns !== null ) {
745 $ids = $this->getNamespaceIds();
746 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
750 * short names for language variants used for language conversion links.
752 * @param $code String
753 * @param $usemsg bool Use the "variantname-xyz" message if it exists
756 function getVariantname( $code, $usemsg = true ) {
757 $msg = "variantname-$code";
758 if ( $usemsg && wfMessage( $msg )->exists() ) {
759 return $this->getMessageFromDB( $msg );
761 $name = self
::fetchLanguageName( $code );
763 return $name; # if it's defined as a language name, show that
765 # otherwise, output the language code
771 * @param $name string
774 function specialPage( $name ) {
775 $aliases = $this->getSpecialPageAliases();
776 if ( isset( $aliases[$name][0] ) ) {
777 $name = $aliases[$name][0];
779 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
785 function getDatePreferences() {
786 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
792 function getDateFormats() {
793 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
797 * @return array|string
799 function getDefaultDateFormat() {
800 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
801 if ( $df === 'dmy or mdy' ) {
802 global $wgAmericanDates;
803 return $wgAmericanDates ?
'mdy' : 'dmy';
812 function getDatePreferenceMigrationMap() {
813 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
820 function getImageFile( $image ) {
821 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
827 function getExtraUserToggles() {
828 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
835 function getUserToggle( $tog ) {
836 return $this->getMessageFromDB( "tog-$tog" );
840 * Get native language names, indexed by code.
841 * Only those defined in MediaWiki, no other data like CLDR.
842 * If $customisedOnly is true, only returns codes with a messages file
844 * @param $customisedOnly bool
847 * @deprecated in 1.20, use fetchLanguageNames()
849 public static function getLanguageNames( $customisedOnly = false ) {
850 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
854 * Get translated language names. This is done on best effort and
855 * by default this is exactly the same as Language::getLanguageNames.
856 * The CLDR extension provides translated names.
857 * @param $code String Language code.
858 * @return Array language code => language name
860 * @deprecated in 1.20, use fetchLanguageNames()
862 public static function getTranslatedLanguageNames( $code ) {
863 return self
::fetchLanguageNames( $code, 'all' );
867 * Get an array of language names, indexed by code.
868 * @param $inLanguage null|string: Code of language in which to return the names
869 * Use null for autonyms (native names)
870 * @param $include string:
871 * 'all' all available languages
872 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
873 * 'mwfile' only if the language is in 'mw' *and* has a message file
874 * @return array: language code => language name
877 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
878 global $wgExtraLanguageNames;
879 static $coreLanguageNames;
881 if ( $coreLanguageNames === null ) {
883 include "$IP/languages/Names.php";
889 # TODO: also include when $inLanguage is null, when this code is more efficient
890 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
893 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
894 foreach ( $mwNames as $mwCode => $mwName ) {
895 # - Prefer own MediaWiki native name when not using the hook
896 # - For other names just add if not added through the hook
897 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
898 $names[$mwCode] = $mwName;
902 if ( $include === 'all' ) {
907 $coreCodes = array_keys( $mwNames );
908 foreach ( $coreCodes as $coreCode ) {
909 $returnMw[$coreCode] = $names[$coreCode];
912 if ( $include === 'mwfile' ) {
913 $namesMwFile = array();
914 # We do this using a foreach over the codes instead of a directory
915 # loop so that messages files in extensions will work correctly.
916 foreach ( $returnMw as $code => $value ) {
917 if ( is_readable( self
::getMessagesFileName( $code ) )
918 ||
is_readable( self
::getJsonMessagesFileName( $code ) )
920 $namesMwFile[$code] = $names[$code];
927 # 'mw' option; default if it's not one of the other two options (all/mwfile)
932 * @param $code string: The code of the language for which to get the name
933 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
934 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
935 * @return string: Language name or empty
938 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
939 $code = strtolower( $code );
940 $array = self
::fetchLanguageNames( $inLanguage, $include );
941 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
945 * Get a message from the MediaWiki namespace.
947 * @param $msg String: message name
950 function getMessageFromDB( $msg ) {
951 return wfMessage( $msg )->inLanguage( $this )->text();
955 * Get the native language name of $code.
956 * Only if defined in MediaWiki, no other data like CLDR.
957 * @param $code string
959 * @deprecated in 1.20, use fetchLanguageName()
961 function getLanguageName( $code ) {
962 return self
::fetchLanguageName( $code );
969 function getMonthName( $key ) {
970 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
976 function getMonthNamesArray() {
977 $monthNames = array( '' );
978 for ( $i = 1; $i < 13; $i++
) {
979 $monthNames[] = $this->getMonthName( $i );
988 function getMonthNameGen( $key ) {
989 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
996 function getMonthAbbreviation( $key ) {
997 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
1003 function getMonthAbbreviationsArray() {
1004 $monthNames = array( '' );
1005 for ( $i = 1; $i < 13; $i++
) {
1006 $monthNames[] = $this->getMonthAbbreviation( $i );
1012 * @param $key string
1015 function getWeekdayName( $key ) {
1016 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
1020 * @param $key string
1023 function getWeekdayAbbreviation( $key ) {
1024 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1028 * @param $key string
1031 function getIranianCalendarMonthName( $key ) {
1032 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1036 * @param $key string
1039 function getHebrewCalendarMonthName( $key ) {
1040 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1044 * @param $key string
1047 function getHebrewCalendarMonthNameGen( $key ) {
1048 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1052 * @param $key string
1055 function getHijriCalendarMonthName( $key ) {
1056 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1060 * This is a workalike of PHP's date() function, but with better
1061 * internationalisation, a reduced set of format characters, and a better
1064 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1065 * the PHP manual for definitions. There are a number of extensions, which
1068 * xn Do not translate digits of the next numeric format character
1069 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1070 * xr Use roman numerals for the next numeric format character
1071 * xh Use hebrew numerals for the next numeric format character
1073 * xg Genitive month name
1075 * xij j (day number) in Iranian calendar
1076 * xiF F (month name) in Iranian calendar
1077 * xin n (month number) in Iranian calendar
1078 * xiy y (two digit year) in Iranian calendar
1079 * xiY Y (full year) in Iranian calendar
1081 * xjj j (day number) in Hebrew calendar
1082 * xjF F (month name) in Hebrew calendar
1083 * xjt t (days in month) in Hebrew calendar
1084 * xjx xg (genitive month name) in Hebrew calendar
1085 * xjn n (month number) in Hebrew calendar
1086 * xjY Y (full year) in Hebrew calendar
1088 * xmj j (day number) in Hijri calendar
1089 * xmF F (month name) in Hijri calendar
1090 * xmn n (month number) in Hijri calendar
1091 * xmY Y (full year) in Hijri calendar
1093 * xkY Y (full year) in Thai solar calendar. Months and days are
1094 * identical to the Gregorian calendar
1095 * xoY Y (full year) in Minguo calendar or Juche year.
1096 * Months and days are identical to the
1097 * Gregorian calendar
1098 * xtY Y (full year) in Japanese nengo. Months and days are
1099 * identical to the Gregorian calendar
1101 * Characters enclosed in double quotes will be considered literal (with
1102 * the quotes themselves removed). Unmatched quotes will be considered
1103 * literal quotes. Example:
1105 * "The month is" F => The month is January
1108 * Backslash escaping is also supported.
1110 * Input timestamp is assumed to be pre-normalized to the desired local
1111 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1112 * $ts is UTC if $zone is not given.
1114 * @param $format String
1115 * @param $ts String: 14-character timestamp
1118 * @param $zone DateTimeZone: Timezone of $ts
1119 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1121 * @throws MWException
1124 function sprintfDate( $format, $ts, DateTimeZone
$zone = null ) {
1129 $dateTimeObj = false;
1138 if ( strlen( $ts ) !== 14 ) {
1139 throw new MWException( __METHOD__
. ": The timestamp $ts should have 14 characters" );
1142 if ( !ctype_digit( $ts ) ) {
1143 throw new MWException( __METHOD__
. ": The timestamp $ts should be a number" );
1146 for ( $p = 0; $p < strlen( $format ); $p++
) {
1148 $code = $format[$p];
1149 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1150 $code .= $format[++
$p];
1153 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1154 $code .= $format[++
$p];
1165 $rawToggle = !$rawToggle;
1174 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1178 $hebrew = self
::tsToHebrew( $ts );
1180 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1183 $num = substr( $ts, 6, 2 );
1186 if ( !$dateTimeObj ) {
1187 $dateTimeObj = DateTime
::createFromFormat(
1188 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1191 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) +
1 );
1194 $num = intval( substr( $ts, 6, 2 ) );
1198 $iranian = self
::tsToIranian( $ts );
1204 $hijri = self
::tsToHijri( $ts );
1210 $hebrew = self
::tsToHebrew( $ts );
1215 if ( !$dateTimeObj ) {
1216 $dateTimeObj = DateTime
::createFromFormat(
1217 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1220 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) +
1 );
1223 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1227 $iranian = self
::tsToIranian( $ts );
1229 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1233 $hijri = self
::tsToHijri( $ts );
1235 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1239 $hebrew = self
::tsToHebrew( $ts );
1241 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1244 $num = substr( $ts, 4, 2 );
1247 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1250 $num = intval( substr( $ts, 4, 2 ) );
1254 $iranian = self
::tsToIranian( $ts );
1260 $hijri = self
::tsToHijri ( $ts );
1266 $hebrew = self
::tsToHebrew( $ts );
1272 $hebrew = self
::tsToHebrew( $ts );
1277 $num = substr( $ts, 0, 4 );
1281 $iranian = self
::tsToIranian( $ts );
1287 $hijri = self
::tsToHijri( $ts );
1293 $hebrew = self
::tsToHebrew( $ts );
1299 $thai = self
::tsToYear( $ts, 'thai' );
1305 $minguo = self
::tsToYear( $ts, 'minguo' );
1311 $tenno = self
::tsToYear( $ts, 'tenno' );
1316 $num = substr( $ts, 2, 2 );
1320 $iranian = self
::tsToIranian( $ts );
1322 $num = substr( $iranian[0], -2 );
1325 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1328 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1331 $h = substr( $ts, 8, 2 );
1332 $num = $h %
12 ?
$h %
12 : 12;
1335 $num = intval( substr( $ts, 8, 2 ) );
1338 $h = substr( $ts, 8, 2 );
1339 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1342 $num = substr( $ts, 8, 2 );
1345 $num = substr( $ts, 10, 2 );
1348 $num = substr( $ts, 12, 2 );
1356 // Pass through string from $dateTimeObj->format()
1357 if ( !$dateTimeObj ) {
1358 $dateTimeObj = DateTime
::createFromFormat(
1359 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1362 $s .= $dateTimeObj->format( $code );
1374 // Pass through number from $dateTimeObj->format()
1375 if ( !$dateTimeObj ) {
1376 $dateTimeObj = DateTime
::createFromFormat(
1377 'YmdHis', $ts, $zone ?
: new DateTimeZone( 'UTC' )
1380 $num = $dateTimeObj->format( $code );
1383 # Backslash escaping
1384 if ( $p < strlen( $format ) - 1 ) {
1385 $s .= $format[++
$p];
1392 if ( $p < strlen( $format ) - 1 ) {
1393 $endQuote = strpos( $format, '"', $p +
1 );
1394 if ( $endQuote === false ) {
1395 # No terminating quote, assume literal "
1398 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1402 # Quote at end of string, assume literal "
1409 if ( $num !== false ) {
1410 if ( $rawToggle ||
$raw ) {
1413 } elseif ( $roman ) {
1414 $s .= Language
::romanNumeral( $num );
1416 } elseif ( $hebrewNum ) {
1417 $s .= self
::hebrewNumeral( $num );
1420 $s .= $this->formatNum( $num, true );
1427 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1428 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1431 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1432 * Gregorian dates to Iranian dates. Originally written in C, it
1433 * is released under the terms of GNU Lesser General Public
1434 * License. Conversion to PHP was performed by Niklas Laxström.
1436 * Link: http://www.farsiweb.info/jalali/jalali.c
1442 private static function tsToIranian( $ts ) {
1443 $gy = substr( $ts, 0, 4 ) -1600;
1444 $gm = substr( $ts, 4, 2 ) -1;
1445 $gd = substr( $ts, 6, 2 ) -1;
1447 # Days passed from the beginning (including leap years)
1449 +
floor( ( $gy +
3 ) / 4 )
1450 - floor( ( $gy +
99 ) / 100 )
1451 +
floor( ( $gy +
399 ) / 400 );
1453 // Add days of the past months of this year
1454 for ( $i = 0; $i < $gm; $i++
) {
1455 $gDayNo +
= self
::$GREG_DAYS[$i];
1459 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1463 // Days passed in current month
1464 $gDayNo +
= (int)$gd;
1466 $jDayNo = $gDayNo - 79;
1468 $jNp = floor( $jDayNo / 12053 );
1471 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1474 if ( $jDayNo >= 366 ) {
1475 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1476 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1479 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1480 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1486 return array( $jy, $jm, $jd );
1490 * Converting Gregorian dates to Hijri dates.
1492 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1494 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1500 private static function tsToHijri( $ts ) {
1501 $year = substr( $ts, 0, 4 );
1502 $month = substr( $ts, 4, 2 );
1503 $day = substr( $ts, 6, 2 );
1511 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1512 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1514 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1515 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1516 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1519 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1520 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1523 $zl = $zjd -1948440 +
10632;
1524 $zn = (int)( ( $zl - 1 ) / 10631 );
1525 $zl = $zl - 10631 * $zn +
354;
1526 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1527 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1528 $zm = (int)( ( 24 * $zl ) / 709 );
1529 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1530 $zy = 30 * $zn +
$zj - 30;
1532 return array( $zy, $zm, $zd );
1536 * Converting Gregorian dates to Hebrew dates.
1538 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1539 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1540 * to translate the relevant functions into PHP and release them under
1543 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1544 * and Adar II is 14. In a non-leap year, Adar is 6.
1550 private static function tsToHebrew( $ts ) {
1552 $year = substr( $ts, 0, 4 );
1553 $month = substr( $ts, 4, 2 );
1554 $day = substr( $ts, 6, 2 );
1556 # Calculate Hebrew year
1557 $hebrewYear = $year +
3760;
1559 # Month number when September = 1, August = 12
1561 if ( $month > 12 ) {
1568 # Calculate day of year from 1 September
1570 for ( $i = 1; $i < $month; $i++
) {
1574 # Check if the year is leap
1575 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1578 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1585 # Calculate the start of the Hebrew year
1586 $start = self
::hebrewYearStart( $hebrewYear );
1588 # Calculate next year's start
1589 if ( $dayOfYear <= $start ) {
1590 # Day is before the start of the year - it is the previous year
1592 $nextStart = $start;
1596 # Add days since previous year's 1 September
1598 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1602 # Start of the new (previous) year
1603 $start = self
::hebrewYearStart( $hebrewYear );
1606 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1609 # Calculate Hebrew day of year
1610 $hebrewDayOfYear = $dayOfYear - $start;
1612 # Difference between year's days
1613 $diff = $nextStart - $start;
1614 # Add 12 (or 13 for leap years) days to ignore the difference between
1615 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1616 # difference is only about the year type
1617 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1623 # Check the year pattern, and is leap year
1624 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1625 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1626 # and non-leap years
1627 $yearPattern = $diff %
30;
1628 # Check if leap year
1629 $isLeap = $diff >= 30;
1631 # Calculate day in the month from number of day in the Hebrew year
1632 # Don't check Adar - if the day is not in Adar, we will stop before;
1633 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1634 $hebrewDay = $hebrewDayOfYear;
1637 while ( $hebrewMonth <= 12 ) {
1638 # Calculate days in this month
1639 if ( $isLeap && $hebrewMonth == 6 ) {
1640 # Adar in a leap year
1642 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1644 if ( $hebrewDay <= $days ) {
1648 # Subtract the days of Adar I
1649 $hebrewDay -= $days;
1652 if ( $hebrewDay <= $days ) {
1658 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1659 # Cheshvan in a complete year (otherwise as the rule below)
1661 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1662 # Kislev in an incomplete year (otherwise as the rule below)
1665 # Odd months have 30 days, even have 29
1666 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1668 if ( $hebrewDay <= $days ) {
1669 # In the current month
1672 # Subtract the days of the current month
1673 $hebrewDay -= $days;
1674 # Try in the next month
1679 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1683 * This calculates the Hebrew year start, as days since 1 September.
1684 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1685 * Used for Hebrew date.
1691 private static function hebrewYearStart( $year ) {
1692 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1693 $b = intval( ( $year - 1 ) %
4 );
1694 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1698 $Mar = intval( $m );
1704 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1705 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1707 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1709 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1713 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1718 * Algorithm to convert Gregorian dates to Thai solar dates,
1719 * Minguo dates or Minguo dates.
1721 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1722 * http://en.wikipedia.org/wiki/Minguo_calendar
1723 * http://en.wikipedia.org/wiki/Japanese_era_name
1725 * @param $ts String: 14-character timestamp
1726 * @param $cName String: calender name
1727 * @return Array: converted year, month, day
1729 private static function tsToYear( $ts, $cName ) {
1730 $gy = substr( $ts, 0, 4 );
1731 $gm = substr( $ts, 4, 2 );
1732 $gd = substr( $ts, 6, 2 );
1734 if ( !strcmp( $cName, 'thai' ) ) {
1736 # Add 543 years to the Gregorian calendar
1737 # Months and days are identical
1738 $gy_offset = $gy +
543;
1739 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1741 # Deduct 1911 years from the Gregorian calendar
1742 # Months and days are identical
1743 $gy_offset = $gy - 1911;
1744 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1745 # Nengō dates up to Meiji period
1746 # Deduct years from the Gregorian calendar
1747 # depending on the nengo periods
1748 # Months and days are identical
1749 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1751 $gy_gannen = $gy - 1868 +
1;
1752 $gy_offset = $gy_gannen;
1753 if ( $gy_gannen == 1 ) {
1756 $gy_offset = '明治' . $gy_offset;
1758 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1759 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1760 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1761 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1762 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1765 $gy_gannen = $gy - 1912 +
1;
1766 $gy_offset = $gy_gannen;
1767 if ( $gy_gannen == 1 ) {
1770 $gy_offset = '大正' . $gy_offset;
1772 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1773 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1774 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1777 $gy_gannen = $gy - 1926 +
1;
1778 $gy_offset = $gy_gannen;
1779 if ( $gy_gannen == 1 ) {
1782 $gy_offset = '昭和' . $gy_offset;
1785 $gy_gannen = $gy - 1989 +
1;
1786 $gy_offset = $gy_gannen;
1787 if ( $gy_gannen == 1 ) {
1790 $gy_offset = '平成' . $gy_offset;
1796 return array( $gy_offset, $gm, $gd );
1800 * Roman number formatting up to 10000
1806 static function romanNumeral( $num ) {
1807 static $table = array(
1808 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1809 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1810 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1811 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1814 $num = intval( $num );
1815 if ( $num > 10000 ||
$num <= 0 ) {
1820 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1821 if ( $num >= $pow10 ) {
1822 $s .= $table[$i][(int)floor( $num / $pow10 )];
1824 $num = $num %
$pow10;
1830 * Hebrew Gematria number formatting up to 9999
1836 static function hebrewNumeral( $num ) {
1837 static $table = array(
1838 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1839 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1840 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1841 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1844 $num = intval( $num );
1845 if ( $num > 9999 ||
$num <= 0 ) {
1850 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1851 if ( $num >= $pow10 ) {
1852 if ( $num == 15 ||
$num == 16 ) {
1853 $s .= $table[0][9] . $table[0][$num - 9];
1856 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1857 if ( $pow10 == 1000 ) {
1862 $num = $num %
$pow10;
1864 if ( strlen( $s ) == 2 ) {
1867 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1868 $str .= substr( $s, strlen( $s ) - 2, 2 );
1870 $start = substr( $str, 0, strlen( $str ) - 2 );
1871 $end = substr( $str, strlen( $str ) - 2 );
1874 $str = $start . 'ך';
1877 $str = $start . 'ם';
1880 $str = $start . 'ן';
1883 $str = $start . 'ף';
1886 $str = $start . 'ץ';
1893 * Used by date() and time() to adjust the time output.
1895 * @param $ts Int the time in date('YmdHis') format
1896 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1897 * get user timecorrection setting)
1900 function userAdjust( $ts, $tz = false ) {
1901 global $wgUser, $wgLocalTZoffset;
1903 if ( $tz === false ) {
1904 $tz = $wgUser->getOption( 'timecorrection' );
1907 $data = explode( '|', $tz, 3 );
1909 if ( $data[0] == 'ZoneInfo' ) {
1910 wfSuppressWarnings();
1911 $userTZ = timezone_open( $data[2] );
1912 wfRestoreWarnings();
1913 if ( $userTZ !== false ) {
1914 $date = date_create( $ts, timezone_open( 'UTC' ) );
1915 date_timezone_set( $date, $userTZ );
1916 $date = date_format( $date, 'YmdHis' );
1919 # Unrecognized timezone, default to 'Offset' with the stored offset.
1920 $data[0] = 'Offset';
1924 if ( $data[0] == 'System' ||
$tz == '' ) {
1925 # Global offset in minutes.
1926 if ( isset( $wgLocalTZoffset ) ) {
1927 $minDiff = $wgLocalTZoffset;
1929 } elseif ( $data[0] == 'Offset' ) {
1930 $minDiff = intval( $data[1] );
1932 $data = explode( ':', $tz );
1933 if ( count( $data ) == 2 ) {
1934 $data[0] = intval( $data[0] );
1935 $data[1] = intval( $data[1] );
1936 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1937 if ( $data[0] < 0 ) {
1938 $minDiff = -$minDiff;
1941 $minDiff = intval( $data[0] ) * 60;
1945 # No difference ? Return time unchanged
1946 if ( 0 == $minDiff ) {
1950 wfSuppressWarnings(); // E_STRICT system time bitching
1951 # Generate an adjusted date; take advantage of the fact that mktime
1952 # will normalize out-of-range values so we don't have to split $minDiff
1953 # into hours and minutes.
1955 (int)substr( $ts, 8, 2 ) ), # Hours
1956 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1957 (int)substr( $ts, 12, 2 ), # Seconds
1958 (int)substr( $ts, 4, 2 ), # Month
1959 (int)substr( $ts, 6, 2 ), # Day
1960 (int)substr( $ts, 0, 4 ) ); # Year
1962 $date = date( 'YmdHis', $t );
1963 wfRestoreWarnings();
1969 * This is meant to be used by time(), date(), and timeanddate() to get
1970 * the date preference they're supposed to use, it should be used in
1974 * function timeanddate([...], $format = true) {
1975 * $datePreference = $this->dateFormat($format);
1980 * @param $usePrefs Mixed: if true, the user's preference is used
1981 * if false, the site/language default is used
1982 * if int/string, assumed to be a format.
1985 function dateFormat( $usePrefs = true ) {
1988 if ( is_bool( $usePrefs ) ) {
1990 $datePreference = $wgUser->getDatePreference();
1992 $datePreference = (string)User
::getDefaultOption( 'date' );
1995 $datePreference = (string)$usePrefs;
1999 if ( $datePreference == '' ) {
2003 return $datePreference;
2007 * Get a format string for a given type and preference
2008 * @param $type string May be date, time or both
2009 * @param $pref string The format name as it appears in Messages*.php
2011 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2015 function getDateFormatString( $type, $pref ) {
2016 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
2017 if ( $pref == 'default' ) {
2018 $pref = $this->getDefaultDateFormat();
2019 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2021 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2023 if ( $type === 'pretty' && $df === null ) {
2024 $df = $this->getDateFormatString( 'date', $pref );
2027 if ( $df === null ) {
2028 $pref = $this->getDefaultDateFormat();
2029 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2032 $this->dateFormatStrings
[$type][$pref] = $df;
2034 return $this->dateFormatStrings
[$type][$pref];
2038 * @param $ts Mixed: the time format which needs to be turned into a
2039 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2040 * @param $adj Bool: whether to adjust the time output according to the
2041 * user configured offset ($timecorrection)
2042 * @param $format Mixed: true to use user's date format preference
2043 * @param $timecorrection String|bool the time offset as returned by
2044 * validateTimeZone() in Special:Preferences
2047 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2048 $ts = wfTimestamp( TS_MW
, $ts );
2050 $ts = $this->userAdjust( $ts, $timecorrection );
2052 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2053 return $this->sprintfDate( $df, $ts );
2057 * @param $ts Mixed: the time format which needs to be turned into a
2058 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2059 * @param $adj Bool: whether to adjust the time output according to the
2060 * user configured offset ($timecorrection)
2061 * @param $format Mixed: true to use user's date format preference
2062 * @param $timecorrection String|bool the time offset as returned by
2063 * validateTimeZone() in Special:Preferences
2066 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2067 $ts = wfTimestamp( TS_MW
, $ts );
2069 $ts = $this->userAdjust( $ts, $timecorrection );
2071 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2072 return $this->sprintfDate( $df, $ts );
2076 * @param $ts Mixed: the time format which needs to be turned into a
2077 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2078 * @param $adj Bool: whether to adjust the time output according to the
2079 * user configured offset ($timecorrection)
2080 * @param $format Mixed: what format to return, if it's false output the
2081 * default one (default true)
2082 * @param $timecorrection String|bool the time offset as returned by
2083 * validateTimeZone() in Special:Preferences
2086 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2087 $ts = wfTimestamp( TS_MW
, $ts );
2089 $ts = $this->userAdjust( $ts, $timecorrection );
2091 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2092 return $this->sprintfDate( $df, $ts );
2096 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2100 * @param integer $seconds The amount of seconds.
2101 * @param array $chosenIntervals The intervals to enable.
2105 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2106 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2108 $segments = array();
2110 foreach ( $intervals as $intervalName => $intervalValue ) {
2111 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2112 // duration-years, duration-decades, duration-centuries, duration-millennia
2113 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2114 $segments[] = $message->inLanguage( $this )->escaped();
2117 return $this->listToText( $segments );
2121 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2122 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2126 * @param integer $seconds The amount of seconds.
2127 * @param array $chosenIntervals The intervals to enable.
2131 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2132 if ( empty( $chosenIntervals ) ) {
2133 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2136 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2137 $sortedNames = array_keys( $intervals );
2138 $smallestInterval = array_pop( $sortedNames );
2140 $segments = array();
2142 foreach ( $intervals as $name => $length ) {
2143 $value = floor( $seconds / $length );
2145 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2146 $seconds -= $value * $length;
2147 $segments[$name] = $value;
2155 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2157 * @param $type String: can be 'date', 'time' or 'both'
2158 * @param $ts Mixed: the time format which needs to be turned into a
2159 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2160 * @param $user User object used to get preferences for timezone and format
2161 * @param $options Array, can contain the following keys:
2162 * - 'timecorrection': time correction, can have the following values:
2163 * - true: use user's preference
2164 * - false: don't use time correction
2165 * - integer: value of time correction in minutes
2166 * - 'format': format to use, can have the following values:
2167 * - true: use user's preference
2168 * - false: use default preference
2169 * - string: format to use
2173 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2174 $ts = wfTimestamp( TS_MW
, $ts );
2175 $options +
= array( 'timecorrection' => true, 'format' => true );
2176 if ( $options['timecorrection'] !== false ) {
2177 if ( $options['timecorrection'] === true ) {
2178 $offset = $user->getOption( 'timecorrection' );
2180 $offset = $options['timecorrection'];
2182 $ts = $this->userAdjust( $ts, $offset );
2184 if ( $options['format'] === true ) {
2185 $format = $user->getDatePreference();
2187 $format = $options['format'];
2189 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2190 return $this->sprintfDate( $df, $ts );
2194 * Get the formatted date for the given timestamp and formatted for
2197 * @param $ts Mixed: the time format which needs to be turned into a
2198 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2199 * @param $user User object used to get preferences for timezone and format
2200 * @param $options Array, can contain the following keys:
2201 * - 'timecorrection': time correction, can have the following values:
2202 * - true: use user's preference
2203 * - false: don't use time correction
2204 * - integer: value of time correction in minutes
2205 * - 'format': format to use, can have the following values:
2206 * - true: use user's preference
2207 * - false: use default preference
2208 * - string: format to use
2212 public function userDate( $ts, User
$user, array $options = array() ) {
2213 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2217 * Get the formatted time for the given timestamp and formatted for
2220 * @param $ts Mixed: the time format which needs to be turned into a
2221 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2222 * @param $user User object used to get preferences for timezone and format
2223 * @param $options Array, can contain the following keys:
2224 * - 'timecorrection': time correction, can have the following values:
2225 * - true: use user's preference
2226 * - false: don't use time correction
2227 * - integer: value of time correction in minutes
2228 * - 'format': format to use, can have the following values:
2229 * - true: use user's preference
2230 * - false: use default preference
2231 * - string: format to use
2235 public function userTime( $ts, User
$user, array $options = array() ) {
2236 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2240 * Get the formatted date and time for the given timestamp and formatted for
2243 * @param $ts Mixed: the time format which needs to be turned into a
2244 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2245 * @param $user User object used to get preferences for timezone and format
2246 * @param $options Array, can contain the following keys:
2247 * - 'timecorrection': time correction, can have the following values:
2248 * - true: use user's preference
2249 * - false: don't use time correction
2250 * - integer: value of time correction in minutes
2251 * - 'format': format to use, can have the following values:
2252 * - true: use user's preference
2253 * - false: use default preference
2254 * - string: format to use
2258 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2259 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2263 * Convert an MWTimestamp into a pretty human-readable timestamp using
2264 * the given user preferences and relative base time.
2266 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2267 * on your timestamp object, which will then call this function. Calling
2268 * this function directly will cause hooks to be skipped over.
2270 * @see MWTimestamp::getHumanTimestamp
2271 * @param MWTimestamp $ts Timestamp to prettify
2272 * @param MWTimestamp $relativeTo Base timestamp
2273 * @param User $user User preferences to use
2274 * @return string Human timestamp
2277 public function getHumanTimestamp( MWTimestamp
$ts, MWTimestamp
$relativeTo, User
$user ) {
2278 $diff = $ts->diff( $relativeTo );
2279 $diffDay = (bool)( (int)$ts->timestamp
->format( 'w' ) - (int)$relativeTo->timestamp
->format( 'w' ) );
2280 $days = $diff->days ?
: (int)$diffDay;
2281 if ( $diff->invert ||
$days > 5 && $ts->timestamp
->format( 'Y' ) !== $relativeTo->timestamp
->format( 'Y' ) ) {
2282 // Timestamps are in different years: use full timestamp
2283 // Also do full timestamp for future dates
2285 * @FIXME Add better handling of future timestamps.
2287 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?
: 'default' );
2288 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2289 } elseif ( $days > 5 ) {
2290 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2291 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?
: 'default' );
2292 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) );
2293 } elseif ( $days > 1 ) {
2294 // Timestamp within the past week: show the day of the week and time
2295 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2296 $weekday = self
::$mWeekdayMsgs[$ts->timestamp
->format( 'w' )];
2298 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2299 $ts = wfMessage( "$weekday-at" )
2300 ->inLanguage( $this )
2301 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2303 } elseif ( $days == 1 ) {
2304 // Timestamp was yesterday: say 'yesterday' and the time.
2305 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2306 $ts = wfMessage( 'yesterday-at' )
2307 ->inLanguage( $this )
2308 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2310 } elseif ( $diff->h
> 1 ||
$diff->h
== 1 && $diff->i
> 30 ) {
2311 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2312 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?
: 'default' );
2313 $ts = wfMessage( 'today-at' )
2314 ->inLanguage( $this )
2315 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW
) ) )
2318 // From here on in, the timestamp was soon enough ago so that we can simply say
2319 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2320 } elseif ( $diff->h
== 1 ) {
2321 // Less than 90 minutes, but more than an hour ago.
2322 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2323 } elseif ( $diff->i
>= 1 ) {
2324 // A few minutes ago.
2325 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i
)->text();
2326 } elseif ( $diff->s
>= 30 ) {
2327 // Less than a minute, but more than 30 sec ago.
2328 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s
)->text();
2330 // Less than 30 seconds ago.
2331 $ts = wfMessage( 'just-now' )->text();
2338 * @param $key string
2339 * @return array|null
2341 function getMessage( $key ) {
2342 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2348 function getAllMessages() {
2349 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2358 function iconv( $in, $out, $string ) {
2359 # This is a wrapper for iconv in all languages except esperanto,
2360 # which does some nasty x-conversions beforehand
2362 # Even with //IGNORE iconv can whine about illegal characters in
2363 # *input* string. We just ignore those too.
2364 # REF: http://bugs.php.net/bug.php?id=37166
2365 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2366 wfSuppressWarnings();
2367 $text = iconv( $in, $out . '//IGNORE', $string );
2368 wfRestoreWarnings();
2372 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2375 * @param $matches array
2376 * @return mixed|string
2378 function ucwordbreaksCallbackAscii( $matches ) {
2379 return $this->ucfirst( $matches[1] );
2383 * @param $matches array
2386 function ucwordbreaksCallbackMB( $matches ) {
2387 return mb_strtoupper( $matches[0] );
2391 * @param $matches array
2394 function ucCallback( $matches ) {
2395 list( $wikiUpperChars ) = self
::getCaseMaps();
2396 return strtr( $matches[1], $wikiUpperChars );
2400 * @param $matches array
2403 function lcCallback( $matches ) {
2404 list( , $wikiLowerChars ) = self
::getCaseMaps();
2405 return strtr( $matches[1], $wikiLowerChars );
2409 * @param $matches array
2412 function ucwordsCallbackMB( $matches ) {
2413 return mb_strtoupper( $matches[0] );
2417 * @param $matches array
2420 function ucwordsCallbackWiki( $matches ) {
2421 list( $wikiUpperChars ) = self
::getCaseMaps();
2422 return strtr( $matches[0], $wikiUpperChars );
2426 * Make a string's first character uppercase
2428 * @param $str string
2432 function ucfirst( $str ) {
2434 if ( $o < 96 ) { // if already uppercase...
2436 } elseif ( $o < 128 ) {
2437 return ucfirst( $str ); // use PHP's ucfirst()
2439 // fall back to more complex logic in case of multibyte strings
2440 return $this->uc( $str, true );
2445 * Convert a string to uppercase
2447 * @param $str string
2448 * @param $first bool
2452 function uc( $str, $first = false ) {
2453 if ( function_exists( 'mb_strtoupper' ) ) {
2455 if ( $this->isMultibyte( $str ) ) {
2456 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2458 return ucfirst( $str );
2461 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2464 if ( $this->isMultibyte( $str ) ) {
2465 $x = $first ?
'^' : '';
2466 return preg_replace_callback(
2467 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2468 array( $this, 'ucCallback' ),
2472 return $first ?
ucfirst( $str ) : strtoupper( $str );
2478 * @param $str string
2479 * @return mixed|string
2481 function lcfirst( $str ) {
2484 return strval( $str );
2485 } elseif ( $o >= 128 ) {
2486 return $this->lc( $str, true );
2487 } elseif ( $o > 96 ) {
2490 $str[0] = strtolower( $str[0] );
2496 * @param $str string
2497 * @param $first bool
2498 * @return mixed|string
2500 function lc( $str, $first = false ) {
2501 if ( function_exists( 'mb_strtolower' ) ) {
2503 if ( $this->isMultibyte( $str ) ) {
2504 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2506 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2509 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2512 if ( $this->isMultibyte( $str ) ) {
2513 $x = $first ?
'^' : '';
2514 return preg_replace_callback(
2515 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2516 array( $this, 'lcCallback' ),
2520 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2526 * @param $str string
2529 function isMultibyte( $str ) {
2530 return (bool)preg_match( '/[\x80-\xff]/', $str );
2534 * @param $str string
2535 * @return mixed|string
2537 function ucwords( $str ) {
2538 if ( $this->isMultibyte( $str ) ) {
2539 $str = $this->lc( $str );
2541 // regexp to find first letter in each word (i.e. after each space)
2542 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2544 // function to use to capitalize a single char
2545 if ( function_exists( 'mb_strtoupper' ) ) {
2546 return preg_replace_callback(
2548 array( $this, 'ucwordsCallbackMB' ),
2552 return preg_replace_callback(
2554 array( $this, 'ucwordsCallbackWiki' ),
2559 return ucwords( strtolower( $str ) );
2564 * capitalize words at word breaks
2566 * @param $str string
2569 function ucwordbreaks( $str ) {
2570 if ( $this->isMultibyte( $str ) ) {
2571 $str = $this->lc( $str );
2573 // since \b doesn't work for UTF-8, we explicitely define word break chars
2574 $breaks = "[ \-\(\)\}\{\.,\?!]";
2576 // find first letter after word break
2577 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2579 if ( function_exists( 'mb_strtoupper' ) ) {
2580 return preg_replace_callback(
2582 array( $this, 'ucwordbreaksCallbackMB' ),
2586 return preg_replace_callback(
2588 array( $this, 'ucwordsCallbackWiki' ),
2593 return preg_replace_callback(
2594 '/\b([\w\x80-\xff]+)\b/',
2595 array( $this, 'ucwordbreaksCallbackAscii' ),
2602 * Return a case-folded representation of $s
2604 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2605 * and $s2 are the same except for the case of their characters. It is not
2606 * necessary for the value returned to make sense when displayed.
2608 * Do *not* perform any other normalisation in this function. If a caller
2609 * uses this function when it should be using a more general normalisation
2610 * function, then fix the caller.
2616 function caseFold( $s ) {
2617 return $this->uc( $s );
2624 function checkTitleEncoding( $s ) {
2625 if ( is_array( $s ) ) {
2626 throw new MWException( 'Given array to checkTitleEncoding.' );
2628 if ( StringUtils
::isUtf8( $s ) ) {
2632 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2638 function fallback8bitEncoding() {
2639 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2643 * Most writing systems use whitespace to break up words.
2644 * Some languages such as Chinese don't conventionally do this,
2645 * which requires special handling when breaking up words for
2650 function hasWordBreaks() {
2655 * Some languages such as Chinese require word segmentation,
2656 * Specify such segmentation when overridden in derived class.
2658 * @param $string String
2661 function segmentByWord( $string ) {
2666 * Some languages have special punctuation need to be normalized.
2667 * Make such changes here.
2669 * @param $string String
2672 function normalizeForSearch( $string ) {
2673 return self
::convertDoubleWidth( $string );
2677 * convert double-width roman characters to single-width.
2678 * range: ff00-ff5f ~= 0020-007f
2680 * @param $string string
2684 protected static function convertDoubleWidth( $string ) {
2685 static $full = null;
2686 static $half = null;
2688 if ( $full === null ) {
2689 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2690 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2691 $full = str_split( $fullWidth, 3 );
2692 $half = str_split( $halfWidth );
2695 $string = str_replace( $full, $half, $string );
2700 * @param $string string
2701 * @param $pattern string
2704 protected static function insertSpace( $string, $pattern ) {
2705 $string = preg_replace( $pattern, " $1 ", $string );
2706 $string = preg_replace( '/ +/', ' ', $string );
2711 * @param $termsArray array
2714 function convertForSearchResult( $termsArray ) {
2715 # some languages, e.g. Chinese, need to do a conversion
2716 # in order for search results to be displayed correctly
2721 * Get the first character of a string.
2726 function firstChar( $s ) {
2729 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2730 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2735 if ( isset( $matches[1] ) ) {
2736 if ( strlen( $matches[1] ) != 3 ) {
2740 // Break down Hangul syllables to grab the first jamo
2741 $code = utf8ToCodepoint( $matches[1] );
2742 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2744 } elseif ( $code < 0xb098 ) {
2745 return "\xe3\x84\xb1";
2746 } elseif ( $code < 0xb2e4 ) {
2747 return "\xe3\x84\xb4";
2748 } elseif ( $code < 0xb77c ) {
2749 return "\xe3\x84\xb7";
2750 } elseif ( $code < 0xb9c8 ) {
2751 return "\xe3\x84\xb9";
2752 } elseif ( $code < 0xbc14 ) {
2753 return "\xe3\x85\x81";
2754 } elseif ( $code < 0xc0ac ) {
2755 return "\xe3\x85\x82";
2756 } elseif ( $code < 0xc544 ) {
2757 return "\xe3\x85\x85";
2758 } elseif ( $code < 0xc790 ) {
2759 return "\xe3\x85\x87";
2760 } elseif ( $code < 0xcc28 ) {
2761 return "\xe3\x85\x88";
2762 } elseif ( $code < 0xce74 ) {
2763 return "\xe3\x85\x8a";
2764 } elseif ( $code < 0xd0c0 ) {
2765 return "\xe3\x85\x8b";
2766 } elseif ( $code < 0xd30c ) {
2767 return "\xe3\x85\x8c";
2768 } elseif ( $code < 0xd558 ) {
2769 return "\xe3\x85\x8d";
2771 return "\xe3\x85\x8e";
2778 function initEncoding() {
2779 # Some languages may have an alternate char encoding option
2780 # (Esperanto X-coding, Japanese furigana conversion, etc)
2781 # If this language is used as the primary content language,
2782 # an override to the defaults can be set here on startup.
2789 function recodeForEdit( $s ) {
2790 # For some languages we'll want to explicitly specify
2791 # which characters make it into the edit box raw
2792 # or are converted in some way or another.
2793 global $wgEditEncoding;
2794 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2797 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2805 function recodeInput( $s ) {
2806 # Take the previous into account.
2807 global $wgEditEncoding;
2808 if ( $wgEditEncoding != '' ) {
2809 $enc = $wgEditEncoding;
2813 if ( $enc == 'UTF-8' ) {
2816 return $this->iconv( $enc, 'UTF-8', $s );
2821 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2822 * also cleans up certain backwards-compatible sequences, converting them
2823 * to the modern Unicode equivalent.
2825 * This is language-specific for performance reasons only.
2831 function normalize( $s ) {
2832 global $wgAllUnicodeFixes;
2833 $s = UtfNormal
::cleanUp( $s );
2834 if ( $wgAllUnicodeFixes ) {
2835 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2836 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2843 * Transform a string using serialized data stored in the given file (which
2844 * must be in the serialized subdirectory of $IP). The file contains pairs
2845 * mapping source characters to destination characters.
2847 * The data is cached in process memory. This will go faster if you have the
2848 * FastStringSearch extension.
2850 * @param $file string
2851 * @param $string string
2853 * @throws MWException
2856 function transformUsingPairFile( $file, $string ) {
2857 if ( !isset( $this->transformData
[$file] ) ) {
2858 $data = wfGetPrecompiledData( $file );
2859 if ( $data === false ) {
2860 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2862 $this->transformData
[$file] = new ReplacementArray( $data );
2864 return $this->transformData
[$file]->replace( $string );
2868 * For right-to-left language support
2873 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2877 * Return the correct HTML 'dir' attribute value for this language.
2881 return $this->isRTL() ?
'rtl' : 'ltr';
2885 * Return 'left' or 'right' as appropriate alignment for line-start
2886 * for this language's text direction.
2888 * Should be equivalent to CSS3 'start' text-align value....
2892 function alignStart() {
2893 return $this->isRTL() ?
'right' : 'left';
2897 * Return 'right' or 'left' as appropriate alignment for line-end
2898 * for this language's text direction.
2900 * Should be equivalent to CSS3 'end' text-align value....
2904 function alignEnd() {
2905 return $this->isRTL() ?
'left' : 'right';
2909 * A hidden direction mark (LRM or RLM), depending on the language direction.
2910 * Unlike getDirMark(), this function returns the character as an HTML entity.
2911 * This function should be used when the output is guaranteed to be HTML,
2912 * because it makes the output HTML source code more readable. When
2913 * the output is plain text or can be escaped, getDirMark() should be used.
2915 * @param $opposite Boolean Get the direction mark opposite to your language
2919 function getDirMarkEntity( $opposite = false ) {
2921 return $this->isRTL() ?
'‎' : '‏';
2923 return $this->isRTL() ?
'‏' : '‎';
2927 * A hidden direction mark (LRM or RLM), depending on the language direction.
2928 * This function produces them as invisible Unicode characters and
2929 * the output may be hard to read and debug, so it should only be used
2930 * when the output is plain text or can be escaped. When the output is
2931 * HTML, use getDirMarkEntity() instead.
2933 * @param $opposite Boolean Get the direction mark opposite to your language
2936 function getDirMark( $opposite = false ) {
2937 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2938 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2940 return $this->isRTL() ?
$lrm : $rlm;
2942 return $this->isRTL() ?
$rlm : $lrm;
2948 function capitalizeAllNouns() {
2949 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2953 * An arrow, depending on the language direction.
2955 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2958 function getArrow( $direction = 'forwards' ) {
2959 switch ( $direction ) {
2961 return $this->isRTL() ?
'←' : '→';
2963 return $this->isRTL() ?
'→' : '←';
2976 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2980 function linkPrefixExtension() {
2981 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2985 * Get all magic words from cache.
2988 function getMagicWords() {
2989 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2993 * Run the LanguageGetMagic hook once.
2995 protected function doMagicHook() {
2996 if ( $this->mMagicHookDone
) {
2999 $this->mMagicHookDone
= true;
3000 wfProfileIn( 'LanguageGetMagic' );
3001 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
3002 wfProfileOut( 'LanguageGetMagic' );
3006 * Fill a MagicWord object with data from here
3010 function getMagic( $mw ) {
3011 // Saves a function call
3012 if ( ! $this->mMagicHookDone
) {
3013 $this->doMagicHook();
3016 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
3017 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
3019 $rawEntry = self
::$dataCache->getSubitem(
3020 $this->mCode
, 'magicWords', $mw->mId
);
3023 if ( !is_array( $rawEntry ) ) {
3024 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3026 $mw->mCaseSensitive
= $rawEntry[0];
3027 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
3032 * Add magic words to the extension array
3034 * @param $newWords array
3036 function addMagicWordsByLang( $newWords ) {
3037 $fallbackChain = $this->getFallbackLanguages();
3038 $fallbackChain = array_reverse( $fallbackChain );
3039 foreach ( $fallbackChain as $code ) {
3040 if ( isset( $newWords[$code] ) ) {
3041 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
3047 * Get special page names, as an associative array
3048 * case folded alias => real name
3050 function getSpecialPageAliases() {
3051 // Cache aliases because it may be slow to load them
3052 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
3054 $this->mExtendedSpecialPageAliases
=
3055 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
3056 wfRunHooks( 'LanguageGetSpecialPageAliases',
3057 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
3060 return $this->mExtendedSpecialPageAliases
;
3064 * Italic is unsuitable for some languages
3066 * @param $text String: the text to be emphasized.
3069 function emphasize( $text ) {
3070 return "<em>$text</em>";
3074 * Normally we output all numbers in plain en_US style, that is
3075 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3076 * point twohundredthirtyfive. However this is not suitable for all
3077 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3078 * Icelandic just want to use commas instead of dots, and dots instead
3079 * of commas like "293.291,235".
3081 * An example of this function being called:
3083 * wfMessage( 'message' )->numParams( $num )->text()
3086 * See $separatorTransformTable on MessageIs.php for
3087 * the , => . and . => , implementation.
3089 * @todo check if it's viable to use localeconv() for the decimal
3091 * @param $number Mixed: the string to be formatted, should be an integer
3092 * or a floating point number.
3093 * @param $nocommafy Bool: set to true for special numbers like dates
3096 public function formatNum( $number, $nocommafy = false ) {
3097 global $wgTranslateNumerals;
3098 if ( !$nocommafy ) {
3099 $number = $this->commafy( $number );
3100 $s = $this->separatorTransformTable();
3102 $number = strtr( $number, $s );
3106 if ( $wgTranslateNumerals ) {
3107 $s = $this->digitTransformTable();
3109 $number = strtr( $number, $s );
3117 * Front-end for non-commafied formatNum
3119 * @param mixed $number the string to be formatted, should be an integer
3120 * or a floating point number.
3124 public function formatNumNoSeparators( $number ) {
3125 return $this->formatNum( $number, true );
3129 * @param $number string
3132 function parseFormattedNumber( $number ) {
3133 $s = $this->digitTransformTable();
3135 $number = strtr( $number, array_flip( $s ) );
3138 $s = $this->separatorTransformTable();
3140 $number = strtr( $number, array_flip( $s ) );
3143 $number = strtr( $number, array( ',' => '' ) );
3148 * Adds commas to a given number
3150 * @param $number mixed
3153 function commafy( $number ) {
3154 $digitGroupingPattern = $this->digitGroupingPattern();
3155 if ( $number === null ) {
3159 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3160 // default grouping is at thousands, use the same for ###,###,### pattern too.
3161 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3163 // Ref: http://cldr.unicode.org/translation/number-patterns
3165 if ( intval( $number ) < 0 ) {
3166 // For negative numbers apply the algorithm like positive number and add sign.
3168 $number = substr( $number, 1 );
3170 $integerPart = array();
3171 $decimalPart = array();
3172 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3173 preg_match( "/\d+/", $number, $integerPart );
3174 preg_match( "/\.\d*/", $number, $decimalPart );
3175 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0] : "";
3176 if ( $groupedNumber === $number ) {
3177 // the string does not have any number part. Eg: .12345
3178 return $sign . $groupedNumber;
3180 $start = $end = strlen( $integerPart[0] );
3181 while ( $start > 0 ) {
3182 $match = $matches[0][$numMatches - 1];
3183 $matchLen = strlen( $match );
3184 $start = $end - $matchLen;
3188 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3190 if ( $numMatches > 1 ) {
3191 // use the last pattern for the rest of the number
3195 $groupedNumber = "," . $groupedNumber;
3198 return $sign . $groupedNumber;
3205 function digitGroupingPattern() {
3206 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3212 function digitTransformTable() {
3213 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3219 function separatorTransformTable() {
3220 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3224 * Take a list of strings and build a locale-friendly comma-separated
3225 * list, using the local comma-separator message.
3226 * The last two strings are chained with an "and".
3227 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3232 function listToText( array $l ) {
3233 $m = count( $l ) - 1;
3238 $and = $this->getMessageFromDB( 'and' );
3239 $space = $this->getMessageFromDB( 'word-separator' );
3241 $comma = $this->getMessageFromDB( 'comma-separator' );
3245 for ( $i = $m - 1; $i >= 0; $i-- ) {
3246 if ( $i == $m - 1 ) {
3247 $s = $l[$i] . $and . $space . $s;
3249 $s = $l[$i] . $comma . $s;
3256 * Take a list of strings and build a locale-friendly comma-separated
3257 * list, using the local comma-separator message.
3258 * @param $list array of strings to put in a comma list
3261 function commaList( array $list ) {
3263 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3269 * Take a list of strings and build a locale-friendly semicolon-separated
3270 * list, using the local semicolon-separator message.
3271 * @param $list array of strings to put in a semicolon list
3274 function semicolonList( array $list ) {
3276 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3282 * Same as commaList, but separate it with the pipe instead.
3283 * @param $list array of strings to put in a pipe list
3286 function pipeList( array $list ) {
3288 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3294 * Truncate a string to a specified length in bytes, appending an optional
3295 * string (e.g. for ellipses)
3297 * The database offers limited byte lengths for some columns in the database;
3298 * multi-byte character sets mean we need to ensure that only whole characters
3299 * are included, otherwise broken characters can be passed to the user
3301 * If $length is negative, the string will be truncated from the beginning
3303 * @param $string String to truncate
3304 * @param $length Int: maximum length (including ellipses)
3305 * @param $ellipsis String to append to the truncated text
3306 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3307 * $adjustLength was introduced in 1.18, before that behaved as if false.
3310 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3311 # Use the localized ellipsis character
3312 if ( $ellipsis == '...' ) {
3313 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3315 # Check if there is no need to truncate
3316 if ( $length == 0 ) {
3317 return $ellipsis; // convention
3318 } elseif ( strlen( $string ) <= abs( $length ) ) {
3319 return $string; // no need to truncate
3321 $stringOriginal = $string;
3322 # If ellipsis length is >= $length then we can't apply $adjustLength
3323 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3324 $string = $ellipsis; // this can be slightly unexpected
3325 # Otherwise, truncate and add ellipsis...
3327 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3328 if ( $length > 0 ) {
3329 $length -= $eLength;
3330 $string = substr( $string, 0, $length ); // xyz...
3331 $string = $this->removeBadCharLast( $string );
3332 $string = rtrim( $string );
3333 $string = $string . $ellipsis;
3335 $length +
= $eLength;
3336 $string = substr( $string, $length ); // ...xyz
3337 $string = $this->removeBadCharFirst( $string );
3338 $string = ltrim( $string );
3339 $string = $ellipsis . $string;
3342 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3343 # This check is *not* redundant if $adjustLength, due to the single case where
3344 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3345 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3348 return $stringOriginal;
3353 * Remove bytes that represent an incomplete Unicode character
3354 * at the end of string (e.g. bytes of the char are missing)
3356 * @param $string String
3359 protected function removeBadCharLast( $string ) {
3360 if ( $string != '' ) {
3361 $char = ord( $string[strlen( $string ) - 1] );
3363 if ( $char >= 0xc0 ) {
3364 # We got the first byte only of a multibyte char; remove it.
3365 $string = substr( $string, 0, -1 );
3366 } elseif ( $char >= 0x80 &&
3367 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3368 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3370 # We chopped in the middle of a character; remove it
3378 * Remove bytes that represent an incomplete Unicode character
3379 * at the start of string (e.g. bytes of the char are missing)
3381 * @param $string String
3384 protected function removeBadCharFirst( $string ) {
3385 if ( $string != '' ) {
3386 $char = ord( $string[0] );
3387 if ( $char >= 0x80 && $char < 0xc0 ) {
3388 # We chopped in the middle of a character; remove the whole thing
3389 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3396 * Truncate a string of valid HTML to a specified length in bytes,
3397 * appending an optional string (e.g. for ellipses), and return valid HTML
3399 * This is only intended for styled/linked text, such as HTML with
3400 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3401 * Also, this will not detect things like "display:none" CSS.
3403 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3405 * @param string $text HTML string to truncate
3406 * @param int $length (zero/positive) Maximum length (including ellipses)
3407 * @param string $ellipsis String to append to the truncated text
3410 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3411 # Use the localized ellipsis character
3412 if ( $ellipsis == '...' ) {
3413 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3415 # Check if there is clearly no need to truncate
3416 if ( $length <= 0 ) {
3417 return $ellipsis; // no text shown, nothing to format (convention)
3418 } elseif ( strlen( $text ) <= $length ) {
3419 return $text; // string short enough even *with* HTML (short-circuit)
3422 $dispLen = 0; // innerHTML legth so far
3423 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3424 $tagType = 0; // 0-open, 1-close
3425 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3426 $entityState = 0; // 0-not entity, 1-entity
3427 $tag = $ret = ''; // accumulated tag name, accumulated result string
3428 $openTags = array(); // open tag stack
3429 $maybeState = null; // possible truncation state
3431 $textLen = strlen( $text );
3432 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3433 for ( $pos = 0; true; ++
$pos ) {
3434 # Consider truncation once the display length has reached the maximim.
3435 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3436 # Check that we're not in the middle of a bracket/entity...
3437 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3438 if ( !$testingEllipsis ) {
3439 $testingEllipsis = true;
3440 # Save where we are; we will truncate here unless there turn out to
3441 # be so few remaining characters that truncation is not necessary.
3442 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3443 $maybeState = array( $ret, $openTags ); // save state
3445 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3446 # String in fact does need truncation, the truncation point was OK.
3447 list( $ret, $openTags ) = $maybeState; // reload state
3448 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3449 $ret .= $ellipsis; // add ellipsis
3453 if ( $pos >= $textLen ) {
3454 break; // extra iteration just for above checks
3457 # Read the next char...
3459 $lastCh = $pos ?
$text[$pos - 1] : '';
3460 $ret .= $ch; // add to result string
3462 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3463 $entityState = 0; // for bad HTML
3464 $bracketState = 1; // tag started (checking for backslash)
3465 } elseif ( $ch == '>' ) {
3466 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3467 $entityState = 0; // for bad HTML
3468 $bracketState = 0; // out of brackets
3469 } elseif ( $bracketState == 1 ) {
3471 $tagType = 1; // close tag (e.g. "</span>")
3473 $tagType = 0; // open tag (e.g. "<span>")
3476 $bracketState = 2; // building tag name
3477 } elseif ( $bracketState == 2 ) {
3481 // Name found (e.g. "<a href=..."), add on tag attributes...
3482 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3484 } elseif ( $bracketState == 0 ) {
3485 if ( $entityState ) {
3488 $dispLen++
; // entity is one displayed char
3491 if ( $neLength == 0 && !$maybeState ) {
3492 // Save state without $ch. We want to *hit* the first
3493 // display char (to get tags) but not *use* it if truncating.
3494 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3497 $entityState = 1; // entity found, (e.g. " ")
3499 $dispLen++
; // this char is displayed
3500 // Add the next $max display text chars after this in one swoop...
3501 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3502 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3503 $dispLen +
= $skipped;
3509 // Close the last tag if left unclosed by bad HTML
3510 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3511 while ( count( $openTags ) > 0 ) {
3512 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3518 * truncateHtml() helper function
3519 * like strcspn() but adds the skipped chars to $ret
3528 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3529 if ( $len === null ) {
3530 $len = -1; // -1 means "no limit" for strcspn
3531 } elseif ( $len < 0 ) {
3535 if ( $start < strlen( $text ) ) {
3536 $skipCount = strcspn( $text, $search, $start, $len );
3537 $ret .= substr( $text, $start, $skipCount );
3543 * truncateHtml() helper function
3544 * (a) push or pop $tag from $openTags as needed
3545 * (b) clear $tag value
3546 * @param &$tag string Current HTML tag name we are looking at
3547 * @param $tagType int (0-open tag, 1-close tag)
3548 * @param $lastCh string Character before the '>' that ended this tag
3549 * @param &$openTags array Open tag stack (not accounting for $tag)
3551 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3552 $tag = ltrim( $tag );
3554 if ( $tagType == 0 && $lastCh != '/' ) {
3555 $openTags[] = $tag; // tag opened (didn't close itself)
3556 } elseif ( $tagType == 1 ) {
3557 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3558 array_pop( $openTags ); // tag closed
3566 * Grammatical transformations, needed for inflected languages
3567 * Invoked by putting {{grammar:case|word}} in a message
3569 * @param $word string
3570 * @param $case string
3573 function convertGrammar( $word, $case ) {
3574 global $wgGrammarForms;
3575 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3576 return $wgGrammarForms[$this->getCode()][$case][$word];
3581 * Get the grammar forms for the content language
3582 * @return array of grammar forms
3585 function getGrammarForms() {
3586 global $wgGrammarForms;
3587 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3588 return $wgGrammarForms[$this->getCode()];
3593 * Provides an alternative text depending on specified gender.
3594 * Usage {{gender:username|masculine|feminine|unknown}}.
3595 * username is optional, in which case the gender of current user is used,
3596 * but only in (some) interface messages; otherwise default gender is used.
3598 * If no forms are given, an empty string is returned. If only one form is
3599 * given, it will be returned unconditionally. These details are implied by
3600 * the caller and cannot be overridden in subclasses.
3602 * If three forms are given, the default is to use the third (unknown) form.
3603 * If fewer than three forms are given, the default is to use the first (masculine) form.
3604 * These details can be overridden in subclasses.
3606 * @param $gender string
3607 * @param $forms array
3611 function gender( $gender, $forms ) {
3612 if ( !count( $forms ) ) {
3615 $forms = $this->preConvertPlural( $forms, 2 );
3616 if ( $gender === 'male' ) {
3619 if ( $gender === 'female' ) {
3622 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3626 * Plural form transformations, needed for some languages.
3627 * For example, there are 3 form of plural in Russian and Polish,
3628 * depending on "count mod 10". See [[w:Plural]]
3629 * For English it is pretty simple.
3631 * Invoked by putting {{plural:count|wordform1|wordform2}}
3632 * or {{plural:count|wordform1|wordform2|wordform3}}
3634 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3636 * @param $count Integer: non-localized number
3637 * @param $forms Array: different plural forms
3638 * @return string Correct form of plural for $count in this language
3640 function convertPlural( $count, $forms ) {
3641 // Handle explicit n=pluralform cases
3642 $forms = $this->handleExplicitPluralForms( $count, $forms );
3643 if ( is_string( $forms ) ) {
3646 if ( !count( $forms ) ) {
3650 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3651 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3652 return $forms[$pluralForm];
3656 * Handles explicit plural forms for Language::convertPlural()
3658 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3659 * If an explicitly defined plural form matches the $count, then
3660 * string value returned, otherwise array returned for further consideration
3661 * by CLDR rules or overridden convertPlural().
3665 * @param int $count non-localized number
3666 * @param array $forms different plural forms
3668 * @return array|string
3670 protected function handleExplicitPluralForms( $count, array $forms ) {
3671 foreach ( $forms as $index => $form ) {
3672 if ( preg_match( '/\d+=/i', $form ) ) {
3673 $pos = strpos( $form, '=' );
3674 if ( substr( $form, 0, $pos ) === (string) $count ) {
3675 return substr( $form, $pos +
1 );
3677 unset( $forms[$index] );
3680 return array_values( $forms );
3684 * Checks that convertPlural was given an array and pads it to requested
3685 * amount of forms by copying the last one.
3687 * @param $count Integer: How many forms should there be at least
3688 * @param $forms Array of forms given to convertPlural
3689 * @return array Padded array of forms or an exception if not an array
3691 protected function preConvertPlural( /* Array */ $forms, $count ) {
3692 while ( count( $forms ) < $count ) {
3693 $forms[] = $forms[count( $forms ) - 1];
3699 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3700 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3701 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3702 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3705 * @param $str String: the validated block duration in English
3706 * @return string Somehow translated block duration
3707 * @see LanguageFi.php for example implementation
3709 function translateBlockExpiry( $str ) {
3710 $duration = SpecialBlock
::getSuggestedDurations( $this );
3711 foreach ( $duration as $show => $value ) {
3712 if ( strcmp( $str, $value ) == 0 ) {
3713 return htmlspecialchars( trim( $show ) );
3717 // Since usually only infinite or indefinite is only on list, so try
3718 // equivalents if still here.
3719 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3720 if ( in_array( $str, $indefs ) ) {
3721 foreach ( $indefs as $val ) {
3722 $show = array_search( $val, $duration, true );
3723 if ( $show !== false ) {
3724 return htmlspecialchars( trim( $show ) );
3729 // If all else fails, return a standard duration or timestamp description.
3730 $time = strtotime( $str, 0 );
3731 if ( $time === false ) { // Unknown format. Return it as-is in case.
3733 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3734 // $time is relative to 0 so it's a duration length.
3735 return $this->formatDuration( $time );
3736 } else { // It's an absolute timestamp.
3737 if ( $time === 0 ) {
3738 // wfTimestamp() handles 0 as current time instead of epoch.
3739 return $this->timeanddate( '19700101000000' );
3741 return $this->timeanddate( $time );
3747 * languages like Chinese need to be segmented in order for the diff
3750 * @param $text String
3753 public function segmentForDiff( $text ) {
3758 * and unsegment to show the result
3760 * @param $text String
3763 public function unsegmentForDiff( $text ) {
3768 * Return the LanguageConverter used in the Language
3771 * @return LanguageConverter
3773 public function getConverter() {
3774 return $this->mConverter
;
3778 * convert text to all supported variants
3780 * @param $text string
3783 public function autoConvertToAllVariants( $text ) {
3784 return $this->mConverter
->autoConvertToAllVariants( $text );
3788 * convert text to different variants of a language.
3790 * @param $text string
3793 public function convert( $text ) {
3794 return $this->mConverter
->convert( $text );
3798 * Convert a Title object to a string in the preferred variant
3800 * @param $title Title
3803 public function convertTitle( $title ) {
3804 return $this->mConverter
->convertTitle( $title );
3808 * Convert a namespace index to a string in the preferred variant
3813 public function convertNamespace( $ns ) {
3814 return $this->mConverter
->convertNamespace( $ns );
3818 * Check if this is a language with variants
3822 public function hasVariants() {
3823 return count( $this->getVariants() ) > 1;
3827 * Check if the language has the specific variant
3830 * @param $variant string
3833 public function hasVariant( $variant ) {
3834 return (bool)$this->mConverter
->validateVariant( $variant );
3838 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3840 * @param $text string
3842 * @deprecated since 1.22 is no longer used
3844 public function armourMath( $text ) {
3845 return $this->mConverter
->armourMath( $text );
3849 * Perform output conversion on a string, and encode for safe HTML output.
3850 * @param $text String text to be converted
3851 * @param $isTitle Bool whether this conversion is for the article title
3853 * @todo this should get integrated somewhere sane
3855 public function convertHtml( $text, $isTitle = false ) {
3856 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3860 * @param $key string
3863 public function convertCategoryKey( $key ) {
3864 return $this->mConverter
->convertCategoryKey( $key );
3868 * Get the list of variants supported by this language
3869 * see sample implementation in LanguageZh.php
3871 * @return array an array of language codes
3873 public function getVariants() {
3874 return $this->mConverter
->getVariants();
3880 public function getPreferredVariant() {
3881 return $this->mConverter
->getPreferredVariant();
3887 public function getDefaultVariant() {
3888 return $this->mConverter
->getDefaultVariant();
3894 public function getURLVariant() {
3895 return $this->mConverter
->getURLVariant();
3899 * If a language supports multiple variants, it is
3900 * possible that non-existing link in one variant
3901 * actually exists in another variant. this function
3902 * tries to find it. See e.g. LanguageZh.php
3904 * @param $link String: the name of the link
3905 * @param $nt Mixed: the title object of the link
3906 * @param $ignoreOtherCond Boolean: to disable other conditions when
3907 * we need to transclude a template or update a category's link
3908 * @return null the input parameters may be modified upon return
3910 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3911 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3915 * returns language specific options used by User::getPageRenderHash()
3916 * for example, the preferred language variant
3920 function getExtraHashOptions() {
3921 return $this->mConverter
->getExtraHashOptions();
3925 * For languages that support multiple variants, the title of an
3926 * article may be displayed differently in different variants. this
3927 * function returns the apporiate title defined in the body of the article.
3931 public function getParsedTitle() {
3932 return $this->mConverter
->getParsedTitle();
3936 * Prepare external link text for conversion. When the text is
3937 * a URL, it shouldn't be converted, and it'll be wrapped in
3938 * the "raw" tag (-{R| }-) to prevent conversion.
3940 * This function is called "markNoConversion" for historical
3943 * @param $text String: text to be used for external link
3944 * @param $noParse bool: wrap it without confirming it's a real URL first
3945 * @return string the tagged text
3947 public function markNoConversion( $text, $noParse = false ) {
3948 // Excluding protocal-relative URLs may avoid many false positives.
3949 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3950 return $this->mConverter
->markNoConversion( $text );
3957 * A regular expression to match legal word-trailing characters
3958 * which should be merged onto a link of the form [[foo]]bar.
3962 public function linkTrail() {
3963 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3967 * A regular expression character set to match legal word-prefixing
3968 * characters which should be merged onto a link of the form foo[[bar]].
3972 public function linkPrefixCharset() {
3973 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixCharset' );
3979 function getLangObj() {
3984 * Get the "parent" language which has a converter to convert a "compatible" language
3985 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
3987 * @return Language|null
3990 public function getParentLanguage() {
3991 if ( $this->mParentLanguage
!== false ) {
3992 return $this->mParentLanguage
;
3995 $pieces = explode( '-', $this->getCode() );
3997 if ( !in_array( $code, LanguageConverter
::$languagesWithVariants ) ) {
3998 $this->mParentLanguage
= null;
4001 $lang = Language
::factory( $code );
4002 if ( !$lang->hasVariant( $this->getCode() ) ) {
4003 $this->mParentLanguage
= null;
4007 $this->mParentLanguage
= $lang;
4012 * Get the RFC 3066 code for this language object
4014 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4015 * htmlspecialchars() or similar
4019 public function getCode() {
4020 return $this->mCode
;
4024 * Get the code in Bcp47 format which we can use
4025 * inside of html lang="" tags.
4027 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4028 * htmlspecialchars() or similar.
4033 public function getHtmlCode() {
4034 if ( is_null( $this->mHtmlCode
) ) {
4035 $this->mHtmlCode
= wfBCP47( $this->getCode() );
4037 return $this->mHtmlCode
;
4041 * @param $code string
4043 public function setCode( $code ) {
4044 $this->mCode
= $code;
4045 // Ensure we don't leave incorrect cached data lying around
4046 $this->mHtmlCode
= null;
4047 $this->mParentLanguage
= false;
4051 * Get the name of a file for a certain language code
4052 * @param $prefix string Prepend this to the filename
4053 * @param $code string Language code
4054 * @param $suffix string Append this to the filename
4055 * @throws MWException
4056 * @return string $prefix . $mangledCode . $suffix
4058 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4059 if ( !self
::isValidBuiltInCode( $code ) ) {
4060 throw new MWException( "Invalid language code \"$code\"" );
4063 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4067 * Get the language code from a file name. Inverse of getFileName()
4068 * @param $filename string $prefix . $languageCode . $suffix
4069 * @param $prefix string Prefix before the language code
4070 * @param $suffix string Suffix after the language code
4071 * @return string Language code, or false if $prefix or $suffix isn't found
4073 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4075 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4076 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4077 if ( !count( $m ) ) {
4080 return str_replace( '_', '-', strtolower( $m[1] ) );
4084 * @param $code string
4087 public static function getMessagesFileName( $code ) {
4089 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4090 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4095 * @param $code string
4099 public static function getJsonMessagesFileName( $code ) {
4102 if ( !self
::isValidBuiltInCode( $code ) ) {
4103 throw new MWException( "Invalid language code \"$code\"" );
4106 return "$IP/languages/i18n/$code.json" ;
4110 * @param $code string
4113 public static function getClassFileName( $code ) {
4115 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4119 * Get the first fallback for a given language.
4121 * @param $code string
4123 * @return bool|string
4125 public static function getFallbackFor( $code ) {
4126 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4129 $fallbacks = self
::getFallbacksFor( $code );
4130 $first = array_shift( $fallbacks );
4136 * Get the ordered list of fallback languages.
4139 * @param $code string Language code
4142 public static function getFallbacksFor( $code ) {
4143 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
4146 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
4147 $v = array_map( 'trim', explode( ',', $v ) );
4148 if ( $v[count( $v ) - 1] !== 'en' ) {
4156 * Get the ordered list of fallback languages, ending with the fallback
4157 * language chain for the site language.
4160 * @param string $code Language code
4161 * @return array array( fallbacks, site fallbacks )
4163 public static function getFallbacksIncludingSiteLanguage( $code ) {
4164 global $wgLanguageCode;
4166 // Usually, we will only store a tiny number of fallback chains, so we
4167 // keep them in static memory.
4168 $cacheKey = "{$code}-{$wgLanguageCode}";
4170 if ( !array_key_exists( $cacheKey, self
::$fallbackLanguageCache ) ) {
4171 $fallbacks = self
::getFallbacksFor( $code );
4173 // Append the site's fallback chain, including the site language itself
4174 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4175 array_unshift( $siteFallbacks, $wgLanguageCode );
4177 // Eliminate any languages already included in the chain
4178 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4180 self
::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4182 return self
::$fallbackLanguageCache[$cacheKey];
4186 * Get all messages for a given language
4187 * WARNING: this may take a long time. If you just need all message *keys*
4188 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4190 * @param $code string
4194 public static function getMessagesFor( $code ) {
4195 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4199 * Get a message for a given language
4201 * @param $key string
4202 * @param $code string
4206 public static function getMessageFor( $key, $code ) {
4207 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4211 * Get all message keys for a given language. This is a faster alternative to
4212 * array_keys( Language::getMessagesFor( $code ) )
4215 * @param $code string Language code
4216 * @return array of message keys (strings)
4218 public static function getMessageKeysFor( $code ) {
4219 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4226 function fixVariableInNamespace( $talk ) {
4227 if ( strpos( $talk, '$1' ) === false ) {
4231 global $wgMetaNamespace;
4232 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4234 # Allow grammar transformations
4235 # Allowing full message-style parsing would make simple requests
4236 # such as action=raw much more expensive than they need to be.
4237 # This will hopefully cover most cases.
4238 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4239 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4240 return str_replace( ' ', '_', $talk );
4247 function replaceGrammarInNamespace( $m ) {
4248 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4252 * @throws MWException
4255 static function getCaseMaps() {
4256 static $wikiUpperChars, $wikiLowerChars;
4257 if ( isset( $wikiUpperChars ) ) {
4258 return array( $wikiUpperChars, $wikiLowerChars );
4261 wfProfileIn( __METHOD__
);
4262 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4263 if ( $arr === false ) {
4264 throw new MWException(
4265 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4267 $wikiUpperChars = $arr['wikiUpperChars'];
4268 $wikiLowerChars = $arr['wikiLowerChars'];
4269 wfProfileOut( __METHOD__
);
4270 return array( $wikiUpperChars, $wikiLowerChars );
4274 * Decode an expiry (block, protection, etc) which has come from the DB
4276 * @todo FIXME: why are we returnings DBMS-dependent strings???
4278 * @param $expiry String: Database expiry String
4279 * @param $format Bool|Int true to process using language functions, or TS_ constant
4280 * to return the expiry in a given timestamp
4284 public function formatExpiry( $expiry, $format = true ) {
4286 if ( $infinity === null ) {
4287 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4290 if ( $expiry == '' ||
$expiry == $infinity ) {
4291 return $format === true
4292 ?
$this->getMessageFromDB( 'infiniteblock' )
4295 return $format === true
4296 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4297 : wfTimestamp( $format, $expiry );
4303 * @param $seconds int|float
4304 * @param $format Array Optional
4305 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4306 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4307 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4308 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4311 function formatTimePeriod( $seconds, $format = array() ) {
4312 if ( !is_array( $format ) ) {
4313 $format = array( 'avoid' => $format ); // For backwards compatibility
4315 if ( !isset( $format['avoid'] ) ) {
4316 $format['avoid'] = false;
4318 if ( !isset( $format['noabbrevs' ] ) ) {
4319 $format['noabbrevs'] = false;
4321 $secondsMsg = wfMessage(
4322 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4323 $minutesMsg = wfMessage(
4324 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4325 $hoursMsg = wfMessage(
4326 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4327 $daysMsg = wfMessage(
4328 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4330 if ( round( $seconds * 10 ) < 100 ) {
4331 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4332 $s = $secondsMsg->params( $s )->text();
4333 } elseif ( round( $seconds ) < 60 ) {
4334 $s = $this->formatNum( round( $seconds ) );
4335 $s = $secondsMsg->params( $s )->text();
4336 } elseif ( round( $seconds ) < 3600 ) {
4337 $minutes = floor( $seconds / 60 );
4338 $secondsPart = round( fmod( $seconds, 60 ) );
4339 if ( $secondsPart == 60 ) {
4343 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4345 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4346 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4347 $hours = floor( $seconds / 3600 );
4348 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4349 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4350 if ( $secondsPart == 60 ) {
4354 if ( $minutes == 60 ) {
4358 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4360 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4361 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4362 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4365 $days = floor( $seconds / 86400 );
4366 if ( $format['avoid'] === 'avoidminutes' ) {
4367 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4368 if ( $hours == 24 ) {
4372 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4374 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4375 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4376 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4377 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4378 if ( $minutes == 60 ) {
4382 if ( $hours == 24 ) {
4386 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4388 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4390 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4392 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4394 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4401 * Format a bitrate for output, using an appropriate
4402 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4404 * This use base 1000. For base 1024 use formatSize(), for another base
4405 * see formatComputingNumbers()
4410 function formatBitrate( $bps ) {
4411 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4415 * @param $size int Size of the unit
4416 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4417 * @param $messageKey string Message key to be uesd
4420 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4422 return str_replace( '$1', $this->formatNum( $size ),
4423 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4426 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4429 $maxIndex = count( $sizes ) - 1;
4430 while ( $size >= $boundary && $index < $maxIndex ) {
4435 // For small sizes no decimal places necessary
4438 // For MB and bigger two decimal places are smarter
4441 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4443 $size = round( $size, $round );
4444 $text = $this->getMessageFromDB( $msg );
4445 return str_replace( '$1', $this->formatNum( $size ), $text );
4449 * Format a size in bytes for output, using an appropriate
4450 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4452 * This method use base 1024. For base 1000 use formatBitrate(), for
4453 * another base see formatComputingNumbers()
4455 * @param $size int Size to format
4456 * @return string Plain text (not HTML)
4458 function formatSize( $size ) {
4459 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4463 * Make a list item, used by various special pages
4465 * @param $page String Page link
4466 * @param $details String Text between brackets
4467 * @param $oppositedm Boolean Add the direction mark opposite to your
4468 * language, to display text properly
4471 function specialList( $page, $details, $oppositedm = true ) {
4472 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4473 $this->getDirMark();
4474 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4475 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4476 return $page . $details;
4480 * Generate (prev x| next x) (20|50|100...) type links for paging
4482 * @param $title Title object to link
4483 * @param $offset Integer offset parameter
4484 * @param $limit Integer limit parameter
4485 * @param $query array|String optional URL query parameter string
4486 * @param $atend Bool optional param for specified if this is the last page
4489 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4490 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4492 # Make 'previous' link
4493 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4494 if ( $offset > 0 ) {
4495 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4496 $query, $prev, 'prevn-title', 'mw-prevlink' );
4498 $plink = htmlspecialchars( $prev );
4502 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4504 $nlink = htmlspecialchars( $next );
4506 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4507 $query, $next, 'nextn-title', 'mw-nextlink' );
4510 # Make links to set number of items per page
4511 $numLinks = array();
4512 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4513 $numLinks[] = $this->numLink( $title, $offset, $num,
4514 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4517 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4518 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4522 * Helper function for viewPrevNext() that generates links
4524 * @param $title Title object to link
4525 * @param $offset Integer offset parameter
4526 * @param $limit Integer limit parameter
4527 * @param $query Array extra query parameters
4528 * @param $link String text to use for the link; will be escaped
4529 * @param $tooltipMsg String name of the message to use as tooltip
4530 * @param $class String value of the "class" attribute of the link
4531 * @return String HTML fragment
4533 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4534 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4535 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4536 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4537 'title' => $tooltip, 'class' => $class ), $link );
4541 * Get the conversion rule title, if any.
4545 public function getConvRuleTitle() {
4546 return $this->mConverter
->getConvRuleTitle();
4550 * Get the compiled plural rules for the language
4552 * @return array Associative array with plural form, and plural rule as key-value pairs
4554 public function getCompiledPluralRules() {
4555 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4556 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4557 if ( !$pluralRules ) {
4558 foreach ( $fallbacks as $fallbackCode ) {
4559 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4560 if ( $pluralRules ) {
4565 return $pluralRules;
4569 * Get the plural rules for the language
4571 * @return array Associative array with plural form number and plural rule as key-value pairs
4573 public function getPluralRules() {
4574 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4575 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4576 if ( !$pluralRules ) {
4577 foreach ( $fallbacks as $fallbackCode ) {
4578 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4579 if ( $pluralRules ) {
4584 return $pluralRules;
4588 * Get the plural rule types for the language
4590 * @return array Associative array with plural form number and plural rule type as key-value pairs
4592 public function getPluralRuleTypes() {
4593 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRuleTypes' );
4594 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4595 if ( !$pluralRuleTypes ) {
4596 foreach ( $fallbacks as $fallbackCode ) {
4597 $pluralRuleTypes = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4598 if ( $pluralRuleTypes ) {
4603 return $pluralRuleTypes;
4607 * Find the index number of the plural rule appropriate for the given number
4608 * @return int The index number of the plural rule
4610 public function getPluralRuleIndexNumber( $number ) {
4611 $pluralRules = $this->getCompiledPluralRules();
4612 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );
4617 * Find the plural rule type appropriate for the given number
4618 * For example, if the language is set to Arabic, getPluralType(5) should
4621 * @return string The name of the plural rule type, e.g. one, two, few, many
4623 public function getPluralRuleType( $number ) {
4624 $index = $this->getPluralRuleIndexNumber( $number );
4625 $pluralRuleTypes = $this->getPluralRuleTypes();
4626 if ( isset( $pluralRuleTypes[$index] ) ) {
4627 return $pluralRuleTypes[$index];