Merge "Always use the canonical extension name to link the license file"
[mediawiki.git] / languages / Language.php
blobd46845fb0603c23d61f61b66078cfc1ba7f433b7
1 <?php
2 /**
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
20 * @file
21 * @ingroup Language
24 /**
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
30 exit( 1 );
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
37 /**
38 * Internationalisation code
39 * @ingroup Language
41 class Language {
42 /**
43 * @var LanguageConverter
45 public $mConverter;
47 public $mVariants, $mCode, $mLoaded = false;
48 public $mMagicExtensions = array(), $mMagicHookDone = false;
49 private $mHtmlCode = null, $mParentLanguage = false;
51 public $dateFormatStrings = array();
52 public $mExtendedSpecialPageAliases;
54 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
56 /**
57 * ReplacementArray object caches
59 public $transformData = array();
61 /**
62 * @var LocalisationCache
64 static public $dataCache;
66 static public $mLangObjCache = array();
68 static public $mWeekdayMsgs = array(
69 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
70 'friday', 'saturday'
73 static public $mWeekdayAbbrevMsgs = array(
74 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
77 static public $mMonthMsgs = array(
78 'january', 'february', 'march', 'april', 'may_long', 'june',
79 'july', 'august', 'september', 'october', 'november',
80 'december'
82 static public $mMonthGenMsgs = array(
83 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
84 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
85 'december-gen'
87 static public $mMonthAbbrevMsgs = array(
88 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
89 'sep', 'oct', 'nov', 'dec'
92 static public $mIranianCalendarMonthMsgs = array(
93 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
94 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
95 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
96 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
99 static public $mHebrewCalendarMonthMsgs = array(
100 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
101 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
102 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
103 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
104 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
107 static public $mHebrewCalendarMonthGenMsgs = array(
108 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
109 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
110 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
111 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
112 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
115 static public $mHijriCalendarMonthMsgs = array(
116 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
117 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
118 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
119 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
123 * @since 1.20
124 * @var array
126 static public $durationIntervals = array(
127 'millennia' => 31556952000,
128 'centuries' => 3155695200,
129 'decades' => 315569520,
130 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
131 'weeks' => 604800,
132 'days' => 86400,
133 'hours' => 3600,
134 'minutes' => 60,
135 'seconds' => 1,
139 * Cache for language fallbacks.
140 * @see Language::getFallbacksIncludingSiteLanguage
141 * @since 1.21
142 * @var array
144 static private $fallbackLanguageCache = array();
147 * Cache for language names
148 * @var MapCacheLRU|null
150 static private $languageNameCache;
153 * Get a cached or new language object for a given language code
154 * @param string $code
155 * @return Language
157 static function factory( $code ) {
158 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
160 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
161 $code = $wgDummyLanguageCodes[$code];
164 // get the language object to process
165 $langObj = isset( self::$mLangObjCache[$code] )
166 ? self::$mLangObjCache[$code]
167 : self::newFromCode( $code );
169 // merge the language object in to get it up front in the cache
170 self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache );
171 // get rid of the oldest ones in case we have an overflow
172 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
174 return $langObj;
178 * Create a language object for a given language code
179 * @param string $code
180 * @throws MWException
181 * @return Language
183 protected static function newFromCode( $code ) {
184 // Protect against path traversal below
185 if ( !Language::isValidCode( $code )
186 || strcspn( $code, ":/\\\000" ) !== strlen( $code )
188 throw new MWException( "Invalid language code \"$code\"" );
191 if ( !Language::isValidBuiltInCode( $code ) ) {
192 // It's not possible to customise this code with class files, so
193 // just return a Language object. This is to support uselang= hacks.
194 $lang = new Language;
195 $lang->setCode( $code );
196 return $lang;
199 // Check if there is a language class for the code
200 $class = self::classFromCode( $code );
201 self::preloadLanguageClass( $class );
202 if ( class_exists( $class ) ) {
203 $lang = new $class;
204 return $lang;
207 // Keep trying the fallback list until we find an existing class
208 $fallbacks = Language::getFallbacksFor( $code );
209 foreach ( $fallbacks as $fallbackCode ) {
210 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
211 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
214 $class = self::classFromCode( $fallbackCode );
215 self::preloadLanguageClass( $class );
216 if ( class_exists( $class ) ) {
217 $lang = Language::newFromCode( $fallbackCode );
218 $lang->setCode( $code );
219 return $lang;
223 throw new MWException( "Invalid fallback sequence for language '$code'" );
227 * Checks whether any localisation is available for that language tag
228 * in MediaWiki (MessagesXx.php exists).
230 * @param string $code Language tag (in lower case)
231 * @return bool Whether language is supported
232 * @since 1.21
234 public static function isSupportedLanguage( $code ) {
235 return self::isValidBuiltInCode( $code )
236 && ( is_readable( self::getMessagesFileName( $code ) )
237 || is_readable( self::getJsonMessagesFileName( $code ) )
242 * Returns true if a language code string is a well-formed language tag
243 * according to RFC 5646.
244 * This function only checks well-formedness; it doesn't check that
245 * language, script or variant codes actually exist in the repositories.
247 * Based on regexes by Mark Davis of the Unicode Consortium:
248 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
250 * @param string $code
251 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
253 * @return bool
254 * @since 1.21
256 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
257 $alpha = '[a-z]';
258 $digit = '[0-9]';
259 $alphanum = '[a-z0-9]';
260 $x = 'x'; # private use singleton
261 $singleton = '[a-wy-z]'; # other singleton
262 $s = $lenient ? '[-_]' : '-';
264 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
265 $script = "$alpha{4}"; # ISO 15924
266 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
267 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
268 $extension = "$singleton(?:$s$alphanum{2,8})+";
269 $privateUse = "$x(?:$s$alphanum{1,8})+";
271 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
272 # Since these are limited, this is safe even later changes to the registry --
273 # the only oddity is that it might change the type of the tag, and thus
274 # the results from the capturing groups.
275 # http://www.iana.org/assignments/language-subtag-registry
277 $grandfathered = "en{$s}GB{$s}oed"
278 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
279 . "|no{$s}(?:bok|nyn)"
280 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
281 . "|zh{$s}min{$s}nan";
283 $variantList = "$variant(?:$s$variant)*";
284 $extensionList = "$extension(?:$s$extension)*";
286 $langtag = "(?:($language)"
287 . "(?:$s$script)?"
288 . "(?:$s$region)?"
289 . "(?:$s$variantList)?"
290 . "(?:$s$extensionList)?"
291 . "(?:$s$privateUse)?)";
293 # The final breakdown, with capturing groups for each of these components
294 # The variants, extensions, grandfathered, and private-use may have interior '-'
296 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
298 return (bool)preg_match( "/$root/", strtolower( $code ) );
302 * Returns true if a language code string is of a valid form, whether or
303 * not it exists. This includes codes which are used solely for
304 * customisation via the MediaWiki namespace.
306 * @param string $code
308 * @return bool
310 public static function isValidCode( $code ) {
311 static $cache = array();
312 if ( isset( $cache[$code] ) ) {
313 return $cache[$code];
315 // People think language codes are html safe, so enforce it.
316 // Ideally we should only allow a-zA-Z0-9-
317 // but, .+ and other chars are often used for {{int:}} hacks
318 // see bugs 37564, 37587, 36938
319 $cache[$code] =
320 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
321 && !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code );
323 return $cache[$code];
327 * Returns true if a language code is of a valid form for the purposes of
328 * internal customisation of MediaWiki, via Messages*.php or *.json.
330 * @param string $code
332 * @throws MWException
333 * @since 1.18
334 * @return bool
336 public static function isValidBuiltInCode( $code ) {
338 if ( !is_string( $code ) ) {
339 if ( is_object( $code ) ) {
340 $addmsg = " of class " . get_class( $code );
341 } else {
342 $addmsg = '';
344 $type = gettype( $code );
345 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
348 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
352 * Returns true if a language code is an IETF tag known to MediaWiki.
354 * @param string $tag
356 * @since 1.21
357 * @return bool
359 public static function isKnownLanguageTag( $tag ) {
360 static $coreLanguageNames;
362 // Quick escape for invalid input to avoid exceptions down the line
363 // when code tries to process tags which are not valid at all.
364 if ( !self::isValidBuiltInCode( $tag ) ) {
365 return false;
368 if ( $coreLanguageNames === null ) {
369 global $IP;
370 include "$IP/languages/Names.php";
373 if ( isset( $coreLanguageNames[$tag] )
374 || self::fetchLanguageName( $tag, $tag ) !== ''
376 return true;
379 return false;
383 * @param string $code
384 * @return string Name of the language class
386 public static function classFromCode( $code ) {
387 if ( $code == 'en' ) {
388 return 'Language';
389 } else {
390 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
395 * Includes language class files
397 * @param string $class Name of the language class
399 public static function preloadLanguageClass( $class ) {
400 global $IP;
402 if ( $class === 'Language' ) {
403 return;
406 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
407 include_once "$IP/languages/classes/$class.php";
412 * Get the LocalisationCache instance
414 * @return LocalisationCache
416 public static function getLocalisationCache() {
417 if ( is_null( self::$dataCache ) ) {
418 global $wgLocalisationCacheConf;
419 $class = $wgLocalisationCacheConf['class'];
420 self::$dataCache = new $class( $wgLocalisationCacheConf );
422 return self::$dataCache;
425 function __construct() {
426 $this->mConverter = new FakeConverter( $this );
427 // Set the code to the name of the descendant
428 if ( get_class( $this ) == 'Language' ) {
429 $this->mCode = 'en';
430 } else {
431 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
433 self::getLocalisationCache();
437 * Reduce memory usage
439 function __destruct() {
440 foreach ( $this as $name => $value ) {
441 unset( $this->$name );
446 * Hook which will be called if this is the content language.
447 * Descendants can use this to register hook functions or modify globals
449 function initContLang() {
453 * @return array
454 * @since 1.19
456 function getFallbackLanguages() {
457 return self::getFallbacksFor( $this->mCode );
461 * Exports $wgBookstoreListEn
462 * @return array
464 function getBookstoreList() {
465 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
469 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
470 * available in localised form, it will be included in English.
472 * @return array
474 public function getNamespaces() {
475 if ( is_null( $this->namespaceNames ) ) {
476 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
478 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
479 $validNamespaces = MWNamespace::getCanonicalNamespaces();
481 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
483 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
484 if ( $wgMetaNamespaceTalk ) {
485 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
486 } else {
487 $talk = $this->namespaceNames[NS_PROJECT_TALK];
488 $this->namespaceNames[NS_PROJECT_TALK] =
489 $this->fixVariableInNamespace( $talk );
492 # Sometimes a language will be localised but not actually exist on this wiki.
493 foreach ( $this->namespaceNames as $key => $text ) {
494 if ( !isset( $validNamespaces[$key] ) ) {
495 unset( $this->namespaceNames[$key] );
499 # The above mixing may leave namespaces out of canonical order.
500 # Re-order by namespace ID number...
501 ksort( $this->namespaceNames );
503 Hooks::run( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
506 return $this->namespaceNames;
510 * Arbitrarily set all of the namespace names at once. Mainly used for testing
511 * @param array $namespaces Array of namespaces (id => name)
513 public function setNamespaces( array $namespaces ) {
514 $this->namespaceNames = $namespaces;
515 $this->mNamespaceIds = null;
519 * Resets all of the namespace caches. Mainly used for testing
521 public function resetNamespaces() {
522 $this->namespaceNames = null;
523 $this->mNamespaceIds = null;
524 $this->namespaceAliases = null;
528 * A convenience function that returns the same thing as
529 * getNamespaces() except with the array values changed to ' '
530 * where it found '_', useful for producing output to be displayed
531 * e.g. in <select> forms.
533 * @return array
535 function getFormattedNamespaces() {
536 $ns = $this->getNamespaces();
537 foreach ( $ns as $k => $v ) {
538 $ns[$k] = strtr( $v, '_', ' ' );
540 return $ns;
544 * Get a namespace value by key
545 * <code>
546 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
547 * echo $mw_ns; // prints 'MediaWiki'
548 * </code>
550 * @param int $index The array key of the namespace to return
551 * @return string|bool String if the namespace value exists, otherwise false
553 function getNsText( $index ) {
554 $ns = $this->getNamespaces();
556 return isset( $ns[$index] ) ? $ns[$index] : false;
560 * A convenience function that returns the same thing as
561 * getNsText() except with '_' changed to ' ', useful for
562 * producing output.
564 * <code>
565 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
566 * echo $mw_ns; // prints 'MediaWiki talk'
567 * </code>
569 * @param int $index The array key of the namespace to return
570 * @return string Namespace name without underscores (empty string if namespace does not exist)
572 function getFormattedNsText( $index ) {
573 $ns = $this->getNsText( $index );
575 return strtr( $ns, '_', ' ' );
579 * Returns gender-dependent namespace alias if available.
580 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
581 * @param int $index Namespace index
582 * @param string $gender Gender key (male, female... )
583 * @return string
584 * @since 1.18
586 function getGenderNsText( $index, $gender ) {
587 global $wgExtraGenderNamespaces;
589 $ns = $wgExtraGenderNamespaces +
590 self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
592 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
596 * Whether this language uses gender-dependent namespace aliases.
597 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
598 * @return bool
599 * @since 1.18
601 function needsGenderDistinction() {
602 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
603 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
604 // $wgExtraGenderNamespaces overrides everything
605 return true;
606 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
607 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
608 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
609 return false;
610 } else {
611 // Check what is in i18n files
612 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
613 return count( $aliases ) > 0;
618 * Get a namespace key by value, case insensitive.
619 * Only matches namespace names for the current language, not the
620 * canonical ones defined in Namespace.php.
622 * @param string $text
623 * @return int|bool An integer if $text is a valid value otherwise false
625 function getLocalNsIndex( $text ) {
626 $lctext = $this->lc( $text );
627 $ids = $this->getNamespaceIds();
628 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
632 * @return array
634 function getNamespaceAliases() {
635 if ( is_null( $this->namespaceAliases ) ) {
636 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
637 if ( !$aliases ) {
638 $aliases = array();
639 } else {
640 foreach ( $aliases as $name => $index ) {
641 if ( $index === NS_PROJECT_TALK ) {
642 unset( $aliases[$name] );
643 $name = $this->fixVariableInNamespace( $name );
644 $aliases[$name] = $index;
649 global $wgExtraGenderNamespaces;
650 $genders = $wgExtraGenderNamespaces +
651 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
652 foreach ( $genders as $index => $forms ) {
653 foreach ( $forms as $alias ) {
654 $aliases[$alias] = $index;
658 # Also add converted namespace names as aliases, to avoid confusion.
659 $convertedNames = array();
660 foreach ( $this->getVariants() as $variant ) {
661 if ( $variant === $this->mCode ) {
662 continue;
664 foreach ( $this->getNamespaces() as $ns => $_ ) {
665 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
669 $this->namespaceAliases = $aliases + $convertedNames;
672 return $this->namespaceAliases;
676 * @return array
678 function getNamespaceIds() {
679 if ( is_null( $this->mNamespaceIds ) ) {
680 global $wgNamespaceAliases;
681 # Put namespace names and aliases into a hashtable.
682 # If this is too slow, then we should arrange it so that it is done
683 # before caching. The catch is that at pre-cache time, the above
684 # class-specific fixup hasn't been done.
685 $this->mNamespaceIds = array();
686 foreach ( $this->getNamespaces() as $index => $name ) {
687 $this->mNamespaceIds[$this->lc( $name )] = $index;
689 foreach ( $this->getNamespaceAliases() as $name => $index ) {
690 $this->mNamespaceIds[$this->lc( $name )] = $index;
692 if ( $wgNamespaceAliases ) {
693 foreach ( $wgNamespaceAliases as $name => $index ) {
694 $this->mNamespaceIds[$this->lc( $name )] = $index;
698 return $this->mNamespaceIds;
702 * Get a namespace key by value, case insensitive. Canonical namespace
703 * names override custom ones defined for the current language.
705 * @param string $text
706 * @return int|bool An integer if $text is a valid value otherwise false
708 function getNsIndex( $text ) {
709 $lctext = $this->lc( $text );
710 $ns = MWNamespace::getCanonicalIndex( $lctext );
711 if ( $ns !== null ) {
712 return $ns;
714 $ids = $this->getNamespaceIds();
715 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
719 * short names for language variants used for language conversion links.
721 * @param string $code
722 * @param bool $usemsg Use the "variantname-xyz" message if it exists
723 * @return string
725 function getVariantname( $code, $usemsg = true ) {
726 $msg = "variantname-$code";
727 if ( $usemsg && wfMessage( $msg )->exists() ) {
728 return $this->getMessageFromDB( $msg );
730 $name = self::fetchLanguageName( $code );
731 if ( $name ) {
732 return $name; # if it's defined as a language name, show that
733 } else {
734 # otherwise, output the language code
735 return $code;
740 * @deprecated since 1.24, doesn't handle conflicting aliases. Use
741 * SpecialPageFactory::getLocalNameFor instead.
742 * @param string $name
743 * @return string
745 function specialPage( $name ) {
746 $aliases = $this->getSpecialPageAliases();
747 if ( isset( $aliases[$name][0] ) ) {
748 $name = $aliases[$name][0];
750 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
754 * @return array
756 function getDatePreferences() {
757 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
761 * @return array
763 function getDateFormats() {
764 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
768 * @return array|string
770 function getDefaultDateFormat() {
771 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
772 if ( $df === 'dmy or mdy' ) {
773 global $wgAmericanDates;
774 return $wgAmericanDates ? 'mdy' : 'dmy';
775 } else {
776 return $df;
781 * @return array
783 function getDatePreferenceMigrationMap() {
784 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
788 * @param string $image
789 * @return array|null
791 function getImageFile( $image ) {
792 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
796 * @return array
797 * @since 1.24
799 function getImageFiles() {
800 return self::$dataCache->getItem( $this->mCode, 'imageFiles' );
804 * @return array
806 function getExtraUserToggles() {
807 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
811 * @param string $tog
812 * @return string
814 function getUserToggle( $tog ) {
815 return $this->getMessageFromDB( "tog-$tog" );
819 * Get native language names, indexed by code.
820 * Only those defined in MediaWiki, no other data like CLDR.
821 * If $customisedOnly is true, only returns codes with a messages file
823 * @param bool $customisedOnly
825 * @return array
826 * @deprecated since 1.20, use fetchLanguageNames()
828 public static function getLanguageNames( $customisedOnly = false ) {
829 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
833 * Get translated language names. This is done on best effort and
834 * by default this is exactly the same as Language::getLanguageNames.
835 * The CLDR extension provides translated names.
836 * @param string $code Language code.
837 * @return array Language code => language name
838 * @since 1.18.0
839 * @deprecated since 1.20, use fetchLanguageNames()
841 public static function getTranslatedLanguageNames( $code ) {
842 return self::fetchLanguageNames( $code, 'all' );
846 * Get an array of language names, indexed by code.
847 * @param null|string $inLanguage Code of language in which to return the names
848 * Use null for autonyms (native names)
849 * @param string $include One of:
850 * 'all' all available languages
851 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
852 * 'mwfile' only if the language is in 'mw' *and* has a message file
853 * @return array Language code => language name
854 * @since 1.20
856 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
857 wfProfileIn( __METHOD__ );
858 $cacheKey = $inLanguage === null ? 'null' : $inLanguage;
859 $cacheKey .= ":$include";
860 if ( self::$languageNameCache === null ) {
861 self::$languageNameCache = new MapCacheLRU( 20 );
863 if ( self::$languageNameCache->has( $cacheKey ) ) {
864 $ret = self::$languageNameCache->get( $cacheKey );
865 } else {
866 $ret = self::fetchLanguageNamesUncached( $inLanguage, $include );
867 self::$languageNameCache->set( $cacheKey, $ret );
869 wfProfileOut( __METHOD__ );
870 return $ret;
874 * Uncached helper for fetchLanguageNames
875 * @param null|string $inLanguage Code of language in which to return the names
876 * Use null for autonyms (native names)
877 * @param string $include One of:
878 * 'all' all available languages
879 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
880 * 'mwfile' only if the language is in 'mw' *and* has a message file
881 * @return array Language code => language name
883 private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
884 global $wgExtraLanguageNames;
885 static $coreLanguageNames;
887 if ( $coreLanguageNames === null ) {
888 global $IP;
889 include "$IP/languages/Names.php";
892 // If passed an invalid language code to use, fallback to en
893 if ( $inLanguage !== null && !Language::isValidCode( $inLanguage ) ) {
894 $inLanguage = 'en';
897 $names = array();
899 if ( $inLanguage ) {
900 # TODO: also include when $inLanguage is null, when this code is more efficient
901 Hooks::run( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
904 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
905 foreach ( $mwNames as $mwCode => $mwName ) {
906 # - Prefer own MediaWiki native name when not using the hook
907 # - For other names just add if not added through the hook
908 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
909 $names[$mwCode] = $mwName;
913 if ( $include === 'all' ) {
914 ksort( $names );
915 return $names;
918 $returnMw = array();
919 $coreCodes = array_keys( $mwNames );
920 foreach ( $coreCodes as $coreCode ) {
921 $returnMw[$coreCode] = $names[$coreCode];
924 if ( $include === 'mwfile' ) {
925 $namesMwFile = array();
926 # We do this using a foreach over the codes instead of a directory
927 # loop so that messages files in extensions will work correctly.
928 foreach ( $returnMw as $code => $value ) {
929 if ( is_readable( self::getMessagesFileName( $code ) )
930 || is_readable( self::getJsonMessagesFileName( $code ) )
932 $namesMwFile[$code] = $names[$code];
936 ksort( $namesMwFile );
937 return $namesMwFile;
940 ksort( $returnMw );
941 # 'mw' option; default if it's not one of the other two options (all/mwfile)
942 return $returnMw;
946 * @param string $code The code of the language for which to get the name
947 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
948 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
949 * @return string Language name or empty
950 * @since 1.20
952 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
953 $code = strtolower( $code );
954 $array = self::fetchLanguageNames( $inLanguage, $include );
955 return !array_key_exists( $code, $array ) ? '' : $array[$code];
959 * Get a message from the MediaWiki namespace.
961 * @param string $msg Message name
962 * @return string
964 function getMessageFromDB( $msg ) {
965 return $this->msg( $msg )->text();
969 * Get message object in this language. Only for use inside this class.
971 * @param string $msg Message name
972 * @return Message
974 protected function msg( $msg ) {
975 return wfMessage( $msg )->inLanguage( $this );
979 * Get the native language name of $code.
980 * Only if defined in MediaWiki, no other data like CLDR.
981 * @param string $code
982 * @return string
983 * @deprecated since 1.20, use fetchLanguageName()
985 function getLanguageName( $code ) {
986 return self::fetchLanguageName( $code );
990 * @param string $key
991 * @return string
993 function getMonthName( $key ) {
994 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
998 * @return array
1000 function getMonthNamesArray() {
1001 $monthNames = array( '' );
1002 for ( $i = 1; $i < 13; $i++ ) {
1003 $monthNames[] = $this->getMonthName( $i );
1005 return $monthNames;
1009 * @param string $key
1010 * @return string
1012 function getMonthNameGen( $key ) {
1013 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
1017 * @param string $key
1018 * @return string
1020 function getMonthAbbreviation( $key ) {
1021 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
1025 * @return array
1027 function getMonthAbbreviationsArray() {
1028 $monthNames = array( '' );
1029 for ( $i = 1; $i < 13; $i++ ) {
1030 $monthNames[] = $this->getMonthAbbreviation( $i );
1032 return $monthNames;
1036 * @param string $key
1037 * @return string
1039 function getWeekdayName( $key ) {
1040 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
1044 * @param string $key
1045 * @return string
1047 function getWeekdayAbbreviation( $key ) {
1048 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
1052 * @param string $key
1053 * @return string
1055 function getIranianCalendarMonthName( $key ) {
1056 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1060 * @param string $key
1061 * @return string
1063 function getHebrewCalendarMonthName( $key ) {
1064 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1068 * @param string $key
1069 * @return string
1071 function getHebrewCalendarMonthNameGen( $key ) {
1072 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1076 * @param string $key
1077 * @return string
1079 function getHijriCalendarMonthName( $key ) {
1080 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1084 * Pass through result from $dateTimeObj->format()
1085 * @param DateTime|bool|null &$dateTimeObj
1086 * @param string $ts
1087 * @param DateTimeZone|bool|null $zone
1088 * @param string $code
1089 * @return string
1091 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1092 if ( !$dateTimeObj ) {
1093 $dateTimeObj = DateTime::createFromFormat(
1094 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1097 return $dateTimeObj->format( $code );
1101 * This is a workalike of PHP's date() function, but with better
1102 * internationalisation, a reduced set of format characters, and a better
1103 * escaping format.
1105 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1106 * the PHP manual for definitions. There are a number of extensions, which
1107 * start with "x":
1109 * xn Do not translate digits of the next numeric format character
1110 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1111 * xr Use roman numerals for the next numeric format character
1112 * xh Use hebrew numerals for the next numeric format character
1113 * xx Literal x
1114 * xg Genitive month name
1116 * xij j (day number) in Iranian calendar
1117 * xiF F (month name) in Iranian calendar
1118 * xin n (month number) in Iranian calendar
1119 * xiy y (two digit year) in Iranian calendar
1120 * xiY Y (full year) in Iranian calendar
1122 * xjj j (day number) in Hebrew calendar
1123 * xjF F (month name) in Hebrew calendar
1124 * xjt t (days in month) in Hebrew calendar
1125 * xjx xg (genitive month name) in Hebrew calendar
1126 * xjn n (month number) in Hebrew calendar
1127 * xjY Y (full year) in Hebrew calendar
1129 * xmj j (day number) in Hijri calendar
1130 * xmF F (month name) in Hijri calendar
1131 * xmn n (month number) in Hijri calendar
1132 * xmY Y (full year) in Hijri calendar
1134 * xkY Y (full year) in Thai solar calendar. Months and days are
1135 * identical to the Gregorian calendar
1136 * xoY Y (full year) in Minguo calendar or Juche year.
1137 * Months and days are identical to the
1138 * Gregorian calendar
1139 * xtY Y (full year) in Japanese nengo. Months and days are
1140 * identical to the Gregorian calendar
1142 * Characters enclosed in double quotes will be considered literal (with
1143 * the quotes themselves removed). Unmatched quotes will be considered
1144 * literal quotes. Example:
1146 * "The month is" F => The month is January
1147 * i's" => 20'11"
1149 * Backslash escaping is also supported.
1151 * Input timestamp is assumed to be pre-normalized to the desired local
1152 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1153 * $ts is UTC if $zone is not given.
1155 * @param string $format
1156 * @param string $ts 14-character timestamp
1157 * YYYYMMDDHHMMSS
1158 * 01234567890123
1159 * @param DateTimeZone $zone Timezone of $ts
1160 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1161 * Only makes sense if $ts is the current time.
1162 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1164 * @throws MWException
1165 * @return string
1167 function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = null ) {
1168 $s = '';
1169 $raw = false;
1170 $roman = false;
1171 $hebrewNum = false;
1172 $dateTimeObj = false;
1173 $rawToggle = false;
1174 $iranian = false;
1175 $hebrew = false;
1176 $hijri = false;
1177 $thai = false;
1178 $minguo = false;
1179 $tenno = false;
1181 $usedSecond = false;
1182 $usedMinute = false;
1183 $usedHour = false;
1184 $usedAMPM = false;
1185 $usedDay = false;
1186 $usedWeek = false;
1187 $usedMonth = false;
1188 $usedYear = false;
1189 $usedISOYear = false;
1190 $usedIsLeapYear = false;
1192 $usedHebrewMonth = false;
1193 $usedIranianMonth = false;
1194 $usedHijriMonth = false;
1195 $usedHebrewYear = false;
1196 $usedIranianYear = false;
1197 $usedHijriYear = false;
1198 $usedTennoYear = false;
1200 if ( strlen( $ts ) !== 14 ) {
1201 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1204 if ( !ctype_digit( $ts ) ) {
1205 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1208 $formatLength = strlen( $format );
1209 for ( $p = 0; $p < $formatLength; $p++ ) {
1210 $num = false;
1211 $code = $format[$p];
1212 if ( $code == 'x' && $p < $formatLength - 1 ) {
1213 $code .= $format[++$p];
1216 if ( ( $code === 'xi'
1217 || $code === 'xj'
1218 || $code === 'xk'
1219 || $code === 'xm'
1220 || $code === 'xo'
1221 || $code === 'xt' )
1222 && $p < $formatLength - 1 ) {
1223 $code .= $format[++$p];
1226 switch ( $code ) {
1227 case 'xx':
1228 $s .= 'x';
1229 break;
1230 case 'xn':
1231 $raw = true;
1232 break;
1233 case 'xN':
1234 $rawToggle = !$rawToggle;
1235 break;
1236 case 'xr':
1237 $roman = true;
1238 break;
1239 case 'xh':
1240 $hebrewNum = true;
1241 break;
1242 case 'xg':
1243 $usedMonth = true;
1244 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1245 break;
1246 case 'xjx':
1247 $usedHebrewMonth = true;
1248 if ( !$hebrew ) {
1249 $hebrew = self::tsToHebrew( $ts );
1251 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1252 break;
1253 case 'd':
1254 $usedDay = true;
1255 $num = substr( $ts, 6, 2 );
1256 break;
1257 case 'D':
1258 $usedDay = true;
1259 $s .= $this->getWeekdayAbbreviation( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1260 break;
1261 case 'j':
1262 $usedDay = true;
1263 $num = intval( substr( $ts, 6, 2 ) );
1264 break;
1265 case 'xij':
1266 $usedDay = true;
1267 if ( !$iranian ) {
1268 $iranian = self::tsToIranian( $ts );
1270 $num = $iranian[2];
1271 break;
1272 case 'xmj':
1273 $usedDay = true;
1274 if ( !$hijri ) {
1275 $hijri = self::tsToHijri( $ts );
1277 $num = $hijri[2];
1278 break;
1279 case 'xjj':
1280 $usedDay = true;
1281 if ( !$hebrew ) {
1282 $hebrew = self::tsToHebrew( $ts );
1284 $num = $hebrew[2];
1285 break;
1286 case 'l':
1287 $usedDay = true;
1288 $s .= $this->getWeekdayName( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1289 break;
1290 case 'F':
1291 $usedMonth = true;
1292 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1293 break;
1294 case 'xiF':
1295 $usedIranianMonth = true;
1296 if ( !$iranian ) {
1297 $iranian = self::tsToIranian( $ts );
1299 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1300 break;
1301 case 'xmF':
1302 $usedHijriMonth = true;
1303 if ( !$hijri ) {
1304 $hijri = self::tsToHijri( $ts );
1306 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1307 break;
1308 case 'xjF':
1309 $usedHebrewMonth = true;
1310 if ( !$hebrew ) {
1311 $hebrew = self::tsToHebrew( $ts );
1313 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1314 break;
1315 case 'm':
1316 $usedMonth = true;
1317 $num = substr( $ts, 4, 2 );
1318 break;
1319 case 'M':
1320 $usedMonth = true;
1321 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1322 break;
1323 case 'n':
1324 $usedMonth = true;
1325 $num = intval( substr( $ts, 4, 2 ) );
1326 break;
1327 case 'xin':
1328 $usedIranianMonth = true;
1329 if ( !$iranian ) {
1330 $iranian = self::tsToIranian( $ts );
1332 $num = $iranian[1];
1333 break;
1334 case 'xmn':
1335 $usedHijriMonth = true;
1336 if ( !$hijri ) {
1337 $hijri = self::tsToHijri ( $ts );
1339 $num = $hijri[1];
1340 break;
1341 case 'xjn':
1342 $usedHebrewMonth = true;
1343 if ( !$hebrew ) {
1344 $hebrew = self::tsToHebrew( $ts );
1346 $num = $hebrew[1];
1347 break;
1348 case 'xjt':
1349 $usedHebrewMonth = true;
1350 if ( !$hebrew ) {
1351 $hebrew = self::tsToHebrew( $ts );
1353 $num = $hebrew[3];
1354 break;
1355 case 'Y':
1356 $usedYear = true;
1357 $num = substr( $ts, 0, 4 );
1358 break;
1359 case 'xiY':
1360 $usedIranianYear = true;
1361 if ( !$iranian ) {
1362 $iranian = self::tsToIranian( $ts );
1364 $num = $iranian[0];
1365 break;
1366 case 'xmY':
1367 $usedHijriYear = true;
1368 if ( !$hijri ) {
1369 $hijri = self::tsToHijri( $ts );
1371 $num = $hijri[0];
1372 break;
1373 case 'xjY':
1374 $usedHebrewYear = true;
1375 if ( !$hebrew ) {
1376 $hebrew = self::tsToHebrew( $ts );
1378 $num = $hebrew[0];
1379 break;
1380 case 'xkY':
1381 $usedYear = true;
1382 if ( !$thai ) {
1383 $thai = self::tsToYear( $ts, 'thai' );
1385 $num = $thai[0];
1386 break;
1387 case 'xoY':
1388 $usedYear = true;
1389 if ( !$minguo ) {
1390 $minguo = self::tsToYear( $ts, 'minguo' );
1392 $num = $minguo[0];
1393 break;
1394 case 'xtY':
1395 $usedTennoYear = true;
1396 if ( !$tenno ) {
1397 $tenno = self::tsToYear( $ts, 'tenno' );
1399 $num = $tenno[0];
1400 break;
1401 case 'y':
1402 $usedYear = true;
1403 $num = substr( $ts, 2, 2 );
1404 break;
1405 case 'xiy':
1406 $usedIranianYear = true;
1407 if ( !$iranian ) {
1408 $iranian = self::tsToIranian( $ts );
1410 $num = substr( $iranian[0], -2 );
1411 break;
1412 case 'a':
1413 $usedAMPM = true;
1414 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1415 break;
1416 case 'A':
1417 $usedAMPM = true;
1418 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1419 break;
1420 case 'g':
1421 $usedHour = true;
1422 $h = substr( $ts, 8, 2 );
1423 $num = $h % 12 ? $h % 12 : 12;
1424 break;
1425 case 'G':
1426 $usedHour = true;
1427 $num = intval( substr( $ts, 8, 2 ) );
1428 break;
1429 case 'h':
1430 $usedHour = true;
1431 $h = substr( $ts, 8, 2 );
1432 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1433 break;
1434 case 'H':
1435 $usedHour = true;
1436 $num = substr( $ts, 8, 2 );
1437 break;
1438 case 'i':
1439 $usedMinute = true;
1440 $num = substr( $ts, 10, 2 );
1441 break;
1442 case 's':
1443 $usedSecond = true;
1444 $num = substr( $ts, 12, 2 );
1445 break;
1446 case 'c':
1447 case 'r':
1448 $usedSecond = true;
1449 // fall through
1450 case 'e':
1451 case 'O':
1452 case 'P':
1453 case 'T':
1454 $s .= Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1455 break;
1456 case 'w':
1457 case 'N':
1458 case 'z':
1459 $usedDay = true;
1460 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1461 break;
1462 case 'W':
1463 $usedWeek = true;
1464 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1465 break;
1466 case 't':
1467 $usedMonth = true;
1468 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1469 break;
1470 case 'L':
1471 $usedIsLeapYear = true;
1472 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1473 break;
1474 case 'o':
1475 $usedISOYear = true;
1476 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1477 break;
1478 case 'U':
1479 $usedSecond = true;
1480 // fall through
1481 case 'I':
1482 case 'Z':
1483 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1484 break;
1485 case '\\':
1486 # Backslash escaping
1487 if ( $p < $formatLength - 1 ) {
1488 $s .= $format[++$p];
1489 } else {
1490 $s .= '\\';
1492 break;
1493 case '"':
1494 # Quoted literal
1495 if ( $p < $formatLength - 1 ) {
1496 $endQuote = strpos( $format, '"', $p + 1 );
1497 if ( $endQuote === false ) {
1498 # No terminating quote, assume literal "
1499 $s .= '"';
1500 } else {
1501 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1502 $p = $endQuote;
1504 } else {
1505 # Quote at end of string, assume literal "
1506 $s .= '"';
1508 break;
1509 default:
1510 $s .= $format[$p];
1512 if ( $num !== false ) {
1513 if ( $rawToggle || $raw ) {
1514 $s .= $num;
1515 $raw = false;
1516 } elseif ( $roman ) {
1517 $s .= Language::romanNumeral( $num );
1518 $roman = false;
1519 } elseif ( $hebrewNum ) {
1520 $s .= self::hebrewNumeral( $num );
1521 $hebrewNum = false;
1522 } else {
1523 $s .= $this->formatNum( $num, true );
1528 if ( $usedSecond ) {
1529 $ttl = 1;
1530 } elseif ( $usedMinute ) {
1531 $ttl = 60 - substr( $ts, 12, 2 );
1532 } elseif ( $usedHour ) {
1533 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1534 } elseif ( $usedAMPM ) {
1535 $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1536 } elseif ( $usedDay || $usedHebrewMonth || $usedIranianMonth || $usedHijriMonth || $usedHebrewYear || $usedIranianYear || $usedHijriYear || $usedTennoYear ) {
1537 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1538 // so that they don't need purged every day.
1539 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1540 } else {
1541 $possibleTtls = array();
1542 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1543 if ( $usedWeek ) {
1544 $possibleTtls[] = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1545 } elseif ( $usedISOYear ) {
1546 // December 28th falls on the last ISO week of the year, every year.
1547 // The last ISO week of a year can be 52 or 53.
1548 $lastWeekOfISOYear = DateTime::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?: new DateTimeZone( 'UTC' ) )->format( 'W' );
1549 $currentISOWeek = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1550 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1551 $timeRemainingInWeek = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1552 $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1555 if ( $usedMonth ) {
1556 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 + $timeRemainingInDay;
1557 } elseif ( $usedYear ) {
1558 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1559 + $timeRemainingInDay;
1560 } elseif ( $usedIsLeapYear ) {
1561 $year = substr( $ts, 0, 4 );
1562 $timeRemainingInYear = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1563 + $timeRemainingInDay;
1564 $mod = $year % 4;
1565 if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1566 // this isn't a leap year. see when the next one starts
1567 $nextCandidate = $year - $mod + 4;
1568 if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1569 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 + $timeRemainingInYear;
1570 } else {
1571 $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 + $timeRemainingInYear;
1573 } else {
1574 // this is a leap year, so the next year isn't
1575 $possibleTtls[] = $timeRemainingInYear;
1579 if ( $possibleTtls ) {
1580 $ttl = min( $possibleTtls );
1584 return $s;
1587 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1588 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1591 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1592 * Gregorian dates to Iranian dates. Originally written in C, it
1593 * is released under the terms of GNU Lesser General Public
1594 * License. Conversion to PHP was performed by Niklas Laxström.
1596 * Link: http://www.farsiweb.info/jalali/jalali.c
1598 * @param string $ts
1600 * @return string
1602 private static function tsToIranian( $ts ) {
1603 $gy = substr( $ts, 0, 4 ) -1600;
1604 $gm = substr( $ts, 4, 2 ) -1;
1605 $gd = substr( $ts, 6, 2 ) -1;
1607 # Days passed from the beginning (including leap years)
1608 $gDayNo = 365 * $gy
1609 + floor( ( $gy + 3 ) / 4 )
1610 - floor( ( $gy + 99 ) / 100 )
1611 + floor( ( $gy + 399 ) / 400 );
1613 // Add days of the past months of this year
1614 for ( $i = 0; $i < $gm; $i++ ) {
1615 $gDayNo += self::$GREG_DAYS[$i];
1618 // Leap years
1619 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1620 $gDayNo++;
1623 // Days passed in current month
1624 $gDayNo += (int)$gd;
1626 $jDayNo = $gDayNo - 79;
1628 $jNp = floor( $jDayNo / 12053 );
1629 $jDayNo %= 12053;
1631 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1632 $jDayNo %= 1461;
1634 if ( $jDayNo >= 366 ) {
1635 $jy += floor( ( $jDayNo - 1 ) / 365 );
1636 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1639 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1640 $jDayNo -= self::$IRANIAN_DAYS[$i];
1643 $jm = $i + 1;
1644 $jd = $jDayNo + 1;
1646 return array( $jy, $jm, $jd );
1650 * Converting Gregorian dates to Hijri dates.
1652 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1654 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1656 * @param string $ts
1658 * @return string
1660 private static function tsToHijri( $ts ) {
1661 $year = substr( $ts, 0, 4 );
1662 $month = substr( $ts, 4, 2 );
1663 $day = substr( $ts, 6, 2 );
1665 $zyr = $year;
1666 $zd = $day;
1667 $zm = $month;
1668 $zy = $zyr;
1670 if (
1671 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1672 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1674 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1675 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1676 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1677 $zd - 32075;
1678 } else {
1679 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1680 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1683 $zl = $zjd -1948440 + 10632;
1684 $zn = (int)( ( $zl - 1 ) / 10631 );
1685 $zl = $zl - 10631 * $zn + 354;
1686 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1687 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1688 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1689 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1690 $zm = (int)( ( 24 * $zl ) / 709 );
1691 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1692 $zy = 30 * $zn + $zj - 30;
1694 return array( $zy, $zm, $zd );
1698 * Converting Gregorian dates to Hebrew dates.
1700 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1701 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1702 * to translate the relevant functions into PHP and release them under
1703 * GNU GPL.
1705 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1706 * and Adar II is 14. In a non-leap year, Adar is 6.
1708 * @param string $ts
1710 * @return string
1712 private static function tsToHebrew( $ts ) {
1713 # Parse date
1714 $year = substr( $ts, 0, 4 );
1715 $month = substr( $ts, 4, 2 );
1716 $day = substr( $ts, 6, 2 );
1718 # Calculate Hebrew year
1719 $hebrewYear = $year + 3760;
1721 # Month number when September = 1, August = 12
1722 $month += 4;
1723 if ( $month > 12 ) {
1724 # Next year
1725 $month -= 12;
1726 $year++;
1727 $hebrewYear++;
1730 # Calculate day of year from 1 September
1731 $dayOfYear = $day;
1732 for ( $i = 1; $i < $month; $i++ ) {
1733 if ( $i == 6 ) {
1734 # February
1735 $dayOfYear += 28;
1736 # Check if the year is leap
1737 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1738 $dayOfYear++;
1740 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1741 $dayOfYear += 30;
1742 } else {
1743 $dayOfYear += 31;
1747 # Calculate the start of the Hebrew year
1748 $start = self::hebrewYearStart( $hebrewYear );
1750 # Calculate next year's start
1751 if ( $dayOfYear <= $start ) {
1752 # Day is before the start of the year - it is the previous year
1753 # Next year's start
1754 $nextStart = $start;
1755 # Previous year
1756 $year--;
1757 $hebrewYear--;
1758 # Add days since previous year's 1 September
1759 $dayOfYear += 365;
1760 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1761 # Leap year
1762 $dayOfYear++;
1764 # Start of the new (previous) year
1765 $start = self::hebrewYearStart( $hebrewYear );
1766 } else {
1767 # Next year's start
1768 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1771 # Calculate Hebrew day of year
1772 $hebrewDayOfYear = $dayOfYear - $start;
1774 # Difference between year's days
1775 $diff = $nextStart - $start;
1776 # Add 12 (or 13 for leap years) days to ignore the difference between
1777 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1778 # difference is only about the year type
1779 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1780 $diff += 13;
1781 } else {
1782 $diff += 12;
1785 # Check the year pattern, and is leap year
1786 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1787 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1788 # and non-leap years
1789 $yearPattern = $diff % 30;
1790 # Check if leap year
1791 $isLeap = $diff >= 30;
1793 # Calculate day in the month from number of day in the Hebrew year
1794 # Don't check Adar - if the day is not in Adar, we will stop before;
1795 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1796 $hebrewDay = $hebrewDayOfYear;
1797 $hebrewMonth = 1;
1798 $days = 0;
1799 while ( $hebrewMonth <= 12 ) {
1800 # Calculate days in this month
1801 if ( $isLeap && $hebrewMonth == 6 ) {
1802 # Adar in a leap year
1803 if ( $isLeap ) {
1804 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1805 $days = 30;
1806 if ( $hebrewDay <= $days ) {
1807 # Day in Adar I
1808 $hebrewMonth = 13;
1809 } else {
1810 # Subtract the days of Adar I
1811 $hebrewDay -= $days;
1812 # Try Adar II
1813 $days = 29;
1814 if ( $hebrewDay <= $days ) {
1815 # Day in Adar II
1816 $hebrewMonth = 14;
1820 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1821 # Cheshvan in a complete year (otherwise as the rule below)
1822 $days = 30;
1823 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1824 # Kislev in an incomplete year (otherwise as the rule below)
1825 $days = 29;
1826 } else {
1827 # Odd months have 30 days, even have 29
1828 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1830 if ( $hebrewDay <= $days ) {
1831 # In the current month
1832 break;
1833 } else {
1834 # Subtract the days of the current month
1835 $hebrewDay -= $days;
1836 # Try in the next month
1837 $hebrewMonth++;
1841 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1845 * This calculates the Hebrew year start, as days since 1 September.
1846 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1847 * Used for Hebrew date.
1849 * @param int $year
1851 * @return string
1853 private static function hebrewYearStart( $year ) {
1854 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1855 $b = intval( ( $year - 1 ) % 4 );
1856 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1857 if ( $m < 0 ) {
1858 $m--;
1860 $Mar = intval( $m );
1861 if ( $m < 0 ) {
1862 $m++;
1864 $m -= $Mar;
1866 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1867 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1868 $Mar++;
1869 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1870 $Mar += 2;
1871 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1872 $Mar++;
1875 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1876 return $Mar;
1880 * Algorithm to convert Gregorian dates to Thai solar dates,
1881 * Minguo dates or Minguo dates.
1883 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1884 * http://en.wikipedia.org/wiki/Minguo_calendar
1885 * http://en.wikipedia.org/wiki/Japanese_era_name
1887 * @param string $ts 14-character timestamp
1888 * @param string $cName Calender name
1889 * @return array Converted year, month, day
1891 private static function tsToYear( $ts, $cName ) {
1892 $gy = substr( $ts, 0, 4 );
1893 $gm = substr( $ts, 4, 2 );
1894 $gd = substr( $ts, 6, 2 );
1896 if ( !strcmp( $cName, 'thai' ) ) {
1897 # Thai solar dates
1898 # Add 543 years to the Gregorian calendar
1899 # Months and days are identical
1900 $gy_offset = $gy + 543;
1901 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1902 # Minguo dates
1903 # Deduct 1911 years from the Gregorian calendar
1904 # Months and days are identical
1905 $gy_offset = $gy - 1911;
1906 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1907 # Nengō dates up to Meiji period
1908 # Deduct years from the Gregorian calendar
1909 # depending on the nengo periods
1910 # Months and days are identical
1911 if ( ( $gy < 1912 )
1912 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1913 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1915 # Meiji period
1916 $gy_gannen = $gy - 1868 + 1;
1917 $gy_offset = $gy_gannen;
1918 if ( $gy_gannen == 1 ) {
1919 $gy_offset = '元';
1921 $gy_offset = '明治' . $gy_offset;
1922 } elseif (
1923 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1924 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1925 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1926 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1927 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1929 # Taishō period
1930 $gy_gannen = $gy - 1912 + 1;
1931 $gy_offset = $gy_gannen;
1932 if ( $gy_gannen == 1 ) {
1933 $gy_offset = '元';
1935 $gy_offset = '大正' . $gy_offset;
1936 } elseif (
1937 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1938 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1939 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1941 # Shōwa period
1942 $gy_gannen = $gy - 1926 + 1;
1943 $gy_offset = $gy_gannen;
1944 if ( $gy_gannen == 1 ) {
1945 $gy_offset = '元';
1947 $gy_offset = '昭和' . $gy_offset;
1948 } else {
1949 # Heisei period
1950 $gy_gannen = $gy - 1989 + 1;
1951 $gy_offset = $gy_gannen;
1952 if ( $gy_gannen == 1 ) {
1953 $gy_offset = '元';
1955 $gy_offset = '平成' . $gy_offset;
1957 } else {
1958 $gy_offset = $gy;
1961 return array( $gy_offset, $gm, $gd );
1965 * Roman number formatting up to 10000
1967 * @param int $num
1969 * @return string
1971 static function romanNumeral( $num ) {
1972 static $table = array(
1973 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1974 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1975 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1976 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1977 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1980 $num = intval( $num );
1981 if ( $num > 10000 || $num <= 0 ) {
1982 return $num;
1985 $s = '';
1986 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1987 if ( $num >= $pow10 ) {
1988 $s .= $table[$i][(int)floor( $num / $pow10 )];
1990 $num = $num % $pow10;
1992 return $s;
1996 * Hebrew Gematria number formatting up to 9999
1998 * @param int $num
2000 * @return string
2002 static function hebrewNumeral( $num ) {
2003 static $table = array(
2004 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
2005 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
2006 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
2007 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
2010 $num = intval( $num );
2011 if ( $num > 9999 || $num <= 0 ) {
2012 return $num;
2015 $s = '';
2016 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2017 if ( $num >= $pow10 ) {
2018 if ( $num == 15 || $num == 16 ) {
2019 $s .= $table[0][9] . $table[0][$num - 9];
2020 $num = 0;
2021 } else {
2022 $s .= $table[$i][intval( ( $num / $pow10 ) )];
2023 if ( $pow10 == 1000 ) {
2024 $s .= "'";
2028 $num = $num % $pow10;
2030 if ( strlen( $s ) == 2 ) {
2031 $str = $s . "'";
2032 } else {
2033 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
2034 $str .= substr( $s, strlen( $s ) - 2, 2 );
2036 $start = substr( $str, 0, strlen( $str ) - 2 );
2037 $end = substr( $str, strlen( $str ) - 2 );
2038 switch ( $end ) {
2039 case 'כ':
2040 $str = $start . 'ך';
2041 break;
2042 case 'מ':
2043 $str = $start . 'ם';
2044 break;
2045 case 'נ':
2046 $str = $start . 'ן';
2047 break;
2048 case 'פ':
2049 $str = $start . 'ף';
2050 break;
2051 case 'צ':
2052 $str = $start . 'ץ';
2053 break;
2055 return $str;
2059 * Used by date() and time() to adjust the time output.
2061 * @param string $ts The time in date('YmdHis') format
2062 * @param mixed $tz Adjust the time by this amount (default false, mean we
2063 * get user timecorrection setting)
2064 * @return int
2066 function userAdjust( $ts, $tz = false ) {
2067 global $wgUser, $wgLocalTZoffset;
2069 if ( $tz === false ) {
2070 $tz = $wgUser->getOption( 'timecorrection' );
2073 $data = explode( '|', $tz, 3 );
2075 if ( $data[0] == 'ZoneInfo' ) {
2076 wfSuppressWarnings();
2077 $userTZ = timezone_open( $data[2] );
2078 wfRestoreWarnings();
2079 if ( $userTZ !== false ) {
2080 $date = date_create( $ts, timezone_open( 'UTC' ) );
2081 date_timezone_set( $date, $userTZ );
2082 $date = date_format( $date, 'YmdHis' );
2083 return $date;
2085 # Unrecognized timezone, default to 'Offset' with the stored offset.
2086 $data[0] = 'Offset';
2089 if ( $data[0] == 'System' || $tz == '' ) {
2090 # Global offset in minutes.
2091 $minDiff = $wgLocalTZoffset;
2092 } elseif ( $data[0] == 'Offset' ) {
2093 $minDiff = intval( $data[1] );
2094 } else {
2095 $data = explode( ':', $tz );
2096 if ( count( $data ) == 2 ) {
2097 $data[0] = intval( $data[0] );
2098 $data[1] = intval( $data[1] );
2099 $minDiff = abs( $data[0] ) * 60 + $data[1];
2100 if ( $data[0] < 0 ) {
2101 $minDiff = -$minDiff;
2103 } else {
2104 $minDiff = intval( $data[0] ) * 60;
2108 # No difference ? Return time unchanged
2109 if ( 0 == $minDiff ) {
2110 return $ts;
2113 wfSuppressWarnings(); // E_STRICT system time bitching
2114 # Generate an adjusted date; take advantage of the fact that mktime
2115 # will normalize out-of-range values so we don't have to split $minDiff
2116 # into hours and minutes.
2117 $t = mktime( (
2118 (int)substr( $ts, 8, 2 ) ), # Hours
2119 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2120 (int)substr( $ts, 12, 2 ), # Seconds
2121 (int)substr( $ts, 4, 2 ), # Month
2122 (int)substr( $ts, 6, 2 ), # Day
2123 (int)substr( $ts, 0, 4 ) ); # Year
2125 $date = date( 'YmdHis', $t );
2126 wfRestoreWarnings();
2128 return $date;
2132 * This is meant to be used by time(), date(), and timeanddate() to get
2133 * the date preference they're supposed to use, it should be used in
2134 * all children.
2136 *<code>
2137 * function timeanddate([...], $format = true) {
2138 * $datePreference = $this->dateFormat($format);
2139 * [...]
2141 *</code>
2143 * @param int|string|bool $usePrefs If true, the user's preference is used
2144 * if false, the site/language default is used
2145 * if int/string, assumed to be a format.
2146 * @return string
2148 function dateFormat( $usePrefs = true ) {
2149 global $wgUser;
2151 if ( is_bool( $usePrefs ) ) {
2152 if ( $usePrefs ) {
2153 $datePreference = $wgUser->getDatePreference();
2154 } else {
2155 $datePreference = (string)User::getDefaultOption( 'date' );
2157 } else {
2158 $datePreference = (string)$usePrefs;
2161 // return int
2162 if ( $datePreference == '' ) {
2163 return 'default';
2166 return $datePreference;
2170 * Get a format string for a given type and preference
2171 * @param string $type May be date, time or both
2172 * @param string $pref The format name as it appears in Messages*.php
2174 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2176 * @return string
2178 function getDateFormatString( $type, $pref ) {
2179 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2180 if ( $pref == 'default' ) {
2181 $pref = $this->getDefaultDateFormat();
2182 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2183 } else {
2184 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2186 if ( $type === 'pretty' && $df === null ) {
2187 $df = $this->getDateFormatString( 'date', $pref );
2190 if ( $df === null ) {
2191 $pref = $this->getDefaultDateFormat();
2192 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2195 $this->dateFormatStrings[$type][$pref] = $df;
2197 return $this->dateFormatStrings[$type][$pref];
2201 * @param string $ts The time format which needs to be turned into a
2202 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2203 * @param bool $adj Whether to adjust the time output according to the
2204 * user configured offset ($timecorrection)
2205 * @param mixed $format True to use user's date format preference
2206 * @param string|bool $timecorrection The time offset as returned by
2207 * validateTimeZone() in Special:Preferences
2208 * @return string
2210 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2211 $ts = wfTimestamp( TS_MW, $ts );
2212 if ( $adj ) {
2213 $ts = $this->userAdjust( $ts, $timecorrection );
2215 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2216 return $this->sprintfDate( $df, $ts );
2220 * @param string $ts The time format which needs to be turned into a
2221 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2222 * @param bool $adj Whether to adjust the time output according to the
2223 * user configured offset ($timecorrection)
2224 * @param mixed $format True to use user's date format preference
2225 * @param string|bool $timecorrection The time offset as returned by
2226 * validateTimeZone() in Special:Preferences
2227 * @return string
2229 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2230 $ts = wfTimestamp( TS_MW, $ts );
2231 if ( $adj ) {
2232 $ts = $this->userAdjust( $ts, $timecorrection );
2234 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2235 return $this->sprintfDate( $df, $ts );
2239 * @param string $ts The time format which needs to be turned into a
2240 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2241 * @param bool $adj Whether to adjust the time output according to the
2242 * user configured offset ($timecorrection)
2243 * @param mixed $format What format to return, if it's false output the
2244 * default one (default true)
2245 * @param string|bool $timecorrection The time offset as returned by
2246 * validateTimeZone() in Special:Preferences
2247 * @return string
2249 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2250 $ts = wfTimestamp( TS_MW, $ts );
2251 if ( $adj ) {
2252 $ts = $this->userAdjust( $ts, $timecorrection );
2254 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2255 return $this->sprintfDate( $df, $ts );
2259 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2261 * @since 1.20
2263 * @param int $seconds The amount of seconds.
2264 * @param array $chosenIntervals The intervals to enable.
2266 * @return string
2268 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2269 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2271 $segments = array();
2273 foreach ( $intervals as $intervalName => $intervalValue ) {
2274 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2275 // duration-years, duration-decades, duration-centuries, duration-millennia
2276 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2277 $segments[] = $message->inLanguage( $this )->escaped();
2280 return $this->listToText( $segments );
2284 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2285 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2287 * @since 1.20
2289 * @param int $seconds The amount of seconds.
2290 * @param array $chosenIntervals The intervals to enable.
2292 * @return array
2294 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2295 if ( empty( $chosenIntervals ) ) {
2296 $chosenIntervals = array(
2297 'millennia',
2298 'centuries',
2299 'decades',
2300 'years',
2301 'days',
2302 'hours',
2303 'minutes',
2304 'seconds'
2308 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2309 $sortedNames = array_keys( $intervals );
2310 $smallestInterval = array_pop( $sortedNames );
2312 $segments = array();
2314 foreach ( $intervals as $name => $length ) {
2315 $value = floor( $seconds / $length );
2317 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2318 $seconds -= $value * $length;
2319 $segments[$name] = $value;
2323 return $segments;
2327 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2329 * @param string $type Can be 'date', 'time' or 'both'
2330 * @param string $ts The time format which needs to be turned into a
2331 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2332 * @param User $user User object used to get preferences for timezone and format
2333 * @param array $options Array, can contain the following keys:
2334 * - 'timecorrection': time correction, can have the following values:
2335 * - true: use user's preference
2336 * - false: don't use time correction
2337 * - int: value of time correction in minutes
2338 * - 'format': format to use, can have the following values:
2339 * - true: use user's preference
2340 * - false: use default preference
2341 * - string: format to use
2342 * @since 1.19
2343 * @return string
2345 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2346 $ts = wfTimestamp( TS_MW, $ts );
2347 $options += array( 'timecorrection' => true, 'format' => true );
2348 if ( $options['timecorrection'] !== false ) {
2349 if ( $options['timecorrection'] === true ) {
2350 $offset = $user->getOption( 'timecorrection' );
2351 } else {
2352 $offset = $options['timecorrection'];
2354 $ts = $this->userAdjust( $ts, $offset );
2356 if ( $options['format'] === true ) {
2357 $format = $user->getDatePreference();
2358 } else {
2359 $format = $options['format'];
2361 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2362 return $this->sprintfDate( $df, $ts );
2366 * Get the formatted date for the given timestamp and formatted for
2367 * the given user.
2369 * @param mixed $ts Mixed: the time format which needs to be turned into a
2370 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2371 * @param User $user User object used to get preferences for timezone and format
2372 * @param array $options Array, can contain the following keys:
2373 * - 'timecorrection': time correction, can have the following values:
2374 * - true: use user's preference
2375 * - false: don't use time correction
2376 * - int: value of time correction in minutes
2377 * - 'format': format to use, can have the following values:
2378 * - true: use user's preference
2379 * - false: use default preference
2380 * - string: format to use
2381 * @since 1.19
2382 * @return string
2384 public function userDate( $ts, User $user, array $options = array() ) {
2385 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2389 * Get the formatted time for the given timestamp and formatted for
2390 * the given user.
2392 * @param mixed $ts The time format which needs to be turned into a
2393 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2394 * @param User $user User object used to get preferences for timezone and format
2395 * @param array $options Array, can contain the following keys:
2396 * - 'timecorrection': time correction, can have the following values:
2397 * - true: use user's preference
2398 * - false: don't use time correction
2399 * - int: value of time correction in minutes
2400 * - 'format': format to use, can have the following values:
2401 * - true: use user's preference
2402 * - false: use default preference
2403 * - string: format to use
2404 * @since 1.19
2405 * @return string
2407 public function userTime( $ts, User $user, array $options = array() ) {
2408 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2412 * Get the formatted date and time for the given timestamp and formatted for
2413 * the given user.
2415 * @param mixed $ts The time format which needs to be turned into a
2416 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2417 * @param User $user User object used to get preferences for timezone and format
2418 * @param array $options Array, can contain the following keys:
2419 * - 'timecorrection': time correction, can have the following values:
2420 * - true: use user's preference
2421 * - false: don't use time correction
2422 * - int: value of time correction in minutes
2423 * - 'format': format to use, can have the following values:
2424 * - true: use user's preference
2425 * - false: use default preference
2426 * - string: format to use
2427 * @since 1.19
2428 * @return string
2430 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2431 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2435 * Convert an MWTimestamp into a pretty human-readable timestamp using
2436 * the given user preferences and relative base time.
2438 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2439 * on your timestamp object, which will then call this function. Calling
2440 * this function directly will cause hooks to be skipped over.
2442 * @see MWTimestamp::getHumanTimestamp
2443 * @param MWTimestamp $ts Timestamp to prettify
2444 * @param MWTimestamp $relativeTo Base timestamp
2445 * @param User $user User preferences to use
2446 * @return string Human timestamp
2447 * @since 1.22
2449 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2450 $diff = $ts->diff( $relativeTo );
2451 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2452 (int)$relativeTo->timestamp->format( 'w' ) );
2453 $days = $diff->days ?: (int)$diffDay;
2454 if ( $diff->invert || $days > 5
2455 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2457 // Timestamps are in different years: use full timestamp
2458 // Also do full timestamp for future dates
2460 * @todo FIXME: Add better handling of future timestamps.
2462 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2463 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2464 } elseif ( $days > 5 ) {
2465 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2466 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2467 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2468 } elseif ( $days > 1 ) {
2469 // Timestamp within the past week: show the day of the week and time
2470 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2471 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2472 // Messages:
2473 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2474 $ts = wfMessage( "$weekday-at" )
2475 ->inLanguage( $this )
2476 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2477 ->text();
2478 } elseif ( $days == 1 ) {
2479 // Timestamp was yesterday: say 'yesterday' and the time.
2480 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2481 $ts = wfMessage( 'yesterday-at' )
2482 ->inLanguage( $this )
2483 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2484 ->text();
2485 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2486 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2487 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2488 $ts = wfMessage( 'today-at' )
2489 ->inLanguage( $this )
2490 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2491 ->text();
2493 // From here on in, the timestamp was soon enough ago so that we can simply say
2494 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2495 } elseif ( $diff->h == 1 ) {
2496 // Less than 90 minutes, but more than an hour ago.
2497 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2498 } elseif ( $diff->i >= 1 ) {
2499 // A few minutes ago.
2500 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2501 } elseif ( $diff->s >= 30 ) {
2502 // Less than a minute, but more than 30 sec ago.
2503 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2504 } else {
2505 // Less than 30 seconds ago.
2506 $ts = wfMessage( 'just-now' )->text();
2509 return $ts;
2513 * @param string $key
2514 * @return array|null
2516 function getMessage( $key ) {
2517 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2521 * @return array
2523 function getAllMessages() {
2524 return self::$dataCache->getItem( $this->mCode, 'messages' );
2528 * @param string $in
2529 * @param string $out
2530 * @param string $string
2531 * @return string
2533 function iconv( $in, $out, $string ) {
2534 # This is a wrapper for iconv in all languages except esperanto,
2535 # which does some nasty x-conversions beforehand
2537 # Even with //IGNORE iconv can whine about illegal characters in
2538 # *input* string. We just ignore those too.
2539 # REF: http://bugs.php.net/bug.php?id=37166
2540 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2541 wfSuppressWarnings();
2542 $text = iconv( $in, $out . '//IGNORE', $string );
2543 wfRestoreWarnings();
2544 return $text;
2547 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2550 * @param array $matches
2551 * @return mixed|string
2553 function ucwordbreaksCallbackAscii( $matches ) {
2554 return $this->ucfirst( $matches[1] );
2558 * @param array $matches
2559 * @return string
2561 function ucwordbreaksCallbackMB( $matches ) {
2562 return mb_strtoupper( $matches[0] );
2566 * @param array $matches
2567 * @return string
2569 function ucCallback( $matches ) {
2570 list( $wikiUpperChars ) = self::getCaseMaps();
2571 return strtr( $matches[1], $wikiUpperChars );
2575 * @param array $matches
2576 * @return string
2578 function lcCallback( $matches ) {
2579 list( , $wikiLowerChars ) = self::getCaseMaps();
2580 return strtr( $matches[1], $wikiLowerChars );
2584 * @param array $matches
2585 * @return string
2587 function ucwordsCallbackMB( $matches ) {
2588 return mb_strtoupper( $matches[0] );
2592 * @param array $matches
2593 * @return string
2595 function ucwordsCallbackWiki( $matches ) {
2596 list( $wikiUpperChars ) = self::getCaseMaps();
2597 return strtr( $matches[0], $wikiUpperChars );
2601 * Make a string's first character uppercase
2603 * @param string $str
2605 * @return string
2607 function ucfirst( $str ) {
2608 $o = ord( $str );
2609 if ( $o < 96 ) { // if already uppercase...
2610 return $str;
2611 } elseif ( $o < 128 ) {
2612 return ucfirst( $str ); // use PHP's ucfirst()
2613 } else {
2614 // fall back to more complex logic in case of multibyte strings
2615 return $this->uc( $str, true );
2620 * Convert a string to uppercase
2622 * @param string $str
2623 * @param bool $first
2625 * @return string
2627 function uc( $str, $first = false ) {
2628 if ( function_exists( 'mb_strtoupper' ) ) {
2629 if ( $first ) {
2630 if ( $this->isMultibyte( $str ) ) {
2631 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2632 } else {
2633 return ucfirst( $str );
2635 } else {
2636 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2638 } else {
2639 if ( $this->isMultibyte( $str ) ) {
2640 $x = $first ? '^' : '';
2641 return preg_replace_callback(
2642 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2643 array( $this, 'ucCallback' ),
2644 $str
2646 } else {
2647 return $first ? ucfirst( $str ) : strtoupper( $str );
2653 * @param string $str
2654 * @return mixed|string
2656 function lcfirst( $str ) {
2657 $o = ord( $str );
2658 if ( !$o ) {
2659 return strval( $str );
2660 } elseif ( $o >= 128 ) {
2661 return $this->lc( $str, true );
2662 } elseif ( $o > 96 ) {
2663 return $str;
2664 } else {
2665 $str[0] = strtolower( $str[0] );
2666 return $str;
2671 * @param string $str
2672 * @param bool $first
2673 * @return mixed|string
2675 function lc( $str, $first = false ) {
2676 if ( function_exists( 'mb_strtolower' ) ) {
2677 if ( $first ) {
2678 if ( $this->isMultibyte( $str ) ) {
2679 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2680 } else {
2681 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2683 } else {
2684 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2686 } else {
2687 if ( $this->isMultibyte( $str ) ) {
2688 $x = $first ? '^' : '';
2689 return preg_replace_callback(
2690 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2691 array( $this, 'lcCallback' ),
2692 $str
2694 } else {
2695 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2701 * @param string $str
2702 * @return bool
2704 function isMultibyte( $str ) {
2705 return (bool)preg_match( '/[\x80-\xff]/', $str );
2709 * @param string $str
2710 * @return mixed|string
2712 function ucwords( $str ) {
2713 if ( $this->isMultibyte( $str ) ) {
2714 $str = $this->lc( $str );
2716 // regexp to find first letter in each word (i.e. after each space)
2717 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2719 // function to use to capitalize a single char
2720 if ( function_exists( 'mb_strtoupper' ) ) {
2721 return preg_replace_callback(
2722 $replaceRegexp,
2723 array( $this, 'ucwordsCallbackMB' ),
2724 $str
2726 } else {
2727 return preg_replace_callback(
2728 $replaceRegexp,
2729 array( $this, 'ucwordsCallbackWiki' ),
2730 $str
2733 } else {
2734 return ucwords( strtolower( $str ) );
2739 * capitalize words at word breaks
2741 * @param string $str
2742 * @return mixed
2744 function ucwordbreaks( $str ) {
2745 if ( $this->isMultibyte( $str ) ) {
2746 $str = $this->lc( $str );
2748 // since \b doesn't work for UTF-8, we explicitely define word break chars
2749 $breaks = "[ \-\(\)\}\{\.,\?!]";
2751 // find first letter after word break
2752 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2753 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2755 if ( function_exists( 'mb_strtoupper' ) ) {
2756 return preg_replace_callback(
2757 $replaceRegexp,
2758 array( $this, 'ucwordbreaksCallbackMB' ),
2759 $str
2761 } else {
2762 return preg_replace_callback(
2763 $replaceRegexp,
2764 array( $this, 'ucwordsCallbackWiki' ),
2765 $str
2768 } else {
2769 return preg_replace_callback(
2770 '/\b([\w\x80-\xff]+)\b/',
2771 array( $this, 'ucwordbreaksCallbackAscii' ),
2772 $str
2778 * Return a case-folded representation of $s
2780 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2781 * and $s2 are the same except for the case of their characters. It is not
2782 * necessary for the value returned to make sense when displayed.
2784 * Do *not* perform any other normalisation in this function. If a caller
2785 * uses this function when it should be using a more general normalisation
2786 * function, then fix the caller.
2788 * @param string $s
2790 * @return string
2792 function caseFold( $s ) {
2793 return $this->uc( $s );
2797 * @param string $s
2798 * @return string
2800 function checkTitleEncoding( $s ) {
2801 if ( is_array( $s ) ) {
2802 throw new MWException( 'Given array to checkTitleEncoding.' );
2804 if ( StringUtils::isUtf8( $s ) ) {
2805 return $s;
2808 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2812 * @return array
2814 function fallback8bitEncoding() {
2815 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2819 * Most writing systems use whitespace to break up words.
2820 * Some languages such as Chinese don't conventionally do this,
2821 * which requires special handling when breaking up words for
2822 * searching etc.
2824 * @return bool
2826 function hasWordBreaks() {
2827 return true;
2831 * Some languages such as Chinese require word segmentation,
2832 * Specify such segmentation when overridden in derived class.
2834 * @param string $string
2835 * @return string
2837 function segmentByWord( $string ) {
2838 return $string;
2842 * Some languages have special punctuation need to be normalized.
2843 * Make such changes here.
2845 * @param string $string
2846 * @return string
2848 function normalizeForSearch( $string ) {
2849 return self::convertDoubleWidth( $string );
2853 * convert double-width roman characters to single-width.
2854 * range: ff00-ff5f ~= 0020-007f
2856 * @param string $string
2858 * @return string
2860 protected static function convertDoubleWidth( $string ) {
2861 static $full = null;
2862 static $half = null;
2864 if ( $full === null ) {
2865 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2866 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2867 $full = str_split( $fullWidth, 3 );
2868 $half = str_split( $halfWidth );
2871 $string = str_replace( $full, $half, $string );
2872 return $string;
2876 * @param string $string
2877 * @param string $pattern
2878 * @return string
2880 protected static function insertSpace( $string, $pattern ) {
2881 $string = preg_replace( $pattern, " $1 ", $string );
2882 $string = preg_replace( '/ +/', ' ', $string );
2883 return $string;
2887 * @param array $termsArray
2888 * @return array
2890 function convertForSearchResult( $termsArray ) {
2891 # some languages, e.g. Chinese, need to do a conversion
2892 # in order for search results to be displayed correctly
2893 return $termsArray;
2897 * Get the first character of a string.
2899 * @param string $s
2900 * @return string
2902 function firstChar( $s ) {
2903 $matches = array();
2904 preg_match(
2905 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2906 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2908 $matches
2911 if ( isset( $matches[1] ) ) {
2912 if ( strlen( $matches[1] ) != 3 ) {
2913 return $matches[1];
2916 // Break down Hangul syllables to grab the first jamo
2917 $code = utf8ToCodepoint( $matches[1] );
2918 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2919 return $matches[1];
2920 } elseif ( $code < 0xb098 ) {
2921 return "\xe3\x84\xb1";
2922 } elseif ( $code < 0xb2e4 ) {
2923 return "\xe3\x84\xb4";
2924 } elseif ( $code < 0xb77c ) {
2925 return "\xe3\x84\xb7";
2926 } elseif ( $code < 0xb9c8 ) {
2927 return "\xe3\x84\xb9";
2928 } elseif ( $code < 0xbc14 ) {
2929 return "\xe3\x85\x81";
2930 } elseif ( $code < 0xc0ac ) {
2931 return "\xe3\x85\x82";
2932 } elseif ( $code < 0xc544 ) {
2933 return "\xe3\x85\x85";
2934 } elseif ( $code < 0xc790 ) {
2935 return "\xe3\x85\x87";
2936 } elseif ( $code < 0xcc28 ) {
2937 return "\xe3\x85\x88";
2938 } elseif ( $code < 0xce74 ) {
2939 return "\xe3\x85\x8a";
2940 } elseif ( $code < 0xd0c0 ) {
2941 return "\xe3\x85\x8b";
2942 } elseif ( $code < 0xd30c ) {
2943 return "\xe3\x85\x8c";
2944 } elseif ( $code < 0xd558 ) {
2945 return "\xe3\x85\x8d";
2946 } else {
2947 return "\xe3\x85\x8e";
2949 } else {
2950 return '';
2954 function initEncoding() {
2955 # Some languages may have an alternate char encoding option
2956 # (Esperanto X-coding, Japanese furigana conversion, etc)
2957 # If this language is used as the primary content language,
2958 # an override to the defaults can be set here on startup.
2962 * @param string $s
2963 * @return string
2965 function recodeForEdit( $s ) {
2966 # For some languages we'll want to explicitly specify
2967 # which characters make it into the edit box raw
2968 # or are converted in some way or another.
2969 global $wgEditEncoding;
2970 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2971 return $s;
2972 } else {
2973 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2978 * @param string $s
2979 * @return string
2981 function recodeInput( $s ) {
2982 # Take the previous into account.
2983 global $wgEditEncoding;
2984 if ( $wgEditEncoding != '' ) {
2985 $enc = $wgEditEncoding;
2986 } else {
2987 $enc = 'UTF-8';
2989 if ( $enc == 'UTF-8' ) {
2990 return $s;
2991 } else {
2992 return $this->iconv( $enc, 'UTF-8', $s );
2997 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2998 * also cleans up certain backwards-compatible sequences, converting them
2999 * to the modern Unicode equivalent.
3001 * This is language-specific for performance reasons only.
3003 * @param string $s
3005 * @return string
3007 function normalize( $s ) {
3008 global $wgAllUnicodeFixes;
3009 $s = UtfNormal::cleanUp( $s );
3010 if ( $wgAllUnicodeFixes ) {
3011 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
3012 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
3015 return $s;
3019 * Transform a string using serialized data stored in the given file (which
3020 * must be in the serialized subdirectory of $IP). The file contains pairs
3021 * mapping source characters to destination characters.
3023 * The data is cached in process memory. This will go faster if you have the
3024 * FastStringSearch extension.
3026 * @param string $file
3027 * @param string $string
3029 * @throws MWException
3030 * @return string
3032 function transformUsingPairFile( $file, $string ) {
3033 if ( !isset( $this->transformData[$file] ) ) {
3034 $data = wfGetPrecompiledData( $file );
3035 if ( $data === false ) {
3036 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
3038 $this->transformData[$file] = new ReplacementArray( $data );
3040 return $this->transformData[$file]->replace( $string );
3044 * For right-to-left language support
3046 * @return bool
3048 function isRTL() {
3049 return self::$dataCache->getItem( $this->mCode, 'rtl' );
3053 * Return the correct HTML 'dir' attribute value for this language.
3054 * @return string
3056 function getDir() {
3057 return $this->isRTL() ? 'rtl' : 'ltr';
3061 * Return 'left' or 'right' as appropriate alignment for line-start
3062 * for this language's text direction.
3064 * Should be equivalent to CSS3 'start' text-align value....
3066 * @return string
3068 function alignStart() {
3069 return $this->isRTL() ? 'right' : 'left';
3073 * Return 'right' or 'left' as appropriate alignment for line-end
3074 * for this language's text direction.
3076 * Should be equivalent to CSS3 'end' text-align value....
3078 * @return string
3080 function alignEnd() {
3081 return $this->isRTL() ? 'left' : 'right';
3085 * A hidden direction mark (LRM or RLM), depending on the language direction.
3086 * Unlike getDirMark(), this function returns the character as an HTML entity.
3087 * This function should be used when the output is guaranteed to be HTML,
3088 * because it makes the output HTML source code more readable. When
3089 * the output is plain text or can be escaped, getDirMark() should be used.
3091 * @param bool $opposite Get the direction mark opposite to your language
3092 * @return string
3093 * @since 1.20
3095 function getDirMarkEntity( $opposite = false ) {
3096 if ( $opposite ) {
3097 return $this->isRTL() ? '&lrm;' : '&rlm;';
3099 return $this->isRTL() ? '&rlm;' : '&lrm;';
3103 * A hidden direction mark (LRM or RLM), depending on the language direction.
3104 * This function produces them as invisible Unicode characters and
3105 * the output may be hard to read and debug, so it should only be used
3106 * when the output is plain text or can be escaped. When the output is
3107 * HTML, use getDirMarkEntity() instead.
3109 * @param bool $opposite Get the direction mark opposite to your language
3110 * @return string
3112 function getDirMark( $opposite = false ) {
3113 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3114 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3115 if ( $opposite ) {
3116 return $this->isRTL() ? $lrm : $rlm;
3118 return $this->isRTL() ? $rlm : $lrm;
3122 * @return array
3124 function capitalizeAllNouns() {
3125 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3129 * An arrow, depending on the language direction.
3131 * @param string $direction The direction of the arrow: forwards (default),
3132 * backwards, left, right, up, down.
3133 * @return string
3135 function getArrow( $direction = 'forwards' ) {
3136 switch ( $direction ) {
3137 case 'forwards':
3138 return $this->isRTL() ? '←' : '→';
3139 case 'backwards':
3140 return $this->isRTL() ? '→' : '←';
3141 case 'left':
3142 return '←';
3143 case 'right':
3144 return '→';
3145 case 'up':
3146 return '↑';
3147 case 'down':
3148 return '↓';
3153 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3155 * @return bool
3157 function linkPrefixExtension() {
3158 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
3162 * Get all magic words from cache.
3163 * @return array
3165 function getMagicWords() {
3166 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
3170 * Run the LanguageGetMagic hook once.
3172 protected function doMagicHook() {
3173 if ( $this->mMagicHookDone ) {
3174 return;
3176 $this->mMagicHookDone = true;
3177 wfProfileIn( 'LanguageGetMagic' );
3178 Hooks::run( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3179 wfProfileOut( 'LanguageGetMagic' );
3183 * Fill a MagicWord object with data from here
3185 * @param MagicWord $mw
3187 function getMagic( $mw ) {
3188 // Saves a function call
3189 if ( !$this->mMagicHookDone ) {
3190 $this->doMagicHook();
3193 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3194 $rawEntry = $this->mMagicExtensions[$mw->mId];
3195 } else {
3196 $rawEntry = self::$dataCache->getSubitem(
3197 $this->mCode, 'magicWords', $mw->mId );
3200 if ( !is_array( $rawEntry ) ) {
3201 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3202 } else {
3203 $mw->mCaseSensitive = $rawEntry[0];
3204 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3209 * Add magic words to the extension array
3211 * @param array $newWords
3213 function addMagicWordsByLang( $newWords ) {
3214 $fallbackChain = $this->getFallbackLanguages();
3215 $fallbackChain = array_reverse( $fallbackChain );
3216 foreach ( $fallbackChain as $code ) {
3217 if ( isset( $newWords[$code] ) ) {
3218 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3224 * Get special page names, as an associative array
3225 * canonical name => array of valid names, including aliases
3226 * @return array
3228 function getSpecialPageAliases() {
3229 // Cache aliases because it may be slow to load them
3230 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3231 // Initialise array
3232 $this->mExtendedSpecialPageAliases =
3233 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3234 Hooks::run( 'LanguageGetSpecialPageAliases',
3235 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3238 return $this->mExtendedSpecialPageAliases;
3242 * Italic is unsuitable for some languages
3244 * @param string $text The text to be emphasized.
3245 * @return string
3247 function emphasize( $text ) {
3248 return "<em>$text</em>";
3252 * Normally we output all numbers in plain en_US style, that is
3253 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3254 * point twohundredthirtyfive. However this is not suitable for all
3255 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3256 * Icelandic just want to use commas instead of dots, and dots instead
3257 * of commas like "293.291,235".
3259 * An example of this function being called:
3260 * <code>
3261 * wfMessage( 'message' )->numParams( $num )->text()
3262 * </code>
3264 * See $separatorTransformTable on MessageIs.php for
3265 * the , => . and . => , implementation.
3267 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3268 * @param int|float $number The string to be formatted, should be an integer
3269 * or a floating point number.
3270 * @param bool $nocommafy Set to true for special numbers like dates
3271 * @return string
3273 public function formatNum( $number, $nocommafy = false ) {
3274 global $wgTranslateNumerals;
3275 if ( !$nocommafy ) {
3276 $number = $this->commafy( $number );
3277 $s = $this->separatorTransformTable();
3278 if ( $s ) {
3279 $number = strtr( $number, $s );
3283 if ( $wgTranslateNumerals ) {
3284 $s = $this->digitTransformTable();
3285 if ( $s ) {
3286 $number = strtr( $number, $s );
3290 return $number;
3294 * Front-end for non-commafied formatNum
3296 * @param int|float $number The string to be formatted, should be an integer
3297 * or a floating point number.
3298 * @since 1.21
3299 * @return string
3301 public function formatNumNoSeparators( $number ) {
3302 return $this->formatNum( $number, true );
3306 * @param string $number
3307 * @return string
3309 public function parseFormattedNumber( $number ) {
3310 $s = $this->digitTransformTable();
3311 if ( $s ) {
3312 // eliminate empty array values such as ''. (bug 64347)
3313 $s = array_filter( $s );
3314 $number = strtr( $number, array_flip( $s ) );
3317 $s = $this->separatorTransformTable();
3318 if ( $s ) {
3319 // eliminate empty array values such as ''. (bug 64347)
3320 $s = array_filter( $s );
3321 $number = strtr( $number, array_flip( $s ) );
3324 $number = strtr( $number, array( ',' => '' ) );
3325 return $number;
3329 * Adds commas to a given number
3330 * @since 1.19
3331 * @param mixed $number
3332 * @return string
3334 function commafy( $number ) {
3335 $digitGroupingPattern = $this->digitGroupingPattern();
3336 if ( $number === null ) {
3337 return '';
3340 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3341 // default grouping is at thousands, use the same for ###,###,### pattern too.
3342 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3343 } else {
3344 // Ref: http://cldr.unicode.org/translation/number-patterns
3345 $sign = "";
3346 if ( intval( $number ) < 0 ) {
3347 // For negative numbers apply the algorithm like positive number and add sign.
3348 $sign = "-";
3349 $number = substr( $number, 1 );
3351 $integerPart = array();
3352 $decimalPart = array();
3353 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3354 preg_match( "/\d+/", $number, $integerPart );
3355 preg_match( "/\.\d*/", $number, $decimalPart );
3356 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3357 if ( $groupedNumber === $number ) {
3358 // the string does not have any number part. Eg: .12345
3359 return $sign . $groupedNumber;
3361 $start = $end = ($integerPart) ? strlen( $integerPart[0] ) : 0;
3362 while ( $start > 0 ) {
3363 $match = $matches[0][$numMatches - 1];
3364 $matchLen = strlen( $match );
3365 $start = $end - $matchLen;
3366 if ( $start < 0 ) {
3367 $start = 0;
3369 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3370 $end = $start;
3371 if ( $numMatches > 1 ) {
3372 // use the last pattern for the rest of the number
3373 $numMatches--;
3375 if ( $start > 0 ) {
3376 $groupedNumber = "," . $groupedNumber;
3379 return $sign . $groupedNumber;
3384 * @return string
3386 function digitGroupingPattern() {
3387 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3391 * @return array
3393 function digitTransformTable() {
3394 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3398 * @return array
3400 function separatorTransformTable() {
3401 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3405 * Take a list of strings and build a locale-friendly comma-separated
3406 * list, using the local comma-separator message.
3407 * The last two strings are chained with an "and".
3408 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3410 * @param string[] $l
3411 * @return string
3413 function listToText( array $l ) {
3414 $m = count( $l ) - 1;
3415 if ( $m < 0 ) {
3416 return '';
3418 if ( $m > 0 ) {
3419 $and = $this->msg( 'and' )->escaped();
3420 $space = $this->msg( 'word-separator' )->escaped();
3421 if ( $m > 1 ) {
3422 $comma = $this->msg( 'comma-separator' )->escaped();
3425 $s = $l[$m];
3426 for ( $i = $m - 1; $i >= 0; $i-- ) {
3427 if ( $i == $m - 1 ) {
3428 $s = $l[$i] . $and . $space . $s;
3429 } else {
3430 $s = $l[$i] . $comma . $s;
3433 return $s;
3437 * Take a list of strings and build a locale-friendly comma-separated
3438 * list, using the local comma-separator message.
3439 * @param string[] $list Array of strings to put in a comma list
3440 * @return string
3442 function commaList( array $list ) {
3443 return implode(
3444 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3445 $list
3450 * Take a list of strings and build a locale-friendly semicolon-separated
3451 * list, using the local semicolon-separator message.
3452 * @param string[] $list Array of strings to put in a semicolon list
3453 * @return string
3455 function semicolonList( array $list ) {
3456 return implode(
3457 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3458 $list
3463 * Same as commaList, but separate it with the pipe instead.
3464 * @param string[] $list Array of strings to put in a pipe list
3465 * @return string
3467 function pipeList( array $list ) {
3468 return implode(
3469 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3470 $list
3475 * Truncate a string to a specified length in bytes, appending an optional
3476 * string (e.g. for ellipses)
3478 * The database offers limited byte lengths for some columns in the database;
3479 * multi-byte character sets mean we need to ensure that only whole characters
3480 * are included, otherwise broken characters can be passed to the user
3482 * If $length is negative, the string will be truncated from the beginning
3484 * @param string $string String to truncate
3485 * @param int $length Maximum length (including ellipses)
3486 * @param string $ellipsis String to append to the truncated text
3487 * @param bool $adjustLength Subtract length of ellipsis from $length.
3488 * $adjustLength was introduced in 1.18, before that behaved as if false.
3489 * @return string
3491 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3492 # Use the localized ellipsis character
3493 if ( $ellipsis == '...' ) {
3494 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3496 # Check if there is no need to truncate
3497 if ( $length == 0 ) {
3498 return $ellipsis; // convention
3499 } elseif ( strlen( $string ) <= abs( $length ) ) {
3500 return $string; // no need to truncate
3502 $stringOriginal = $string;
3503 # If ellipsis length is >= $length then we can't apply $adjustLength
3504 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3505 $string = $ellipsis; // this can be slightly unexpected
3506 # Otherwise, truncate and add ellipsis...
3507 } else {
3508 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3509 if ( $length > 0 ) {
3510 $length -= $eLength;
3511 $string = substr( $string, 0, $length ); // xyz...
3512 $string = $this->removeBadCharLast( $string );
3513 $string = rtrim( $string );
3514 $string = $string . $ellipsis;
3515 } else {
3516 $length += $eLength;
3517 $string = substr( $string, $length ); // ...xyz
3518 $string = $this->removeBadCharFirst( $string );
3519 $string = ltrim( $string );
3520 $string = $ellipsis . $string;
3523 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3524 # This check is *not* redundant if $adjustLength, due to the single case where
3525 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3526 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3527 return $string;
3528 } else {
3529 return $stringOriginal;
3534 * Remove bytes that represent an incomplete Unicode character
3535 * at the end of string (e.g. bytes of the char are missing)
3537 * @param string $string
3538 * @return string
3540 protected function removeBadCharLast( $string ) {
3541 if ( $string != '' ) {
3542 $char = ord( $string[strlen( $string ) - 1] );
3543 $m = array();
3544 if ( $char >= 0xc0 ) {
3545 # We got the first byte only of a multibyte char; remove it.
3546 $string = substr( $string, 0, -1 );
3547 } elseif ( $char >= 0x80 &&
3548 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3549 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3551 # We chopped in the middle of a character; remove it
3552 $string = $m[1];
3555 return $string;
3559 * Remove bytes that represent an incomplete Unicode character
3560 * at the start of string (e.g. bytes of the char are missing)
3562 * @param string $string
3563 * @return string
3565 protected function removeBadCharFirst( $string ) {
3566 if ( $string != '' ) {
3567 $char = ord( $string[0] );
3568 if ( $char >= 0x80 && $char < 0xc0 ) {
3569 # We chopped in the middle of a character; remove the whole thing
3570 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3573 return $string;
3577 * Truncate a string of valid HTML to a specified length in bytes,
3578 * appending an optional string (e.g. for ellipses), and return valid HTML
3580 * This is only intended for styled/linked text, such as HTML with
3581 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3582 * Also, this will not detect things like "display:none" CSS.
3584 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3586 * @param string $text HTML string to truncate
3587 * @param int $length (zero/positive) Maximum length (including ellipses)
3588 * @param string $ellipsis String to append to the truncated text
3589 * @return string
3591 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3592 # Use the localized ellipsis character
3593 if ( $ellipsis == '...' ) {
3594 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3596 # Check if there is clearly no need to truncate
3597 if ( $length <= 0 ) {
3598 return $ellipsis; // no text shown, nothing to format (convention)
3599 } elseif ( strlen( $text ) <= $length ) {
3600 return $text; // string short enough even *with* HTML (short-circuit)
3603 $dispLen = 0; // innerHTML legth so far
3604 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3605 $tagType = 0; // 0-open, 1-close
3606 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3607 $entityState = 0; // 0-not entity, 1-entity
3608 $tag = $ret = ''; // accumulated tag name, accumulated result string
3609 $openTags = array(); // open tag stack
3610 $maybeState = null; // possible truncation state
3612 $textLen = strlen( $text );
3613 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3614 for ( $pos = 0; true; ++$pos ) {
3615 # Consider truncation once the display length has reached the maximim.
3616 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3617 # Check that we're not in the middle of a bracket/entity...
3618 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3619 if ( !$testingEllipsis ) {
3620 $testingEllipsis = true;
3621 # Save where we are; we will truncate here unless there turn out to
3622 # be so few remaining characters that truncation is not necessary.
3623 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3624 $maybeState = array( $ret, $openTags ); // save state
3626 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3627 # String in fact does need truncation, the truncation point was OK.
3628 list( $ret, $openTags ) = $maybeState; // reload state
3629 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3630 $ret .= $ellipsis; // add ellipsis
3631 break;
3634 if ( $pos >= $textLen ) {
3635 break; // extra iteration just for above checks
3638 # Read the next char...
3639 $ch = $text[$pos];
3640 $lastCh = $pos ? $text[$pos - 1] : '';
3641 $ret .= $ch; // add to result string
3642 if ( $ch == '<' ) {
3643 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3644 $entityState = 0; // for bad HTML
3645 $bracketState = 1; // tag started (checking for backslash)
3646 } elseif ( $ch == '>' ) {
3647 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3648 $entityState = 0; // for bad HTML
3649 $bracketState = 0; // out of brackets
3650 } elseif ( $bracketState == 1 ) {
3651 if ( $ch == '/' ) {
3652 $tagType = 1; // close tag (e.g. "</span>")
3653 } else {
3654 $tagType = 0; // open tag (e.g. "<span>")
3655 $tag .= $ch;
3657 $bracketState = 2; // building tag name
3658 } elseif ( $bracketState == 2 ) {
3659 if ( $ch != ' ' ) {
3660 $tag .= $ch;
3661 } else {
3662 // Name found (e.g. "<a href=..."), add on tag attributes...
3663 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3665 } elseif ( $bracketState == 0 ) {
3666 if ( $entityState ) {
3667 if ( $ch == ';' ) {
3668 $entityState = 0;
3669 $dispLen++; // entity is one displayed char
3671 } else {
3672 if ( $neLength == 0 && !$maybeState ) {
3673 // Save state without $ch. We want to *hit* the first
3674 // display char (to get tags) but not *use* it if truncating.
3675 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3677 if ( $ch == '&' ) {
3678 $entityState = 1; // entity found, (e.g. "&#160;")
3679 } else {
3680 $dispLen++; // this char is displayed
3681 // Add the next $max display text chars after this in one swoop...
3682 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3683 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3684 $dispLen += $skipped;
3685 $pos += $skipped;
3690 // Close the last tag if left unclosed by bad HTML
3691 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3692 while ( count( $openTags ) > 0 ) {
3693 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3695 return $ret;
3699 * truncateHtml() helper function
3700 * like strcspn() but adds the skipped chars to $ret
3702 * @param string $ret
3703 * @param string $text
3704 * @param string $search
3705 * @param int $start
3706 * @param null|int $len
3707 * @return int
3709 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3710 if ( $len === null ) {
3711 $len = -1; // -1 means "no limit" for strcspn
3712 } elseif ( $len < 0 ) {
3713 $len = 0; // sanity
3715 $skipCount = 0;
3716 if ( $start < strlen( $text ) ) {
3717 $skipCount = strcspn( $text, $search, $start, $len );
3718 $ret .= substr( $text, $start, $skipCount );
3720 return $skipCount;
3724 * truncateHtml() helper function
3725 * (a) push or pop $tag from $openTags as needed
3726 * (b) clear $tag value
3727 * @param string &$tag Current HTML tag name we are looking at
3728 * @param int $tagType (0-open tag, 1-close tag)
3729 * @param string $lastCh Character before the '>' that ended this tag
3730 * @param array &$openTags Open tag stack (not accounting for $tag)
3732 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3733 $tag = ltrim( $tag );
3734 if ( $tag != '' ) {
3735 if ( $tagType == 0 && $lastCh != '/' ) {
3736 $openTags[] = $tag; // tag opened (didn't close itself)
3737 } elseif ( $tagType == 1 ) {
3738 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3739 array_pop( $openTags ); // tag closed
3742 $tag = '';
3747 * Grammatical transformations, needed for inflected languages
3748 * Invoked by putting {{grammar:case|word}} in a message
3750 * @param string $word
3751 * @param string $case
3752 * @return string
3754 function convertGrammar( $word, $case ) {
3755 global $wgGrammarForms;
3756 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3757 return $wgGrammarForms[$this->getCode()][$case][$word];
3760 return $word;
3763 * Get the grammar forms for the content language
3764 * @return array Array of grammar forms
3765 * @since 1.20
3767 function getGrammarForms() {
3768 global $wgGrammarForms;
3769 if ( isset( $wgGrammarForms[$this->getCode()] )
3770 && is_array( $wgGrammarForms[$this->getCode()] )
3772 return $wgGrammarForms[$this->getCode()];
3775 return array();
3778 * Provides an alternative text depending on specified gender.
3779 * Usage {{gender:username|masculine|feminine|unknown}}.
3780 * username is optional, in which case the gender of current user is used,
3781 * but only in (some) interface messages; otherwise default gender is used.
3783 * If no forms are given, an empty string is returned. If only one form is
3784 * given, it will be returned unconditionally. These details are implied by
3785 * the caller and cannot be overridden in subclasses.
3787 * If three forms are given, the default is to use the third (unknown) form.
3788 * If fewer than three forms are given, the default is to use the first (masculine) form.
3789 * These details can be overridden in subclasses.
3791 * @param string $gender
3792 * @param array $forms
3794 * @return string
3796 function gender( $gender, $forms ) {
3797 if ( !count( $forms ) ) {
3798 return '';
3800 $forms = $this->preConvertPlural( $forms, 2 );
3801 if ( $gender === 'male' ) {
3802 return $forms[0];
3804 if ( $gender === 'female' ) {
3805 return $forms[1];
3807 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3811 * Plural form transformations, needed for some languages.
3812 * For example, there are 3 form of plural in Russian and Polish,
3813 * depending on "count mod 10". See [[w:Plural]]
3814 * For English it is pretty simple.
3816 * Invoked by putting {{plural:count|wordform1|wordform2}}
3817 * or {{plural:count|wordform1|wordform2|wordform3}}
3819 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3821 * @param int $count Non-localized number
3822 * @param array $forms Different plural forms
3823 * @return string Correct form of plural for $count in this language
3825 function convertPlural( $count, $forms ) {
3826 // Handle explicit n=pluralform cases
3827 $forms = $this->handleExplicitPluralForms( $count, $forms );
3828 if ( is_string( $forms ) ) {
3829 return $forms;
3831 if ( !count( $forms ) ) {
3832 return '';
3835 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3836 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3837 return $forms[$pluralForm];
3841 * Handles explicit plural forms for Language::convertPlural()
3843 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3844 * If an explicitly defined plural form matches the $count, then
3845 * string value returned, otherwise array returned for further consideration
3846 * by CLDR rules or overridden convertPlural().
3848 * @since 1.23
3850 * @param int $count Non-localized number
3851 * @param array $forms Different plural forms
3853 * @return array|string
3855 protected function handleExplicitPluralForms( $count, array $forms ) {
3856 foreach ( $forms as $index => $form ) {
3857 if ( preg_match( '/\d+=/i', $form ) ) {
3858 $pos = strpos( $form, '=' );
3859 if ( substr( $form, 0, $pos ) === (string)$count ) {
3860 return substr( $form, $pos + 1 );
3862 unset( $forms[$index] );
3865 return array_values( $forms );
3869 * Checks that convertPlural was given an array and pads it to requested
3870 * amount of forms by copying the last one.
3872 * @param array $forms Array of forms given to convertPlural
3873 * @param int $count How many forms should there be at least
3874 * @return array Padded array of forms or an exception if not an array
3876 protected function preConvertPlural( /* Array */ $forms, $count ) {
3877 while ( count( $forms ) < $count ) {
3878 $forms[] = $forms[count( $forms ) - 1];
3880 return $forms;
3884 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3885 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3886 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3887 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3888 * match up with it.
3890 * @param string $str The validated block duration in English
3891 * @return string Somehow translated block duration
3892 * @see LanguageFi.php for example implementation
3894 function translateBlockExpiry( $str ) {
3895 $duration = SpecialBlock::getSuggestedDurations( $this );
3896 foreach ( $duration as $show => $value ) {
3897 if ( strcmp( $str, $value ) == 0 ) {
3898 return htmlspecialchars( trim( $show ) );
3902 // Since usually only infinite or indefinite is only on list, so try
3903 // equivalents if still here.
3904 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3905 if ( in_array( $str, $indefs ) ) {
3906 foreach ( $indefs as $val ) {
3907 $show = array_search( $val, $duration, true );
3908 if ( $show !== false ) {
3909 return htmlspecialchars( trim( $show ) );
3914 // If all else fails, return a standard duration or timestamp description.
3915 $time = strtotime( $str, 0 );
3916 if ( $time === false ) { // Unknown format. Return it as-is in case.
3917 return $str;
3918 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3919 // $time is relative to 0 so it's a duration length.
3920 return $this->formatDuration( $time );
3921 } else { // It's an absolute timestamp.
3922 if ( $time === 0 ) {
3923 // wfTimestamp() handles 0 as current time instead of epoch.
3924 return $this->timeanddate( '19700101000000' );
3925 } else {
3926 return $this->timeanddate( $time );
3932 * languages like Chinese need to be segmented in order for the diff
3933 * to be of any use
3935 * @param string $text
3936 * @return string
3938 public function segmentForDiff( $text ) {
3939 return $text;
3943 * and unsegment to show the result
3945 * @param string $text
3946 * @return string
3948 public function unsegmentForDiff( $text ) {
3949 return $text;
3953 * Return the LanguageConverter used in the Language
3955 * @since 1.19
3956 * @return LanguageConverter
3958 public function getConverter() {
3959 return $this->mConverter;
3963 * convert text to all supported variants
3965 * @param string $text
3966 * @return array
3968 public function autoConvertToAllVariants( $text ) {
3969 return $this->mConverter->autoConvertToAllVariants( $text );
3973 * convert text to different variants of a language.
3975 * @param string $text
3976 * @return string
3978 public function convert( $text ) {
3979 return $this->mConverter->convert( $text );
3983 * Convert a Title object to a string in the preferred variant
3985 * @param Title $title
3986 * @return string
3988 public function convertTitle( $title ) {
3989 return $this->mConverter->convertTitle( $title );
3993 * Convert a namespace index to a string in the preferred variant
3995 * @param int $ns
3996 * @return string
3998 public function convertNamespace( $ns ) {
3999 return $this->mConverter->convertNamespace( $ns );
4003 * Check if this is a language with variants
4005 * @return bool
4007 public function hasVariants() {
4008 return count( $this->getVariants() ) > 1;
4012 * Check if the language has the specific variant
4014 * @since 1.19
4015 * @param string $variant
4016 * @return bool
4018 public function hasVariant( $variant ) {
4019 return (bool)$this->mConverter->validateVariant( $variant );
4023 * Put custom tags (e.g. -{ }-) around math to prevent conversion
4025 * @param string $text
4026 * @return string
4027 * @deprecated since 1.22 is no longer used
4029 public function armourMath( $text ) {
4030 return $this->mConverter->armourMath( $text );
4034 * Perform output conversion on a string, and encode for safe HTML output.
4035 * @param string $text Text to be converted
4036 * @param bool $isTitle Whether this conversion is for the article title
4037 * @return string
4038 * @todo this should get integrated somewhere sane
4040 public function convertHtml( $text, $isTitle = false ) {
4041 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4045 * @param string $key
4046 * @return string
4048 public function convertCategoryKey( $key ) {
4049 return $this->mConverter->convertCategoryKey( $key );
4053 * Get the list of variants supported by this language
4054 * see sample implementation in LanguageZh.php
4056 * @return array An array of language codes
4058 public function getVariants() {
4059 return $this->mConverter->getVariants();
4063 * @return string
4065 public function getPreferredVariant() {
4066 return $this->mConverter->getPreferredVariant();
4070 * @return string
4072 public function getDefaultVariant() {
4073 return $this->mConverter->getDefaultVariant();
4077 * @return string
4079 public function getURLVariant() {
4080 return $this->mConverter->getURLVariant();
4084 * If a language supports multiple variants, it is
4085 * possible that non-existing link in one variant
4086 * actually exists in another variant. this function
4087 * tries to find it. See e.g. LanguageZh.php
4088 * The input parameters may be modified upon return
4090 * @param string &$link The name of the link
4091 * @param Title &$nt The title object of the link
4092 * @param bool $ignoreOtherCond To disable other conditions when
4093 * we need to transclude a template or update a category's link
4095 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4096 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4100 * returns language specific options used by User::getPageRenderHash()
4101 * for example, the preferred language variant
4103 * @return string
4105 function getExtraHashOptions() {
4106 return $this->mConverter->getExtraHashOptions();
4110 * For languages that support multiple variants, the title of an
4111 * article may be displayed differently in different variants. this
4112 * function returns the apporiate title defined in the body of the article.
4114 * @return string
4116 public function getParsedTitle() {
4117 return $this->mConverter->getParsedTitle();
4121 * Prepare external link text for conversion. When the text is
4122 * a URL, it shouldn't be converted, and it'll be wrapped in
4123 * the "raw" tag (-{R| }-) to prevent conversion.
4125 * This function is called "markNoConversion" for historical
4126 * reasons.
4128 * @param string $text Text to be used for external link
4129 * @param bool $noParse Wrap it without confirming it's a real URL first
4130 * @return string The tagged text
4132 public function markNoConversion( $text, $noParse = false ) {
4133 // Excluding protocal-relative URLs may avoid many false positives.
4134 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4135 return $this->mConverter->markNoConversion( $text );
4136 } else {
4137 return $text;
4142 * A regular expression to match legal word-trailing characters
4143 * which should be merged onto a link of the form [[foo]]bar.
4145 * @return string
4147 public function linkTrail() {
4148 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
4152 * A regular expression character set to match legal word-prefixing
4153 * characters which should be merged onto a link of the form foo[[bar]].
4155 * @return string
4157 public function linkPrefixCharset() {
4158 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
4162 * @deprecated since 1.24, will be removed in 1.25
4163 * @return Language
4165 function getLangObj() {
4166 wfDeprecated( __METHOD__, '1.24' );
4167 return $this;
4171 * Get the "parent" language which has a converter to convert a "compatible" language
4172 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4174 * @return Language|null
4175 * @since 1.22
4177 public function getParentLanguage() {
4178 if ( $this->mParentLanguage !== false ) {
4179 return $this->mParentLanguage;
4182 $pieces = explode( '-', $this->getCode() );
4183 $code = $pieces[0];
4184 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4185 $this->mParentLanguage = null;
4186 return null;
4188 $lang = Language::factory( $code );
4189 if ( !$lang->hasVariant( $this->getCode() ) ) {
4190 $this->mParentLanguage = null;
4191 return null;
4194 $this->mParentLanguage = $lang;
4195 return $lang;
4199 * Get the RFC 3066 code for this language object
4201 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4202 * htmlspecialchars() or similar
4204 * @return string
4206 public function getCode() {
4207 return $this->mCode;
4211 * Get the code in Bcp47 format which we can use
4212 * inside of html lang="" tags.
4214 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4215 * htmlspecialchars() or similar.
4217 * @since 1.19
4218 * @return string
4220 public function getHtmlCode() {
4221 if ( is_null( $this->mHtmlCode ) ) {
4222 $this->mHtmlCode = wfBCP47( $this->getCode() );
4224 return $this->mHtmlCode;
4228 * @param string $code
4230 public function setCode( $code ) {
4231 $this->mCode = $code;
4232 // Ensure we don't leave incorrect cached data lying around
4233 $this->mHtmlCode = null;
4234 $this->mParentLanguage = false;
4238 * Get the name of a file for a certain language code
4239 * @param string $prefix Prepend this to the filename
4240 * @param string $code Language code
4241 * @param string $suffix Append this to the filename
4242 * @throws MWException
4243 * @return string $prefix . $mangledCode . $suffix
4245 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4246 if ( !self::isValidBuiltInCode( $code ) ) {
4247 throw new MWException( "Invalid language code \"$code\"" );
4250 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4254 * Get the language code from a file name. Inverse of getFileName()
4255 * @param string $filename $prefix . $languageCode . $suffix
4256 * @param string $prefix Prefix before the language code
4257 * @param string $suffix Suffix after the language code
4258 * @return string Language code, or false if $prefix or $suffix isn't found
4260 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4261 $m = null;
4262 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4263 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4264 if ( !count( $m ) ) {
4265 return false;
4267 return str_replace( '_', '-', strtolower( $m[1] ) );
4271 * @param string $code
4272 * @return string
4274 public static function getMessagesFileName( $code ) {
4275 global $IP;
4276 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4277 Hooks::run( 'Language::getMessagesFileName', array( $code, &$file ) );
4278 return $file;
4282 * @param string $code
4283 * @return string
4284 * @since 1.23
4286 public static function getJsonMessagesFileName( $code ) {
4287 global $IP;
4289 if ( !self::isValidBuiltInCode( $code ) ) {
4290 throw new MWException( "Invalid language code \"$code\"" );
4293 return "$IP/languages/i18n/$code.json";
4297 * @param string $code
4298 * @return string
4300 public static function getClassFileName( $code ) {
4301 global $IP;
4302 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4306 * Get the first fallback for a given language.
4308 * @param string $code
4310 * @return bool|string
4312 public static function getFallbackFor( $code ) {
4313 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4314 return false;
4315 } else {
4316 $fallbacks = self::getFallbacksFor( $code );
4317 $first = array_shift( $fallbacks );
4318 return $first;
4323 * Get the ordered list of fallback languages.
4325 * @since 1.19
4326 * @param string $code Language code
4327 * @return array
4329 public static function getFallbacksFor( $code ) {
4330 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4331 return array();
4332 } else {
4333 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4334 $v = array_map( 'trim', explode( ',', $v ) );
4335 if ( $v[count( $v ) - 1] !== 'en' ) {
4336 $v[] = 'en';
4338 return $v;
4343 * Get the ordered list of fallback languages, ending with the fallback
4344 * language chain for the site language.
4346 * @since 1.22
4347 * @param string $code Language code
4348 * @return array Array( fallbacks, site fallbacks )
4350 public static function getFallbacksIncludingSiteLanguage( $code ) {
4351 global $wgLanguageCode;
4353 // Usually, we will only store a tiny number of fallback chains, so we
4354 // keep them in static memory.
4355 $cacheKey = "{$code}-{$wgLanguageCode}";
4357 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4358 $fallbacks = self::getFallbacksFor( $code );
4360 // Append the site's fallback chain, including the site language itself
4361 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4362 array_unshift( $siteFallbacks, $wgLanguageCode );
4364 // Eliminate any languages already included in the chain
4365 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4367 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4369 return self::$fallbackLanguageCache[$cacheKey];
4373 * Get all messages for a given language
4374 * WARNING: this may take a long time. If you just need all message *keys*
4375 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4377 * @param string $code
4379 * @return array
4381 public static function getMessagesFor( $code ) {
4382 return self::getLocalisationCache()->getItem( $code, 'messages' );
4386 * Get a message for a given language
4388 * @param string $key
4389 * @param string $code
4391 * @return string
4393 public static function getMessageFor( $key, $code ) {
4394 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4398 * Get all message keys for a given language. This is a faster alternative to
4399 * array_keys( Language::getMessagesFor( $code ) )
4401 * @since 1.19
4402 * @param string $code Language code
4403 * @return array Array of message keys (strings)
4405 public static function getMessageKeysFor( $code ) {
4406 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4410 * @param string $talk
4411 * @return mixed
4413 function fixVariableInNamespace( $talk ) {
4414 if ( strpos( $talk, '$1' ) === false ) {
4415 return $talk;
4418 global $wgMetaNamespace;
4419 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4421 # Allow grammar transformations
4422 # Allowing full message-style parsing would make simple requests
4423 # such as action=raw much more expensive than they need to be.
4424 # This will hopefully cover most cases.
4425 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4426 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4427 return str_replace( ' ', '_', $talk );
4431 * @param string $m
4432 * @return string
4434 function replaceGrammarInNamespace( $m ) {
4435 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4439 * @throws MWException
4440 * @return array
4442 static function getCaseMaps() {
4443 static $wikiUpperChars, $wikiLowerChars;
4444 if ( isset( $wikiUpperChars ) ) {
4445 return array( $wikiUpperChars, $wikiLowerChars );
4448 wfProfileIn( __METHOD__ );
4449 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4450 if ( $arr === false ) {
4451 throw new MWException(
4452 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4454 $wikiUpperChars = $arr['wikiUpperChars'];
4455 $wikiLowerChars = $arr['wikiLowerChars'];
4456 wfProfileOut( __METHOD__ );
4457 return array( $wikiUpperChars, $wikiLowerChars );
4461 * Decode an expiry (block, protection, etc) which has come from the DB
4463 * @todo FIXME: why are we returnings DBMS-dependent strings???
4465 * @param string $expiry Database expiry String
4466 * @param bool|int $format True to process using language functions, or TS_ constant
4467 * to return the expiry in a given timestamp
4468 * @return string
4469 * @since 1.18
4471 public function formatExpiry( $expiry, $format = true ) {
4472 static $infinity;
4473 if ( $infinity === null ) {
4474 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4477 if ( $expiry == '' || $expiry == $infinity ) {
4478 return $format === true
4479 ? $this->getMessageFromDB( 'infiniteblock' )
4480 : $infinity;
4481 } else {
4482 return $format === true
4483 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4484 : wfTimestamp( $format, $expiry );
4489 * @todo Document
4490 * @param int|float $seconds
4491 * @param array $format Optional
4492 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4493 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4494 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4495 * and friends.
4496 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4497 * or 'avoidminutes'.
4498 * @return string
4500 function formatTimePeriod( $seconds, $format = array() ) {
4501 if ( !is_array( $format ) ) {
4502 $format = array( 'avoid' => $format ); // For backwards compatibility
4504 if ( !isset( $format['avoid'] ) ) {
4505 $format['avoid'] = false;
4507 if ( !isset( $format['noabbrevs'] ) ) {
4508 $format['noabbrevs'] = false;
4510 $secondsMsg = wfMessage(
4511 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4512 $minutesMsg = wfMessage(
4513 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4514 $hoursMsg = wfMessage(
4515 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4516 $daysMsg = wfMessage(
4517 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4519 if ( round( $seconds * 10 ) < 100 ) {
4520 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4521 $s = $secondsMsg->params( $s )->text();
4522 } elseif ( round( $seconds ) < 60 ) {
4523 $s = $this->formatNum( round( $seconds ) );
4524 $s = $secondsMsg->params( $s )->text();
4525 } elseif ( round( $seconds ) < 3600 ) {
4526 $minutes = floor( $seconds / 60 );
4527 $secondsPart = round( fmod( $seconds, 60 ) );
4528 if ( $secondsPart == 60 ) {
4529 $secondsPart = 0;
4530 $minutes++;
4532 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4533 $s .= ' ';
4534 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4535 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4536 $hours = floor( $seconds / 3600 );
4537 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4538 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4539 if ( $secondsPart == 60 ) {
4540 $secondsPart = 0;
4541 $minutes++;
4543 if ( $minutes == 60 ) {
4544 $minutes = 0;
4545 $hours++;
4547 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4548 $s .= ' ';
4549 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4550 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4551 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4553 } else {
4554 $days = floor( $seconds / 86400 );
4555 if ( $format['avoid'] === 'avoidminutes' ) {
4556 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4557 if ( $hours == 24 ) {
4558 $hours = 0;
4559 $days++;
4561 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4562 $s .= ' ';
4563 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4564 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4565 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4566 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4567 if ( $minutes == 60 ) {
4568 $minutes = 0;
4569 $hours++;
4571 if ( $hours == 24 ) {
4572 $hours = 0;
4573 $days++;
4575 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4576 $s .= ' ';
4577 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4578 $s .= ' ';
4579 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4580 } else {
4581 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4582 $s .= ' ';
4583 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4586 return $s;
4590 * Format a bitrate for output, using an appropriate
4591 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4592 * the magnitude in question.
4594 * This use base 1000. For base 1024 use formatSize(), for another base
4595 * see formatComputingNumbers().
4597 * @param int $bps
4598 * @return string
4600 function formatBitrate( $bps ) {
4601 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4605 * @param int $size Size of the unit
4606 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4607 * @param string $messageKey Message key to be uesd
4608 * @return string
4610 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4611 if ( $size <= 0 ) {
4612 return str_replace( '$1', $this->formatNum( $size ),
4613 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4616 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4617 $index = 0;
4619 $maxIndex = count( $sizes ) - 1;
4620 while ( $size >= $boundary && $index < $maxIndex ) {
4621 $index++;
4622 $size /= $boundary;
4625 // For small sizes no decimal places necessary
4626 $round = 0;
4627 if ( $index > 1 ) {
4628 // For MB and bigger two decimal places are smarter
4629 $round = 2;
4631 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4633 $size = round( $size, $round );
4634 $text = $this->getMessageFromDB( $msg );
4635 return str_replace( '$1', $this->formatNum( $size ), $text );
4639 * Format a size in bytes for output, using an appropriate
4640 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4642 * This method use base 1024. For base 1000 use formatBitrate(), for
4643 * another base see formatComputingNumbers()
4645 * @param int $size Size to format
4646 * @return string Plain text (not HTML)
4648 function formatSize( $size ) {
4649 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4653 * Make a list item, used by various special pages
4655 * @param string $page Page link
4656 * @param string $details HTML safe text between brackets
4657 * @param bool $oppositedm Add the direction mark opposite to your
4658 * language, to display text properly
4659 * @return HTML escaped string
4661 function specialList( $page, $details, $oppositedm = true ) {
4662 if ( !$details ) {
4663 return $page;
4666 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4667 return
4668 $page .
4669 $dirmark .
4670 $this->msg( 'word-separator' )->escaped() .
4671 $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4675 * Generate (prev x| next x) (20|50|100...) type links for paging
4677 * @param Title $title Title object to link
4678 * @param int $offset
4679 * @param int $limit
4680 * @param array $query Optional URL query parameter string
4681 * @param bool $atend Optional param for specified if this is the last page
4682 * @return string
4684 public function viewPrevNext( Title $title, $offset, $limit,
4685 array $query = array(), $atend = false
4687 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4689 # Make 'previous' link
4690 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4691 if ( $offset > 0 ) {
4692 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4693 $query, $prev, 'prevn-title', 'mw-prevlink' );
4694 } else {
4695 $plink = htmlspecialchars( $prev );
4698 # Make 'next' link
4699 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4700 if ( $atend ) {
4701 $nlink = htmlspecialchars( $next );
4702 } else {
4703 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4704 $query, $next, 'nextn-title', 'mw-nextlink' );
4707 # Make links to set number of items per page
4708 $numLinks = array();
4709 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4710 $numLinks[] = $this->numLink( $title, $offset, $num,
4711 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4714 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4715 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4719 * Helper function for viewPrevNext() that generates links
4721 * @param Title $title Title object to link
4722 * @param int $offset
4723 * @param int $limit
4724 * @param array $query Extra query parameters
4725 * @param string $link Text to use for the link; will be escaped
4726 * @param string $tooltipMsg Name of the message to use as tooltip
4727 * @param string $class Value of the "class" attribute of the link
4728 * @return string HTML fragment
4730 private function numLink( Title $title, $offset, $limit, array $query, $link,
4731 $tooltipMsg, $class
4733 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4734 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4735 ->numParams( $limit )->text();
4737 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4738 'title' => $tooltip, 'class' => $class ), $link );
4742 * Get the conversion rule title, if any.
4744 * @return string
4746 public function getConvRuleTitle() {
4747 return $this->mConverter->getConvRuleTitle();
4751 * Get the compiled plural rules for the language
4752 * @since 1.20
4753 * @return array Associative array with plural form, and plural rule as key-value pairs
4755 public function getCompiledPluralRules() {
4756 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4757 $fallbacks = Language::getFallbacksFor( $this->mCode );
4758 if ( !$pluralRules ) {
4759 foreach ( $fallbacks as $fallbackCode ) {
4760 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4761 if ( $pluralRules ) {
4762 break;
4766 return $pluralRules;
4770 * Get the plural rules for the language
4771 * @since 1.20
4772 * @return array Associative array with plural form number and plural rule as key-value pairs
4774 public function getPluralRules() {
4775 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4776 $fallbacks = Language::getFallbacksFor( $this->mCode );
4777 if ( !$pluralRules ) {
4778 foreach ( $fallbacks as $fallbackCode ) {
4779 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4780 if ( $pluralRules ) {
4781 break;
4785 return $pluralRules;
4789 * Get the plural rule types for the language
4790 * @since 1.22
4791 * @return array Associative array with plural form number and plural rule type as key-value pairs
4793 public function getPluralRuleTypes() {
4794 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4795 $fallbacks = Language::getFallbacksFor( $this->mCode );
4796 if ( !$pluralRuleTypes ) {
4797 foreach ( $fallbacks as $fallbackCode ) {
4798 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4799 if ( $pluralRuleTypes ) {
4800 break;
4804 return $pluralRuleTypes;
4808 * Find the index number of the plural rule appropriate for the given number
4809 * @param int $number
4810 * @return int The index number of the plural rule
4812 public function getPluralRuleIndexNumber( $number ) {
4813 $pluralRules = $this->getCompiledPluralRules();
4814 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4815 return $form;
4819 * Find the plural rule type appropriate for the given number
4820 * For example, if the language is set to Arabic, getPluralType(5) should
4821 * return 'few'.
4822 * @since 1.22
4823 * @param int $number
4824 * @return string The name of the plural rule type, e.g. one, two, few, many
4826 public function getPluralRuleType( $number ) {
4827 $index = $this->getPluralRuleIndexNumber( $number );
4828 $pluralRuleTypes = $this->getPluralRuleTypes();
4829 if ( isset( $pluralRuleTypes[$index] ) ) {
4830 return $pluralRuleTypes[$index];
4831 } else {
4832 return 'other';