Merge "Fix typo: expectedExceptionMesage -> expectedExceptionMessage"
[mediawiki.git] / languages / Language.php
blob88d0f23eba9ae69ae5f6fd7acfbddccf835755de
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 * Get a cached or new language object for a given language code
148 * @param string $code
149 * @return Language
151 static function factory( $code ) {
152 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
154 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
155 $code = $wgDummyLanguageCodes[$code];
158 // get the language object to process
159 $langObj = isset( self::$mLangObjCache[$code] )
160 ? self::$mLangObjCache[$code]
161 : self::newFromCode( $code );
163 // merge the language object in to get it up front in the cache
164 self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache );
165 // get rid of the oldest ones in case we have an overflow
166 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
168 return $langObj;
172 * Create a language object for a given language code
173 * @param string $code
174 * @throws MWException
175 * @return Language
177 protected static function newFromCode( $code ) {
178 // Protect against path traversal below
179 if ( !Language::isValidCode( $code )
180 || strcspn( $code, ":/\\\000" ) !== strlen( $code )
182 throw new MWException( "Invalid language code \"$code\"" );
185 if ( !Language::isValidBuiltInCode( $code ) ) {
186 // It's not possible to customise this code with class files, so
187 // just return a Language object. This is to support uselang= hacks.
188 $lang = new Language;
189 $lang->setCode( $code );
190 return $lang;
193 // Check if there is a language class for the code
194 $class = self::classFromCode( $code );
195 self::preloadLanguageClass( $class );
196 if ( class_exists( $class ) ) {
197 $lang = new $class;
198 return $lang;
201 // Keep trying the fallback list until we find an existing class
202 $fallbacks = Language::getFallbacksFor( $code );
203 foreach ( $fallbacks as $fallbackCode ) {
204 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
205 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
208 $class = self::classFromCode( $fallbackCode );
209 self::preloadLanguageClass( $class );
210 if ( class_exists( $class ) ) {
211 $lang = Language::newFromCode( $fallbackCode );
212 $lang->setCode( $code );
213 return $lang;
217 throw new MWException( "Invalid fallback sequence for language '$code'" );
221 * Checks whether any localisation is available for that language tag
222 * in MediaWiki (MessagesXx.php exists).
224 * @param string $code Language tag (in lower case)
225 * @return bool Whether language is supported
226 * @since 1.21
228 public static function isSupportedLanguage( $code ) {
229 return self::isValidBuiltInCode( $code )
230 && ( is_readable( self::getMessagesFileName( $code ) )
231 || is_readable( self::getJsonMessagesFileName( $code ) )
236 * Returns true if a language code string is a well-formed language tag
237 * according to RFC 5646.
238 * This function only checks well-formedness; it doesn't check that
239 * language, script or variant codes actually exist in the repositories.
241 * Based on regexes by Mark Davis of the Unicode Consortium:
242 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
244 * @param string $code
245 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
247 * @return bool
248 * @since 1.21
250 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
251 $alpha = '[a-z]';
252 $digit = '[0-9]';
253 $alphanum = '[a-z0-9]';
254 $x = 'x'; # private use singleton
255 $singleton = '[a-wy-z]'; # other singleton
256 $s = $lenient ? '[-_]' : '-';
258 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
259 $script = "$alpha{4}"; # ISO 15924
260 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
261 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
262 $extension = "$singleton(?:$s$alphanum{2,8})+";
263 $privateUse = "$x(?:$s$alphanum{1,8})+";
265 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
266 # Since these are limited, this is safe even later changes to the registry --
267 # the only oddity is that it might change the type of the tag, and thus
268 # the results from the capturing groups.
269 # http://www.iana.org/assignments/language-subtag-registry
271 $grandfathered = "en{$s}GB{$s}oed"
272 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
273 . "|no{$s}(?:bok|nyn)"
274 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
275 . "|zh{$s}min{$s}nan";
277 $variantList = "$variant(?:$s$variant)*";
278 $extensionList = "$extension(?:$s$extension)*";
280 $langtag = "(?:($language)"
281 . "(?:$s$script)?"
282 . "(?:$s$region)?"
283 . "(?:$s$variantList)?"
284 . "(?:$s$extensionList)?"
285 . "(?:$s$privateUse)?)";
287 # The final breakdown, with capturing groups for each of these components
288 # The variants, extensions, grandfathered, and private-use may have interior '-'
290 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
292 return (bool)preg_match( "/$root/", strtolower( $code ) );
296 * Returns true if a language code string is of a valid form, whether or
297 * not it exists. This includes codes which are used solely for
298 * customisation via the MediaWiki namespace.
300 * @param string $code
302 * @return bool
304 public static function isValidCode( $code ) {
305 static $cache = array();
306 if ( isset( $cache[$code] ) ) {
307 return $cache[$code];
309 // People think language codes are html safe, so enforce it.
310 // Ideally we should only allow a-zA-Z0-9-
311 // but, .+ and other chars are often used for {{int:}} hacks
312 // see bugs 37564, 37587, 36938
313 $cache[$code] =
314 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
315 && !preg_match( Title::getTitleInvalidRegex(), $code );
317 return $cache[$code];
321 * Returns true if a language code is of a valid form for the purposes of
322 * internal customisation of MediaWiki, via Messages*.php or *.json.
324 * @param string $code
326 * @throws MWException
327 * @since 1.18
328 * @return bool
330 public static function isValidBuiltInCode( $code ) {
332 if ( !is_string( $code ) ) {
333 if ( is_object( $code ) ) {
334 $addmsg = " of class " . get_class( $code );
335 } else {
336 $addmsg = '';
338 $type = gettype( $code );
339 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
342 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
346 * Returns true if a language code is an IETF tag known to MediaWiki.
348 * @param string $code
350 * @since 1.21
351 * @return bool
353 public static function isKnownLanguageTag( $tag ) {
354 static $coreLanguageNames;
356 // Quick escape for invalid input to avoid exceptions down the line
357 // when code tries to process tags which are not valid at all.
358 if ( !self::isValidBuiltInCode( $tag ) ) {
359 return false;
362 if ( $coreLanguageNames === null ) {
363 global $IP;
364 include "$IP/languages/Names.php";
367 if ( isset( $coreLanguageNames[$tag] )
368 || self::fetchLanguageName( $tag, $tag ) !== ''
370 return true;
373 return false;
377 * @param string $code
378 * @return string Name of the language class
380 public static function classFromCode( $code ) {
381 if ( $code == 'en' ) {
382 return 'Language';
383 } else {
384 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
389 * Includes language class files
391 * @param string $class Name of the language class
393 public static function preloadLanguageClass( $class ) {
394 global $IP;
396 if ( $class === 'Language' ) {
397 return;
400 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
401 include_once "$IP/languages/classes/$class.php";
406 * Get the LocalisationCache instance
408 * @return LocalisationCache
410 public static function getLocalisationCache() {
411 if ( is_null( self::$dataCache ) ) {
412 global $wgLocalisationCacheConf;
413 $class = $wgLocalisationCacheConf['class'];
414 self::$dataCache = new $class( $wgLocalisationCacheConf );
416 return self::$dataCache;
419 function __construct() {
420 $this->mConverter = new FakeConverter( $this );
421 // Set the code to the name of the descendant
422 if ( get_class( $this ) == 'Language' ) {
423 $this->mCode = 'en';
424 } else {
425 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
427 self::getLocalisationCache();
431 * Reduce memory usage
433 function __destruct() {
434 foreach ( $this as $name => $value ) {
435 unset( $this->$name );
440 * Hook which will be called if this is the content language.
441 * Descendants can use this to register hook functions or modify globals
443 function initContLang() {
447 * @return array
448 * @since 1.19
450 function getFallbackLanguages() {
451 return self::getFallbacksFor( $this->mCode );
455 * Exports $wgBookstoreListEn
456 * @return array
458 function getBookstoreList() {
459 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
463 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
464 * available in localised form, it will be included in English.
466 * @return array
468 public function getNamespaces() {
469 if ( is_null( $this->namespaceNames ) ) {
470 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
472 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
473 $validNamespaces = MWNamespace::getCanonicalNamespaces();
475 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
477 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
478 if ( $wgMetaNamespaceTalk ) {
479 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
480 } else {
481 $talk = $this->namespaceNames[NS_PROJECT_TALK];
482 $this->namespaceNames[NS_PROJECT_TALK] =
483 $this->fixVariableInNamespace( $talk );
486 # Sometimes a language will be localised but not actually exist on this wiki.
487 foreach ( $this->namespaceNames as $key => $text ) {
488 if ( !isset( $validNamespaces[$key] ) ) {
489 unset( $this->namespaceNames[$key] );
493 # The above mixing may leave namespaces out of canonical order.
494 # Re-order by namespace ID number...
495 ksort( $this->namespaceNames );
497 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
500 return $this->namespaceNames;
504 * Arbitrarily set all of the namespace names at once. Mainly used for testing
505 * @param array $namespaces Array of namespaces (id => name)
507 public function setNamespaces( array $namespaces ) {
508 $this->namespaceNames = $namespaces;
509 $this->mNamespaceIds = null;
513 * Resets all of the namespace caches. Mainly used for testing
515 public function resetNamespaces() {
516 $this->namespaceNames = null;
517 $this->mNamespaceIds = null;
518 $this->namespaceAliases = null;
522 * A convenience function that returns the same thing as
523 * getNamespaces() except with the array values changed to ' '
524 * where it found '_', useful for producing output to be displayed
525 * e.g. in <select> forms.
527 * @return array
529 function getFormattedNamespaces() {
530 $ns = $this->getNamespaces();
531 foreach ( $ns as $k => $v ) {
532 $ns[$k] = strtr( $v, '_', ' ' );
534 return $ns;
538 * Get a namespace value by key
539 * <code>
540 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
541 * echo $mw_ns; // prints 'MediaWiki'
542 * </code>
544 * @param int $index The array key of the namespace to return
545 * @return string|bool String if the namespace value exists, otherwise false
547 function getNsText( $index ) {
548 $ns = $this->getNamespaces();
550 return isset( $ns[$index] ) ? $ns[$index] : false;
554 * A convenience function that returns the same thing as
555 * getNsText() except with '_' changed to ' ', useful for
556 * producing output.
558 * <code>
559 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
560 * echo $mw_ns; // prints 'MediaWiki talk'
561 * </code>
563 * @param int $index The array key of the namespace to return
564 * @return string Namespace name without underscores (empty string if namespace does not exist)
566 function getFormattedNsText( $index ) {
567 $ns = $this->getNsText( $index );
569 return strtr( $ns, '_', ' ' );
573 * Returns gender-dependent namespace alias if available.
574 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
575 * @param int $index Namespace index
576 * @param string $gender Gender key (male, female... )
577 * @return string
578 * @since 1.18
580 function getGenderNsText( $index, $gender ) {
581 global $wgExtraGenderNamespaces;
583 $ns = $wgExtraGenderNamespaces +
584 self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
586 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
590 * Whether this language uses gender-dependent namespace aliases.
591 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
592 * @return bool
593 * @since 1.18
595 function needsGenderDistinction() {
596 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
597 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
598 // $wgExtraGenderNamespaces overrides everything
599 return true;
600 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
601 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
602 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
603 return false;
604 } else {
605 // Check what is in i18n files
606 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
607 return count( $aliases ) > 0;
612 * Get a namespace key by value, case insensitive.
613 * Only matches namespace names for the current language, not the
614 * canonical ones defined in Namespace.php.
616 * @param string $text
617 * @return int|bool An integer if $text is a valid value otherwise false
619 function getLocalNsIndex( $text ) {
620 $lctext = $this->lc( $text );
621 $ids = $this->getNamespaceIds();
622 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
626 * @return array
628 function getNamespaceAliases() {
629 if ( is_null( $this->namespaceAliases ) ) {
630 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
631 if ( !$aliases ) {
632 $aliases = array();
633 } else {
634 foreach ( $aliases as $name => $index ) {
635 if ( $index === NS_PROJECT_TALK ) {
636 unset( $aliases[$name] );
637 $name = $this->fixVariableInNamespace( $name );
638 $aliases[$name] = $index;
643 global $wgExtraGenderNamespaces;
644 $genders = $wgExtraGenderNamespaces +
645 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
646 foreach ( $genders as $index => $forms ) {
647 foreach ( $forms as $alias ) {
648 $aliases[$alias] = $index;
652 # Also add converted namespace names as aliases, to avoid confusion.
653 $convertedNames = array();
654 foreach ( $this->getVariants() as $variant ) {
655 if ( $variant === $this->mCode ) {
656 continue;
658 foreach ( $this->getNamespaces() as $ns => $_ ) {
659 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
663 $this->namespaceAliases = $aliases + $convertedNames;
666 return $this->namespaceAliases;
670 * @return array
672 function getNamespaceIds() {
673 if ( is_null( $this->mNamespaceIds ) ) {
674 global $wgNamespaceAliases;
675 # Put namespace names and aliases into a hashtable.
676 # If this is too slow, then we should arrange it so that it is done
677 # before caching. The catch is that at pre-cache time, the above
678 # class-specific fixup hasn't been done.
679 $this->mNamespaceIds = array();
680 foreach ( $this->getNamespaces() as $index => $name ) {
681 $this->mNamespaceIds[$this->lc( $name )] = $index;
683 foreach ( $this->getNamespaceAliases() as $name => $index ) {
684 $this->mNamespaceIds[$this->lc( $name )] = $index;
686 if ( $wgNamespaceAliases ) {
687 foreach ( $wgNamespaceAliases as $name => $index ) {
688 $this->mNamespaceIds[$this->lc( $name )] = $index;
692 return $this->mNamespaceIds;
696 * Get a namespace key by value, case insensitive. Canonical namespace
697 * names override custom ones defined for the current language.
699 * @param string $text
700 * @return int|bool An integer if $text is a valid value otherwise false
702 function getNsIndex( $text ) {
703 $lctext = $this->lc( $text );
704 $ns = MWNamespace::getCanonicalIndex( $lctext );
705 if ( $ns !== null ) {
706 return $ns;
708 $ids = $this->getNamespaceIds();
709 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
713 * short names for language variants used for language conversion links.
715 * @param string $code
716 * @param bool $usemsg Use the "variantname-xyz" message if it exists
717 * @return string
719 function getVariantname( $code, $usemsg = true ) {
720 $msg = "variantname-$code";
721 if ( $usemsg && wfMessage( $msg )->exists() ) {
722 return $this->getMessageFromDB( $msg );
724 $name = self::fetchLanguageName( $code );
725 if ( $name ) {
726 return $name; # if it's defined as a language name, show that
727 } else {
728 # otherwise, output the language code
729 return $code;
734 * @param string $name
735 * @return string
737 function specialPage( $name ) {
738 $aliases = $this->getSpecialPageAliases();
739 if ( isset( $aliases[$name][0] ) ) {
740 $name = $aliases[$name][0];
742 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
746 * @return array
748 function getDatePreferences() {
749 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
753 * @return array
755 function getDateFormats() {
756 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
760 * @return array|string
762 function getDefaultDateFormat() {
763 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
764 if ( $df === 'dmy or mdy' ) {
765 global $wgAmericanDates;
766 return $wgAmericanDates ? 'mdy' : 'dmy';
767 } else {
768 return $df;
773 * @return array
775 function getDatePreferenceMigrationMap() {
776 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
780 * @param string $image
781 * @return array|null
783 function getImageFile( $image ) {
784 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
788 * @return array
790 function getExtraUserToggles() {
791 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
795 * @param string $tog
796 * @return string
798 function getUserToggle( $tog ) {
799 return $this->getMessageFromDB( "tog-$tog" );
803 * Get native language names, indexed by code.
804 * Only those defined in MediaWiki, no other data like CLDR.
805 * If $customisedOnly is true, only returns codes with a messages file
807 * @param bool $customisedOnly
809 * @return array
810 * @deprecated since 1.20, use fetchLanguageNames()
812 public static function getLanguageNames( $customisedOnly = false ) {
813 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
817 * Get translated language names. This is done on best effort and
818 * by default this is exactly the same as Language::getLanguageNames.
819 * The CLDR extension provides translated names.
820 * @param string $code Language code.
821 * @return array Language code => language name
822 * @since 1.18.0
823 * @deprecated since 1.20, use fetchLanguageNames()
825 public static function getTranslatedLanguageNames( $code ) {
826 return self::fetchLanguageNames( $code, 'all' );
830 * Get an array of language names, indexed by code.
831 * @param null|string $inLanguage Code of language in which to return the names
832 * Use null for autonyms (native names)
833 * @param string $include One of:
834 * 'all' all available languages
835 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
836 * 'mwfile' only if the language is in 'mw' *and* has a message file
837 * @return array Language code => language name
838 * @since 1.20
840 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
841 global $wgExtraLanguageNames;
842 static $coreLanguageNames;
844 if ( $coreLanguageNames === null ) {
845 global $IP;
846 include "$IP/languages/Names.php";
849 // If passed an invalid language code to use, fallback to en
850 if ( $inLanguage !== null && !Language::isValidCode( $inLanguage ) ) {
851 $inLanguage = 'en';
854 $names = array();
856 if ( $inLanguage ) {
857 # TODO: also include when $inLanguage is null, when this code is more efficient
858 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
861 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
862 foreach ( $mwNames as $mwCode => $mwName ) {
863 # - Prefer own MediaWiki native name when not using the hook
864 # - For other names just add if not added through the hook
865 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
866 $names[$mwCode] = $mwName;
870 if ( $include === 'all' ) {
871 return $names;
874 $returnMw = array();
875 $coreCodes = array_keys( $mwNames );
876 foreach ( $coreCodes as $coreCode ) {
877 $returnMw[$coreCode] = $names[$coreCode];
880 if ( $include === 'mwfile' ) {
881 $namesMwFile = array();
882 # We do this using a foreach over the codes instead of a directory
883 # loop so that messages files in extensions will work correctly.
884 foreach ( $returnMw as $code => $value ) {
885 if ( is_readable( self::getMessagesFileName( $code ) )
886 || is_readable( self::getJsonMessagesFileName( $code ) )
888 $namesMwFile[$code] = $names[$code];
892 return $namesMwFile;
895 # 'mw' option; default if it's not one of the other two options (all/mwfile)
896 return $returnMw;
900 * @param string $code The code of the language for which to get the name
901 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
902 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
903 * @return string Language name or empty
904 * @since 1.20
906 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
907 $code = strtolower( $code );
908 $array = self::fetchLanguageNames( $inLanguage, $include );
909 return !array_key_exists( $code, $array ) ? '' : $array[$code];
913 * Get a message from the MediaWiki namespace.
915 * @param string $msg Message name
916 * @return string
918 function getMessageFromDB( $msg ) {
919 return wfMessage( $msg )->inLanguage( $this )->text();
923 * Get the native language name of $code.
924 * Only if defined in MediaWiki, no other data like CLDR.
925 * @param string $code
926 * @return string
927 * @deprecated since 1.20, use fetchLanguageName()
929 function getLanguageName( $code ) {
930 return self::fetchLanguageName( $code );
934 * @param string $key
935 * @return string
937 function getMonthName( $key ) {
938 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
942 * @return array
944 function getMonthNamesArray() {
945 $monthNames = array( '' );
946 for ( $i = 1; $i < 13; $i++ ) {
947 $monthNames[] = $this->getMonthName( $i );
949 return $monthNames;
953 * @param string $key
954 * @return string
956 function getMonthNameGen( $key ) {
957 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
961 * @param string $key
962 * @return string
964 function getMonthAbbreviation( $key ) {
965 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
969 * @return array
971 function getMonthAbbreviationsArray() {
972 $monthNames = array( '' );
973 for ( $i = 1; $i < 13; $i++ ) {
974 $monthNames[] = $this->getMonthAbbreviation( $i );
976 return $monthNames;
980 * @param string $key
981 * @return string
983 function getWeekdayName( $key ) {
984 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
988 * @param string $key
989 * @return string
991 function getWeekdayAbbreviation( $key ) {
992 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
996 * @param string $key
997 * @return string
999 function getIranianCalendarMonthName( $key ) {
1000 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1004 * @param string $key
1005 * @return string
1007 function getHebrewCalendarMonthName( $key ) {
1008 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1012 * @param string $key
1013 * @return string
1015 function getHebrewCalendarMonthNameGen( $key ) {
1016 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1020 * @param string $key
1021 * @return string
1023 function getHijriCalendarMonthName( $key ) {
1024 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1028 * Pass through result from $dateTimeObj->format()
1030 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1031 if ( !$dateTimeObj ) {
1032 $dateTimeObj = DateTime::createFromFormat(
1033 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1036 return $dateTimeObj->format( $code );
1040 * This is a workalike of PHP's date() function, but with better
1041 * internationalisation, a reduced set of format characters, and a better
1042 * escaping format.
1044 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1045 * the PHP manual for definitions. There are a number of extensions, which
1046 * start with "x":
1048 * xn Do not translate digits of the next numeric format character
1049 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1050 * xr Use roman numerals for the next numeric format character
1051 * xh Use hebrew numerals for the next numeric format character
1052 * xx Literal x
1053 * xg Genitive month name
1055 * xij j (day number) in Iranian calendar
1056 * xiF F (month name) in Iranian calendar
1057 * xin n (month number) in Iranian calendar
1058 * xiy y (two digit year) in Iranian calendar
1059 * xiY Y (full year) in Iranian calendar
1061 * xjj j (day number) in Hebrew calendar
1062 * xjF F (month name) in Hebrew calendar
1063 * xjt t (days in month) in Hebrew calendar
1064 * xjx xg (genitive month name) in Hebrew calendar
1065 * xjn n (month number) in Hebrew calendar
1066 * xjY Y (full year) in Hebrew calendar
1068 * xmj j (day number) in Hijri calendar
1069 * xmF F (month name) in Hijri calendar
1070 * xmn n (month number) in Hijri calendar
1071 * xmY Y (full year) in Hijri calendar
1073 * xkY Y (full year) in Thai solar calendar. Months and days are
1074 * identical to the Gregorian calendar
1075 * xoY Y (full year) in Minguo calendar or Juche year.
1076 * Months and days are identical to the
1077 * Gregorian calendar
1078 * xtY Y (full year) in Japanese nengo. Months and days are
1079 * identical to the Gregorian calendar
1081 * Characters enclosed in double quotes will be considered literal (with
1082 * the quotes themselves removed). Unmatched quotes will be considered
1083 * literal quotes. Example:
1085 * "The month is" F => The month is January
1086 * i's" => 20'11"
1088 * Backslash escaping is also supported.
1090 * Input timestamp is assumed to be pre-normalized to the desired local
1091 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1092 * $ts is UTC if $zone is not given.
1094 * @param string $format
1095 * @param string $ts 14-character timestamp
1096 * YYYYMMDDHHMMSS
1097 * 01234567890123
1098 * @param DateTimeZone $zone Timezone of $ts
1099 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1100 * Only makes sense if $ts is the current time.
1101 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1103 * @throws MWException
1104 * @return string
1106 function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = null ) {
1107 $s = '';
1108 $raw = false;
1109 $roman = false;
1110 $hebrewNum = false;
1111 $dateTimeObj = false;
1112 $rawToggle = false;
1113 $iranian = false;
1114 $hebrew = false;
1115 $hijri = false;
1116 $thai = false;
1117 $minguo = false;
1118 $tenno = false;
1120 $usedSecond = false;
1121 $usedMinute = false;
1122 $usedHour = false;
1123 $usedAMPM = false;
1124 $usedDay = false;
1125 $usedWeek = false;
1126 $usedMonth = false;
1127 $usedYear = false;
1128 $usedISOYear = false;
1129 $usedIsLeapYear = false;
1131 $usedHebrewMonth = false;
1132 $usedIranianMonth = false;
1133 $usedHijriMonth = false;
1134 $usedHebrewYear = false;
1135 $usedIranianYear = false;
1136 $usedHijriYear = false;
1137 $usedTennoYear = false;
1139 if ( strlen( $ts ) !== 14 ) {
1140 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1143 if ( !ctype_digit( $ts ) ) {
1144 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1147 $formatLength = strlen( $format );
1148 for ( $p = 0; $p < $formatLength; $p++ ) {
1149 $num = false;
1150 $code = $format[$p];
1151 if ( $code == 'x' && $p < $formatLength - 1 ) {
1152 $code .= $format[++$p];
1155 if ( ( $code === 'xi'
1156 || $code === 'xj'
1157 || $code === 'xk'
1158 || $code === 'xm'
1159 || $code === 'xo'
1160 || $code === 'xt' )
1161 && $p < $formatLength - 1 ) {
1162 $code .= $format[++$p];
1165 switch ( $code ) {
1166 case 'xx':
1167 $s .= 'x';
1168 break;
1169 case 'xn':
1170 $raw = true;
1171 break;
1172 case 'xN':
1173 $rawToggle = !$rawToggle;
1174 break;
1175 case 'xr':
1176 $roman = true;
1177 break;
1178 case 'xh':
1179 $hebrewNum = true;
1180 break;
1181 case 'xg':
1182 $usedMonth = true;
1183 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1184 break;
1185 case 'xjx':
1186 $usedHebrewMonth = true;
1187 if ( !$hebrew ) {
1188 $hebrew = self::tsToHebrew( $ts );
1190 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1191 break;
1192 case 'd':
1193 $usedDay = true;
1194 $num = substr( $ts, 6, 2 );
1195 break;
1196 case 'D':
1197 $usedDay = true;
1198 $s .= $this->getWeekdayAbbreviation( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1199 break;
1200 case 'j':
1201 $usedDay = true;
1202 $num = intval( substr( $ts, 6, 2 ) );
1203 break;
1204 case 'xij':
1205 $usedDay = true;
1206 if ( !$iranian ) {
1207 $iranian = self::tsToIranian( $ts );
1209 $num = $iranian[2];
1210 break;
1211 case 'xmj':
1212 $usedDay = true;
1213 if ( !$hijri ) {
1214 $hijri = self::tsToHijri( $ts );
1216 $num = $hijri[2];
1217 break;
1218 case 'xjj':
1219 $usedDay = true;
1220 if ( !$hebrew ) {
1221 $hebrew = self::tsToHebrew( $ts );
1223 $num = $hebrew[2];
1224 break;
1225 case 'l':
1226 $usedDay = true;
1227 $s .= $this->getWeekdayName( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1228 break;
1229 case 'F':
1230 $usedMonth = true;
1231 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1232 break;
1233 case 'xiF':
1234 $usedIranianMonth = true;
1235 if ( !$iranian ) {
1236 $iranian = self::tsToIranian( $ts );
1238 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1239 break;
1240 case 'xmF':
1241 $usedHijriMonth = true;
1242 if ( !$hijri ) {
1243 $hijri = self::tsToHijri( $ts );
1245 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1246 break;
1247 case 'xjF':
1248 $usedHebrewMonth = true;
1249 if ( !$hebrew ) {
1250 $hebrew = self::tsToHebrew( $ts );
1252 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1253 break;
1254 case 'm':
1255 $usedMonth = true;
1256 $num = substr( $ts, 4, 2 );
1257 break;
1258 case 'M':
1259 $usedMonth = true;
1260 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1261 break;
1262 case 'n':
1263 $usedMonth = true;
1264 $num = intval( substr( $ts, 4, 2 ) );
1265 break;
1266 case 'xin':
1267 $usedIranianMonth = true;
1268 if ( !$iranian ) {
1269 $iranian = self::tsToIranian( $ts );
1271 $num = $iranian[1];
1272 break;
1273 case 'xmn':
1274 $usedHijriMonth = true;
1275 if ( !$hijri ) {
1276 $hijri = self::tsToHijri ( $ts );
1278 $num = $hijri[1];
1279 break;
1280 case 'xjn':
1281 $usedHebrewMonth = true;
1282 if ( !$hebrew ) {
1283 $hebrew = self::tsToHebrew( $ts );
1285 $num = $hebrew[1];
1286 break;
1287 case 'xjt':
1288 $usedHebrewMonth = true;
1289 if ( !$hebrew ) {
1290 $hebrew = self::tsToHebrew( $ts );
1292 $num = $hebrew[3];
1293 break;
1294 case 'Y':
1295 $usedYear = true;
1296 $num = substr( $ts, 0, 4 );
1297 break;
1298 case 'xiY':
1299 $usedIranianYear = true;
1300 if ( !$iranian ) {
1301 $iranian = self::tsToIranian( $ts );
1303 $num = $iranian[0];
1304 break;
1305 case 'xmY':
1306 $usedHijriYear = true;
1307 if ( !$hijri ) {
1308 $hijri = self::tsToHijri( $ts );
1310 $num = $hijri[0];
1311 break;
1312 case 'xjY':
1313 $usedHebrewYear = true;
1314 if ( !$hebrew ) {
1315 $hebrew = self::tsToHebrew( $ts );
1317 $num = $hebrew[0];
1318 break;
1319 case 'xkY':
1320 $usedYear = true;
1321 if ( !$thai ) {
1322 $thai = self::tsToYear( $ts, 'thai' );
1324 $num = $thai[0];
1325 break;
1326 case 'xoY':
1327 $usedYear = true;
1328 if ( !$minguo ) {
1329 $minguo = self::tsToYear( $ts, 'minguo' );
1331 $num = $minguo[0];
1332 break;
1333 case 'xtY':
1334 $usedTennoYear = true;
1335 if ( !$tenno ) {
1336 $tenno = self::tsToYear( $ts, 'tenno' );
1338 $num = $tenno[0];
1339 break;
1340 case 'y':
1341 $usedYear = true;
1342 $num = substr( $ts, 2, 2 );
1343 break;
1344 case 'xiy':
1345 $usedIranianYear = true;
1346 if ( !$iranian ) {
1347 $iranian = self::tsToIranian( $ts );
1349 $num = substr( $iranian[0], -2 );
1350 break;
1351 case 'a':
1352 $usedAMPM = true;
1353 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1354 break;
1355 case 'A':
1356 $usedAMPM = true;
1357 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1358 break;
1359 case 'g':
1360 $usedHour = true;
1361 $h = substr( $ts, 8, 2 );
1362 $num = $h % 12 ? $h % 12 : 12;
1363 break;
1364 case 'G':
1365 $usedHour = true;
1366 $num = intval( substr( $ts, 8, 2 ) );
1367 break;
1368 case 'h':
1369 $usedHour = true;
1370 $h = substr( $ts, 8, 2 );
1371 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1372 break;
1373 case 'H':
1374 $usedHour = true;
1375 $num = substr( $ts, 8, 2 );
1376 break;
1377 case 'i':
1378 $usedMinute = true;
1379 $num = substr( $ts, 10, 2 );
1380 break;
1381 case 's':
1382 $usedSecond = true;
1383 $num = substr( $ts, 12, 2 );
1384 break;
1385 case 'c':
1386 case 'r':
1387 $usedSecond = true;
1388 // fall through
1389 case 'e':
1390 case 'O':
1391 case 'P':
1392 case 'T':
1393 $s .= Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1394 break;
1395 case 'w':
1396 case 'N':
1397 case 'z':
1398 $usedDay = true;
1399 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1400 break;
1401 case 'W':
1402 $usedWeek = true;
1403 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1404 break;
1405 case 't':
1406 $usedMonth = true;
1407 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1408 break;
1409 case 'L':
1410 $usedIsLeapYear = true;
1411 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1412 break;
1413 case 'o':
1414 $usedISOYear = true;
1415 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1416 break;
1417 case 'U':
1418 $usedSecond = true;
1419 // fall through
1420 case 'I':
1421 case 'Z':
1422 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1423 break;
1424 case '\\':
1425 # Backslash escaping
1426 if ( $p < $formatLength - 1 ) {
1427 $s .= $format[++$p];
1428 } else {
1429 $s .= '\\';
1431 break;
1432 case '"':
1433 # Quoted literal
1434 if ( $p < $formatLength - 1 ) {
1435 $endQuote = strpos( $format, '"', $p + 1 );
1436 if ( $endQuote === false ) {
1437 # No terminating quote, assume literal "
1438 $s .= '"';
1439 } else {
1440 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1441 $p = $endQuote;
1443 } else {
1444 # Quote at end of string, assume literal "
1445 $s .= '"';
1447 break;
1448 default:
1449 $s .= $format[$p];
1451 if ( $num !== false ) {
1452 if ( $rawToggle || $raw ) {
1453 $s .= $num;
1454 $raw = false;
1455 } elseif ( $roman ) {
1456 $s .= Language::romanNumeral( $num );
1457 $roman = false;
1458 } elseif ( $hebrewNum ) {
1459 $s .= self::hebrewNumeral( $num );
1460 $hebrewNum = false;
1461 } else {
1462 $s .= $this->formatNum( $num, true );
1467 if ( $usedSecond ) {
1468 $ttl = 1;
1469 } elseif ( $usedMinute ) {
1470 $ttl = 60 - substr( $ts, 12, 2 );
1471 } elseif ( $usedHour ) {
1472 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1473 } elseif ( $usedAMPM ) {
1474 $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1475 } elseif ( $usedDay || $usedHebrewMonth || $usedIranianMonth || $usedHijriMonth || $usedHebrewYear || $usedIranianYear || $usedHijriYear || $usedTennoYear ) {
1476 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1477 // so that they don't need purged every day.
1478 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1479 } else {
1480 $possibleTtls = array();
1481 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1482 if ( $usedWeek ) {
1483 $possibleTtls[] = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1484 } elseif ( $usedISOYear ) {
1485 // December 28th falls on the last ISO week of the year, every year.
1486 // The last ISO week of a year can be 52 or 53.
1487 $lastWeekOfISOYear = DateTime::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?: new DateTimeZone( 'UTC' ) )->format( 'W' );
1488 $currentISOWeek = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1489 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1490 $timeRemainingInWeek = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1491 $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1494 if ( $usedMonth ) {
1495 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 + $timeRemainingInDay;
1496 } elseif ( $usedYear ) {
1497 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1498 + $timeRemainingInDay;
1499 } elseif ( $usedIsLeapYear ) {
1500 $year = substr( $ts, 0, 4 );
1501 $timeRemainingInYear = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1502 + $timeRemainingInDay;
1503 $mod = $year % 4;
1504 if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1505 // this isn't a leap year. see when the next one starts
1506 $nextCandidate = $year - $mod + 4;
1507 if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1508 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 + $timeRemainingInYear;
1509 } else {
1510 $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 + $timeRemainingInYear;
1512 } else {
1513 // this is a leap year, so the next year isn't
1514 $possibleTtls[] = $timeRemainingInYear;
1518 if ( $possibleTtls ) {
1519 $ttl = min( $possibleTtls );
1523 return $s;
1526 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1527 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1530 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1531 * Gregorian dates to Iranian dates. Originally written in C, it
1532 * is released under the terms of GNU Lesser General Public
1533 * License. Conversion to PHP was performed by Niklas Laxström.
1535 * Link: http://www.farsiweb.info/jalali/jalali.c
1537 * @param string $ts
1539 * @return string
1541 private static function tsToIranian( $ts ) {
1542 $gy = substr( $ts, 0, 4 ) -1600;
1543 $gm = substr( $ts, 4, 2 ) -1;
1544 $gd = substr( $ts, 6, 2 ) -1;
1546 # Days passed from the beginning (including leap years)
1547 $gDayNo = 365 * $gy
1548 + floor( ( $gy + 3 ) / 4 )
1549 - floor( ( $gy + 99 ) / 100 )
1550 + floor( ( $gy + 399 ) / 400 );
1552 // Add days of the past months of this year
1553 for ( $i = 0; $i < $gm; $i++ ) {
1554 $gDayNo += self::$GREG_DAYS[$i];
1557 // Leap years
1558 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1559 $gDayNo++;
1562 // Days passed in current month
1563 $gDayNo += (int)$gd;
1565 $jDayNo = $gDayNo - 79;
1567 $jNp = floor( $jDayNo / 12053 );
1568 $jDayNo %= 12053;
1570 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1571 $jDayNo %= 1461;
1573 if ( $jDayNo >= 366 ) {
1574 $jy += floor( ( $jDayNo - 1 ) / 365 );
1575 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1578 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1579 $jDayNo -= self::$IRANIAN_DAYS[$i];
1582 $jm = $i + 1;
1583 $jd = $jDayNo + 1;
1585 return array( $jy, $jm, $jd );
1589 * Converting Gregorian dates to Hijri dates.
1591 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1593 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1595 * @param string $ts
1597 * @return string
1599 private static function tsToHijri( $ts ) {
1600 $year = substr( $ts, 0, 4 );
1601 $month = substr( $ts, 4, 2 );
1602 $day = substr( $ts, 6, 2 );
1604 $zyr = $year;
1605 $zd = $day;
1606 $zm = $month;
1607 $zy = $zyr;
1609 if (
1610 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1611 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1613 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1614 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1615 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1616 $zd - 32075;
1617 } else {
1618 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1619 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1622 $zl = $zjd -1948440 + 10632;
1623 $zn = (int)( ( $zl - 1 ) / 10631 );
1624 $zl = $zl - 10631 * $zn + 354;
1625 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1626 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1627 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1628 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1629 $zm = (int)( ( 24 * $zl ) / 709 );
1630 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1631 $zy = 30 * $zn + $zj - 30;
1633 return array( $zy, $zm, $zd );
1637 * Converting Gregorian dates to Hebrew dates.
1639 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1640 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1641 * to translate the relevant functions into PHP and release them under
1642 * GNU GPL.
1644 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1645 * and Adar II is 14. In a non-leap year, Adar is 6.
1647 * @param string $ts
1649 * @return string
1651 private static function tsToHebrew( $ts ) {
1652 # Parse date
1653 $year = substr( $ts, 0, 4 );
1654 $month = substr( $ts, 4, 2 );
1655 $day = substr( $ts, 6, 2 );
1657 # Calculate Hebrew year
1658 $hebrewYear = $year + 3760;
1660 # Month number when September = 1, August = 12
1661 $month += 4;
1662 if ( $month > 12 ) {
1663 # Next year
1664 $month -= 12;
1665 $year++;
1666 $hebrewYear++;
1669 # Calculate day of year from 1 September
1670 $dayOfYear = $day;
1671 for ( $i = 1; $i < $month; $i++ ) {
1672 if ( $i == 6 ) {
1673 # February
1674 $dayOfYear += 28;
1675 # Check if the year is leap
1676 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1677 $dayOfYear++;
1679 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1680 $dayOfYear += 30;
1681 } else {
1682 $dayOfYear += 31;
1686 # Calculate the start of the Hebrew year
1687 $start = self::hebrewYearStart( $hebrewYear );
1689 # Calculate next year's start
1690 if ( $dayOfYear <= $start ) {
1691 # Day is before the start of the year - it is the previous year
1692 # Next year's start
1693 $nextStart = $start;
1694 # Previous year
1695 $year--;
1696 $hebrewYear--;
1697 # Add days since previous year's 1 September
1698 $dayOfYear += 365;
1699 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1700 # Leap year
1701 $dayOfYear++;
1703 # Start of the new (previous) year
1704 $start = self::hebrewYearStart( $hebrewYear );
1705 } else {
1706 # Next year's start
1707 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1710 # Calculate Hebrew day of year
1711 $hebrewDayOfYear = $dayOfYear - $start;
1713 # Difference between year's days
1714 $diff = $nextStart - $start;
1715 # Add 12 (or 13 for leap years) days to ignore the difference between
1716 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1717 # difference is only about the year type
1718 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1719 $diff += 13;
1720 } else {
1721 $diff += 12;
1724 # Check the year pattern, and is leap year
1725 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1726 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1727 # and non-leap years
1728 $yearPattern = $diff % 30;
1729 # Check if leap year
1730 $isLeap = $diff >= 30;
1732 # Calculate day in the month from number of day in the Hebrew year
1733 # Don't check Adar - if the day is not in Adar, we will stop before;
1734 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1735 $hebrewDay = $hebrewDayOfYear;
1736 $hebrewMonth = 1;
1737 $days = 0;
1738 while ( $hebrewMonth <= 12 ) {
1739 # Calculate days in this month
1740 if ( $isLeap && $hebrewMonth == 6 ) {
1741 # Adar in a leap year
1742 if ( $isLeap ) {
1743 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1744 $days = 30;
1745 if ( $hebrewDay <= $days ) {
1746 # Day in Adar I
1747 $hebrewMonth = 13;
1748 } else {
1749 # Subtract the days of Adar I
1750 $hebrewDay -= $days;
1751 # Try Adar II
1752 $days = 29;
1753 if ( $hebrewDay <= $days ) {
1754 # Day in Adar II
1755 $hebrewMonth = 14;
1759 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1760 # Cheshvan in a complete year (otherwise as the rule below)
1761 $days = 30;
1762 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1763 # Kislev in an incomplete year (otherwise as the rule below)
1764 $days = 29;
1765 } else {
1766 # Odd months have 30 days, even have 29
1767 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1769 if ( $hebrewDay <= $days ) {
1770 # In the current month
1771 break;
1772 } else {
1773 # Subtract the days of the current month
1774 $hebrewDay -= $days;
1775 # Try in the next month
1776 $hebrewMonth++;
1780 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1784 * This calculates the Hebrew year start, as days since 1 September.
1785 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1786 * Used for Hebrew date.
1788 * @param int $year
1790 * @return string
1792 private static function hebrewYearStart( $year ) {
1793 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1794 $b = intval( ( $year - 1 ) % 4 );
1795 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1796 if ( $m < 0 ) {
1797 $m--;
1799 $Mar = intval( $m );
1800 if ( $m < 0 ) {
1801 $m++;
1803 $m -= $Mar;
1805 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1806 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1807 $Mar++;
1808 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1809 $Mar += 2;
1810 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1811 $Mar++;
1814 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1815 return $Mar;
1819 * Algorithm to convert Gregorian dates to Thai solar dates,
1820 * Minguo dates or Minguo dates.
1822 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1823 * http://en.wikipedia.org/wiki/Minguo_calendar
1824 * http://en.wikipedia.org/wiki/Japanese_era_name
1826 * @param string $ts 14-character timestamp
1827 * @param string $cName Calender name
1828 * @return array Converted year, month, day
1830 private static function tsToYear( $ts, $cName ) {
1831 $gy = substr( $ts, 0, 4 );
1832 $gm = substr( $ts, 4, 2 );
1833 $gd = substr( $ts, 6, 2 );
1835 if ( !strcmp( $cName, 'thai' ) ) {
1836 # Thai solar dates
1837 # Add 543 years to the Gregorian calendar
1838 # Months and days are identical
1839 $gy_offset = $gy + 543;
1840 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1841 # Minguo dates
1842 # Deduct 1911 years from the Gregorian calendar
1843 # Months and days are identical
1844 $gy_offset = $gy - 1911;
1845 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1846 # Nengō dates up to Meiji period
1847 # Deduct years from the Gregorian calendar
1848 # depending on the nengo periods
1849 # Months and days are identical
1850 if ( ( $gy < 1912 )
1851 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1852 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1854 # Meiji period
1855 $gy_gannen = $gy - 1868 + 1;
1856 $gy_offset = $gy_gannen;
1857 if ( $gy_gannen == 1 ) {
1858 $gy_offset = '元';
1860 $gy_offset = '明治' . $gy_offset;
1861 } elseif (
1862 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1863 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1864 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1865 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1866 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1868 # Taishō period
1869 $gy_gannen = $gy - 1912 + 1;
1870 $gy_offset = $gy_gannen;
1871 if ( $gy_gannen == 1 ) {
1872 $gy_offset = '元';
1874 $gy_offset = '大正' . $gy_offset;
1875 } elseif (
1876 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1877 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1878 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1880 # Shōwa period
1881 $gy_gannen = $gy - 1926 + 1;
1882 $gy_offset = $gy_gannen;
1883 if ( $gy_gannen == 1 ) {
1884 $gy_offset = '元';
1886 $gy_offset = '昭和' . $gy_offset;
1887 } else {
1888 # Heisei period
1889 $gy_gannen = $gy - 1989 + 1;
1890 $gy_offset = $gy_gannen;
1891 if ( $gy_gannen == 1 ) {
1892 $gy_offset = '元';
1894 $gy_offset = '平成' . $gy_offset;
1896 } else {
1897 $gy_offset = $gy;
1900 return array( $gy_offset, $gm, $gd );
1904 * Roman number formatting up to 10000
1906 * @param int $num
1908 * @return string
1910 static function romanNumeral( $num ) {
1911 static $table = array(
1912 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1913 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1914 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1915 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1916 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1919 $num = intval( $num );
1920 if ( $num > 10000 || $num <= 0 ) {
1921 return $num;
1924 $s = '';
1925 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1926 if ( $num >= $pow10 ) {
1927 $s .= $table[$i][(int)floor( $num / $pow10 )];
1929 $num = $num % $pow10;
1931 return $s;
1935 * Hebrew Gematria number formatting up to 9999
1937 * @param int $num
1939 * @return string
1941 static function hebrewNumeral( $num ) {
1942 static $table = array(
1943 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1944 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1945 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1946 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1949 $num = intval( $num );
1950 if ( $num > 9999 || $num <= 0 ) {
1951 return $num;
1954 $s = '';
1955 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1956 if ( $num >= $pow10 ) {
1957 if ( $num == 15 || $num == 16 ) {
1958 $s .= $table[0][9] . $table[0][$num - 9];
1959 $num = 0;
1960 } else {
1961 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1962 if ( $pow10 == 1000 ) {
1963 $s .= "'";
1967 $num = $num % $pow10;
1969 if ( strlen( $s ) == 2 ) {
1970 $str = $s . "'";
1971 } else {
1972 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1973 $str .= substr( $s, strlen( $s ) - 2, 2 );
1975 $start = substr( $str, 0, strlen( $str ) - 2 );
1976 $end = substr( $str, strlen( $str ) - 2 );
1977 switch ( $end ) {
1978 case 'כ':
1979 $str = $start . 'ך';
1980 break;
1981 case 'מ':
1982 $str = $start . 'ם';
1983 break;
1984 case 'נ':
1985 $str = $start . 'ן';
1986 break;
1987 case 'פ':
1988 $str = $start . 'ף';
1989 break;
1990 case 'צ':
1991 $str = $start . 'ץ';
1992 break;
1994 return $str;
1998 * Used by date() and time() to adjust the time output.
2000 * @param string $ts The time in date('YmdHis') format
2001 * @param mixed $tz Adjust the time by this amount (default false, mean we
2002 * get user timecorrection setting)
2003 * @return int
2005 function userAdjust( $ts, $tz = false ) {
2006 global $wgUser, $wgLocalTZoffset;
2008 if ( $tz === false ) {
2009 $tz = $wgUser->getOption( 'timecorrection' );
2012 $data = explode( '|', $tz, 3 );
2014 if ( $data[0] == 'ZoneInfo' ) {
2015 wfSuppressWarnings();
2016 $userTZ = timezone_open( $data[2] );
2017 wfRestoreWarnings();
2018 if ( $userTZ !== false ) {
2019 $date = date_create( $ts, timezone_open( 'UTC' ) );
2020 date_timezone_set( $date, $userTZ );
2021 $date = date_format( $date, 'YmdHis' );
2022 return $date;
2024 # Unrecognized timezone, default to 'Offset' with the stored offset.
2025 $data[0] = 'Offset';
2028 if ( $data[0] == 'System' || $tz == '' ) {
2029 # Global offset in minutes.
2030 $minDiff = $wgLocalTZoffset;
2031 } elseif ( $data[0] == 'Offset' ) {
2032 $minDiff = intval( $data[1] );
2033 } else {
2034 $data = explode( ':', $tz );
2035 if ( count( $data ) == 2 ) {
2036 $data[0] = intval( $data[0] );
2037 $data[1] = intval( $data[1] );
2038 $minDiff = abs( $data[0] ) * 60 + $data[1];
2039 if ( $data[0] < 0 ) {
2040 $minDiff = -$minDiff;
2042 } else {
2043 $minDiff = intval( $data[0] ) * 60;
2047 # No difference ? Return time unchanged
2048 if ( 0 == $minDiff ) {
2049 return $ts;
2052 wfSuppressWarnings(); // E_STRICT system time bitching
2053 # Generate an adjusted date; take advantage of the fact that mktime
2054 # will normalize out-of-range values so we don't have to split $minDiff
2055 # into hours and minutes.
2056 $t = mktime( (
2057 (int)substr( $ts, 8, 2 ) ), # Hours
2058 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2059 (int)substr( $ts, 12, 2 ), # Seconds
2060 (int)substr( $ts, 4, 2 ), # Month
2061 (int)substr( $ts, 6, 2 ), # Day
2062 (int)substr( $ts, 0, 4 ) ); # Year
2064 $date = date( 'YmdHis', $t );
2065 wfRestoreWarnings();
2067 return $date;
2071 * This is meant to be used by time(), date(), and timeanddate() to get
2072 * the date preference they're supposed to use, it should be used in
2073 * all children.
2075 *<code>
2076 * function timeanddate([...], $format = true) {
2077 * $datePreference = $this->dateFormat($format);
2078 * [...]
2080 *</code>
2082 * @param int|string|bool $usePrefs If true, the user's preference is used
2083 * if false, the site/language default is used
2084 * if int/string, assumed to be a format.
2085 * @return string
2087 function dateFormat( $usePrefs = true ) {
2088 global $wgUser;
2090 if ( is_bool( $usePrefs ) ) {
2091 if ( $usePrefs ) {
2092 $datePreference = $wgUser->getDatePreference();
2093 } else {
2094 $datePreference = (string)User::getDefaultOption( 'date' );
2096 } else {
2097 $datePreference = (string)$usePrefs;
2100 // return int
2101 if ( $datePreference == '' ) {
2102 return 'default';
2105 return $datePreference;
2109 * Get a format string for a given type and preference
2110 * @param string $type May be date, time or both
2111 * @param string $pref The format name as it appears in Messages*.php
2113 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2115 * @return string
2117 function getDateFormatString( $type, $pref ) {
2118 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2119 if ( $pref == 'default' ) {
2120 $pref = $this->getDefaultDateFormat();
2121 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2122 } else {
2123 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2125 if ( $type === 'pretty' && $df === null ) {
2126 $df = $this->getDateFormatString( 'date', $pref );
2129 if ( $df === null ) {
2130 $pref = $this->getDefaultDateFormat();
2131 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2134 $this->dateFormatStrings[$type][$pref] = $df;
2136 return $this->dateFormatStrings[$type][$pref];
2140 * @param string $ts The time format which needs to be turned into a
2141 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2142 * @param bool $adj Whether to adjust the time output according to the
2143 * user configured offset ($timecorrection)
2144 * @param mixed $format True to use user's date format preference
2145 * @param string|bool $timecorrection The time offset as returned by
2146 * validateTimeZone() in Special:Preferences
2147 * @return string
2149 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2150 $ts = wfTimestamp( TS_MW, $ts );
2151 if ( $adj ) {
2152 $ts = $this->userAdjust( $ts, $timecorrection );
2154 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2155 return $this->sprintfDate( $df, $ts );
2159 * @param string $ts The time format which needs to be turned into a
2160 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2161 * @param bool $adj Whether to adjust the time output according to the
2162 * user configured offset ($timecorrection)
2163 * @param mixed $format True to use user's date format preference
2164 * @param string|bool $timecorrection The time offset as returned by
2165 * validateTimeZone() in Special:Preferences
2166 * @return string
2168 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2169 $ts = wfTimestamp( TS_MW, $ts );
2170 if ( $adj ) {
2171 $ts = $this->userAdjust( $ts, $timecorrection );
2173 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2174 return $this->sprintfDate( $df, $ts );
2178 * @param string $ts The time format which needs to be turned into a
2179 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2180 * @param bool $adj Whether to adjust the time output according to the
2181 * user configured offset ($timecorrection)
2182 * @param mixed $format What format to return, if it's false output the
2183 * default one (default true)
2184 * @param string|bool $timecorrection The time offset as returned by
2185 * validateTimeZone() in Special:Preferences
2186 * @return string
2188 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2189 $ts = wfTimestamp( TS_MW, $ts );
2190 if ( $adj ) {
2191 $ts = $this->userAdjust( $ts, $timecorrection );
2193 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2194 return $this->sprintfDate( $df, $ts );
2198 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2200 * @since 1.20
2202 * @param int $seconds The amount of seconds.
2203 * @param array $chosenIntervals The intervals to enable.
2205 * @return string
2207 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2208 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2210 $segments = array();
2212 foreach ( $intervals as $intervalName => $intervalValue ) {
2213 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2214 // duration-years, duration-decades, duration-centuries, duration-millennia
2215 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2216 $segments[] = $message->inLanguage( $this )->escaped();
2219 return $this->listToText( $segments );
2223 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2224 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2226 * @since 1.20
2228 * @param int $seconds The amount of seconds.
2229 * @param array $chosenIntervals The intervals to enable.
2231 * @return array
2233 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2234 if ( empty( $chosenIntervals ) ) {
2235 $chosenIntervals = array(
2236 'millennia',
2237 'centuries',
2238 'decades',
2239 'years',
2240 'days',
2241 'hours',
2242 'minutes',
2243 'seconds'
2247 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2248 $sortedNames = array_keys( $intervals );
2249 $smallestInterval = array_pop( $sortedNames );
2251 $segments = array();
2253 foreach ( $intervals as $name => $length ) {
2254 $value = floor( $seconds / $length );
2256 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2257 $seconds -= $value * $length;
2258 $segments[$name] = $value;
2262 return $segments;
2266 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2268 * @param string $type Can be 'date', 'time' or 'both'
2269 * @param string $ts The time format which needs to be turned into a
2270 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2271 * @param User $user User object used to get preferences for timezone and format
2272 * @param array $options Array, can contain the following keys:
2273 * - 'timecorrection': time correction, can have the following values:
2274 * - true: use user's preference
2275 * - false: don't use time correction
2276 * - int: value of time correction in minutes
2277 * - 'format': format to use, can have the following values:
2278 * - true: use user's preference
2279 * - false: use default preference
2280 * - string: format to use
2281 * @since 1.19
2282 * @return string
2284 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2285 $ts = wfTimestamp( TS_MW, $ts );
2286 $options += array( 'timecorrection' => true, 'format' => true );
2287 if ( $options['timecorrection'] !== false ) {
2288 if ( $options['timecorrection'] === true ) {
2289 $offset = $user->getOption( 'timecorrection' );
2290 } else {
2291 $offset = $options['timecorrection'];
2293 $ts = $this->userAdjust( $ts, $offset );
2295 if ( $options['format'] === true ) {
2296 $format = $user->getDatePreference();
2297 } else {
2298 $format = $options['format'];
2300 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2301 return $this->sprintfDate( $df, $ts );
2305 * Get the formatted date for the given timestamp and formatted for
2306 * the given user.
2308 * @param mixed $ts Mixed: the time format which needs to be turned into a
2309 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2310 * @param User $user User object used to get preferences for timezone and format
2311 * @param array $options Array, can contain the following keys:
2312 * - 'timecorrection': time correction, can have the following values:
2313 * - true: use user's preference
2314 * - false: don't use time correction
2315 * - int: value of time correction in minutes
2316 * - 'format': format to use, can have the following values:
2317 * - true: use user's preference
2318 * - false: use default preference
2319 * - string: format to use
2320 * @since 1.19
2321 * @return string
2323 public function userDate( $ts, User $user, array $options = array() ) {
2324 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2328 * Get the formatted time for the given timestamp and formatted for
2329 * the given user.
2331 * @param mixed $ts The time format which needs to be turned into a
2332 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2333 * @param User $user User object used to get preferences for timezone and format
2334 * @param array $options Array, can contain the following keys:
2335 * - 'timecorrection': time correction, can have the following values:
2336 * - true: use user's preference
2337 * - false: don't use time correction
2338 * - int: value of time correction in minutes
2339 * - 'format': format to use, can have the following values:
2340 * - true: use user's preference
2341 * - false: use default preference
2342 * - string: format to use
2343 * @since 1.19
2344 * @return string
2346 public function userTime( $ts, User $user, array $options = array() ) {
2347 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2351 * Get the formatted date and time for the given timestamp and formatted for
2352 * the given user.
2354 * @param mixed $ts the time format which needs to be turned into a
2355 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2356 * @param User $user User object used to get preferences for timezone and format
2357 * @param array $options Array, can contain the following keys:
2358 * - 'timecorrection': time correction, can have the following values:
2359 * - true: use user's preference
2360 * - false: don't use time correction
2361 * - int: value of time correction in minutes
2362 * - 'format': format to use, can have the following values:
2363 * - true: use user's preference
2364 * - false: use default preference
2365 * - string: format to use
2366 * @since 1.19
2367 * @return string
2369 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2370 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2374 * Convert an MWTimestamp into a pretty human-readable timestamp using
2375 * the given user preferences and relative base time.
2377 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2378 * on your timestamp object, which will then call this function. Calling
2379 * this function directly will cause hooks to be skipped over.
2381 * @see MWTimestamp::getHumanTimestamp
2382 * @param MWTimestamp $ts Timestamp to prettify
2383 * @param MWTimestamp $relativeTo Base timestamp
2384 * @param User $user User preferences to use
2385 * @return string Human timestamp
2386 * @since 1.22
2388 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2389 $diff = $ts->diff( $relativeTo );
2390 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2391 (int)$relativeTo->timestamp->format( 'w' ) );
2392 $days = $diff->days ?: (int)$diffDay;
2393 if ( $diff->invert || $days > 5
2394 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2396 // Timestamps are in different years: use full timestamp
2397 // Also do full timestamp for future dates
2399 * @todo FIXME: Add better handling of future timestamps.
2401 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2402 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2403 } elseif ( $days > 5 ) {
2404 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2405 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2406 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2407 } elseif ( $days > 1 ) {
2408 // Timestamp within the past week: show the day of the week and time
2409 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2410 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2411 // Messages:
2412 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2413 $ts = wfMessage( "$weekday-at" )
2414 ->inLanguage( $this )
2415 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2416 ->text();
2417 } elseif ( $days == 1 ) {
2418 // Timestamp was yesterday: say 'yesterday' and the time.
2419 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2420 $ts = wfMessage( 'yesterday-at' )
2421 ->inLanguage( $this )
2422 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2423 ->text();
2424 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2425 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2426 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2427 $ts = wfMessage( 'today-at' )
2428 ->inLanguage( $this )
2429 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2430 ->text();
2432 // From here on in, the timestamp was soon enough ago so that we can simply say
2433 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2434 } elseif ( $diff->h == 1 ) {
2435 // Less than 90 minutes, but more than an hour ago.
2436 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2437 } elseif ( $diff->i >= 1 ) {
2438 // A few minutes ago.
2439 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2440 } elseif ( $diff->s >= 30 ) {
2441 // Less than a minute, but more than 30 sec ago.
2442 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2443 } else {
2444 // Less than 30 seconds ago.
2445 $ts = wfMessage( 'just-now' )->text();
2448 return $ts;
2452 * @param string $key
2453 * @return array|null
2455 function getMessage( $key ) {
2456 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2460 * @return array
2462 function getAllMessages() {
2463 return self::$dataCache->getItem( $this->mCode, 'messages' );
2467 * @param string $in
2468 * @param string $out
2469 * @param string $string
2470 * @return string
2472 function iconv( $in, $out, $string ) {
2473 # This is a wrapper for iconv in all languages except esperanto,
2474 # which does some nasty x-conversions beforehand
2476 # Even with //IGNORE iconv can whine about illegal characters in
2477 # *input* string. We just ignore those too.
2478 # REF: http://bugs.php.net/bug.php?id=37166
2479 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2480 wfSuppressWarnings();
2481 $text = iconv( $in, $out . '//IGNORE', $string );
2482 wfRestoreWarnings();
2483 return $text;
2486 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2489 * @param array $matches
2490 * @return mixed|string
2492 function ucwordbreaksCallbackAscii( $matches ) {
2493 return $this->ucfirst( $matches[1] );
2497 * @param array $matches
2498 * @return string
2500 function ucwordbreaksCallbackMB( $matches ) {
2501 return mb_strtoupper( $matches[0] );
2505 * @param array $matches
2506 * @return string
2508 function ucCallback( $matches ) {
2509 list( $wikiUpperChars ) = self::getCaseMaps();
2510 return strtr( $matches[1], $wikiUpperChars );
2514 * @param array $matches
2515 * @return string
2517 function lcCallback( $matches ) {
2518 list( , $wikiLowerChars ) = self::getCaseMaps();
2519 return strtr( $matches[1], $wikiLowerChars );
2523 * @param array $matches
2524 * @return string
2526 function ucwordsCallbackMB( $matches ) {
2527 return mb_strtoupper( $matches[0] );
2531 * @param array $matches
2532 * @return string
2534 function ucwordsCallbackWiki( $matches ) {
2535 list( $wikiUpperChars ) = self::getCaseMaps();
2536 return strtr( $matches[0], $wikiUpperChars );
2540 * Make a string's first character uppercase
2542 * @param string $str
2544 * @return string
2546 function ucfirst( $str ) {
2547 $o = ord( $str );
2548 if ( $o < 96 ) { // if already uppercase...
2549 return $str;
2550 } elseif ( $o < 128 ) {
2551 return ucfirst( $str ); // use PHP's ucfirst()
2552 } else {
2553 // fall back to more complex logic in case of multibyte strings
2554 return $this->uc( $str, true );
2559 * Convert a string to uppercase
2561 * @param string $str
2562 * @param bool $first
2564 * @return string
2566 function uc( $str, $first = false ) {
2567 if ( function_exists( 'mb_strtoupper' ) ) {
2568 if ( $first ) {
2569 if ( $this->isMultibyte( $str ) ) {
2570 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2571 } else {
2572 return ucfirst( $str );
2574 } else {
2575 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2577 } else {
2578 if ( $this->isMultibyte( $str ) ) {
2579 $x = $first ? '^' : '';
2580 return preg_replace_callback(
2581 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2582 array( $this, 'ucCallback' ),
2583 $str
2585 } else {
2586 return $first ? ucfirst( $str ) : strtoupper( $str );
2592 * @param string $str
2593 * @return mixed|string
2595 function lcfirst( $str ) {
2596 $o = ord( $str );
2597 if ( !$o ) {
2598 return strval( $str );
2599 } elseif ( $o >= 128 ) {
2600 return $this->lc( $str, true );
2601 } elseif ( $o > 96 ) {
2602 return $str;
2603 } else {
2604 $str[0] = strtolower( $str[0] );
2605 return $str;
2610 * @param string $str
2611 * @param bool $first
2612 * @return mixed|string
2614 function lc( $str, $first = false ) {
2615 if ( function_exists( 'mb_strtolower' ) ) {
2616 if ( $first ) {
2617 if ( $this->isMultibyte( $str ) ) {
2618 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2619 } else {
2620 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2622 } else {
2623 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2625 } else {
2626 if ( $this->isMultibyte( $str ) ) {
2627 $x = $first ? '^' : '';
2628 return preg_replace_callback(
2629 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2630 array( $this, 'lcCallback' ),
2631 $str
2633 } else {
2634 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2640 * @param string $str
2641 * @return bool
2643 function isMultibyte( $str ) {
2644 return (bool)preg_match( '/[\x80-\xff]/', $str );
2648 * @param string $str
2649 * @return mixed|string
2651 function ucwords( $str ) {
2652 if ( $this->isMultibyte( $str ) ) {
2653 $str = $this->lc( $str );
2655 // regexp to find first letter in each word (i.e. after each space)
2656 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2658 // function to use to capitalize a single char
2659 if ( function_exists( 'mb_strtoupper' ) ) {
2660 return preg_replace_callback(
2661 $replaceRegexp,
2662 array( $this, 'ucwordsCallbackMB' ),
2663 $str
2665 } else {
2666 return preg_replace_callback(
2667 $replaceRegexp,
2668 array( $this, 'ucwordsCallbackWiki' ),
2669 $str
2672 } else {
2673 return ucwords( strtolower( $str ) );
2678 * capitalize words at word breaks
2680 * @param string $str
2681 * @return mixed
2683 function ucwordbreaks( $str ) {
2684 if ( $this->isMultibyte( $str ) ) {
2685 $str = $this->lc( $str );
2687 // since \b doesn't work for UTF-8, we explicitely define word break chars
2688 $breaks = "[ \-\(\)\}\{\.,\?!]";
2690 // find first letter after word break
2691 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2692 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2694 if ( function_exists( 'mb_strtoupper' ) ) {
2695 return preg_replace_callback(
2696 $replaceRegexp,
2697 array( $this, 'ucwordbreaksCallbackMB' ),
2698 $str
2700 } else {
2701 return preg_replace_callback(
2702 $replaceRegexp,
2703 array( $this, 'ucwordsCallbackWiki' ),
2704 $str
2707 } else {
2708 return preg_replace_callback(
2709 '/\b([\w\x80-\xff]+)\b/',
2710 array( $this, 'ucwordbreaksCallbackAscii' ),
2711 $str
2717 * Return a case-folded representation of $s
2719 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2720 * and $s2 are the same except for the case of their characters. It is not
2721 * necessary for the value returned to make sense when displayed.
2723 * Do *not* perform any other normalisation in this function. If a caller
2724 * uses this function when it should be using a more general normalisation
2725 * function, then fix the caller.
2727 * @param string $s
2729 * @return string
2731 function caseFold( $s ) {
2732 return $this->uc( $s );
2736 * @param string $s
2737 * @return string
2739 function checkTitleEncoding( $s ) {
2740 if ( is_array( $s ) ) {
2741 throw new MWException( 'Given array to checkTitleEncoding.' );
2743 if ( StringUtils::isUtf8( $s ) ) {
2744 return $s;
2747 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2751 * @return array
2753 function fallback8bitEncoding() {
2754 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2758 * Most writing systems use whitespace to break up words.
2759 * Some languages such as Chinese don't conventionally do this,
2760 * which requires special handling when breaking up words for
2761 * searching etc.
2763 * @return bool
2765 function hasWordBreaks() {
2766 return true;
2770 * Some languages such as Chinese require word segmentation,
2771 * Specify such segmentation when overridden in derived class.
2773 * @param string $string
2774 * @return string
2776 function segmentByWord( $string ) {
2777 return $string;
2781 * Some languages have special punctuation need to be normalized.
2782 * Make such changes here.
2784 * @param string $string
2785 * @return string
2787 function normalizeForSearch( $string ) {
2788 return self::convertDoubleWidth( $string );
2792 * convert double-width roman characters to single-width.
2793 * range: ff00-ff5f ~= 0020-007f
2795 * @param string $string
2797 * @return string
2799 protected static function convertDoubleWidth( $string ) {
2800 static $full = null;
2801 static $half = null;
2803 if ( $full === null ) {
2804 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2805 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2806 $full = str_split( $fullWidth, 3 );
2807 $half = str_split( $halfWidth );
2810 $string = str_replace( $full, $half, $string );
2811 return $string;
2815 * @param string $string
2816 * @param string $pattern
2817 * @return string
2819 protected static function insertSpace( $string, $pattern ) {
2820 $string = preg_replace( $pattern, " $1 ", $string );
2821 $string = preg_replace( '/ +/', ' ', $string );
2822 return $string;
2826 * @param array $termsArray
2827 * @return array
2829 function convertForSearchResult( $termsArray ) {
2830 # some languages, e.g. Chinese, need to do a conversion
2831 # in order for search results to be displayed correctly
2832 return $termsArray;
2836 * Get the first character of a string.
2838 * @param string $s
2839 * @return string
2841 function firstChar( $s ) {
2842 $matches = array();
2843 preg_match(
2844 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2845 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2847 $matches
2850 if ( isset( $matches[1] ) ) {
2851 if ( strlen( $matches[1] ) != 3 ) {
2852 return $matches[1];
2855 // Break down Hangul syllables to grab the first jamo
2856 $code = utf8ToCodepoint( $matches[1] );
2857 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2858 return $matches[1];
2859 } elseif ( $code < 0xb098 ) {
2860 return "\xe3\x84\xb1";
2861 } elseif ( $code < 0xb2e4 ) {
2862 return "\xe3\x84\xb4";
2863 } elseif ( $code < 0xb77c ) {
2864 return "\xe3\x84\xb7";
2865 } elseif ( $code < 0xb9c8 ) {
2866 return "\xe3\x84\xb9";
2867 } elseif ( $code < 0xbc14 ) {
2868 return "\xe3\x85\x81";
2869 } elseif ( $code < 0xc0ac ) {
2870 return "\xe3\x85\x82";
2871 } elseif ( $code < 0xc544 ) {
2872 return "\xe3\x85\x85";
2873 } elseif ( $code < 0xc790 ) {
2874 return "\xe3\x85\x87";
2875 } elseif ( $code < 0xcc28 ) {
2876 return "\xe3\x85\x88";
2877 } elseif ( $code < 0xce74 ) {
2878 return "\xe3\x85\x8a";
2879 } elseif ( $code < 0xd0c0 ) {
2880 return "\xe3\x85\x8b";
2881 } elseif ( $code < 0xd30c ) {
2882 return "\xe3\x85\x8c";
2883 } elseif ( $code < 0xd558 ) {
2884 return "\xe3\x85\x8d";
2885 } else {
2886 return "\xe3\x85\x8e";
2888 } else {
2889 return '';
2893 function initEncoding() {
2894 # Some languages may have an alternate char encoding option
2895 # (Esperanto X-coding, Japanese furigana conversion, etc)
2896 # If this language is used as the primary content language,
2897 # an override to the defaults can be set here on startup.
2901 * @param string $s
2902 * @return string
2904 function recodeForEdit( $s ) {
2905 # For some languages we'll want to explicitly specify
2906 # which characters make it into the edit box raw
2907 # or are converted in some way or another.
2908 global $wgEditEncoding;
2909 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2910 return $s;
2911 } else {
2912 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2917 * @param string $s
2918 * @return string
2920 function recodeInput( $s ) {
2921 # Take the previous into account.
2922 global $wgEditEncoding;
2923 if ( $wgEditEncoding != '' ) {
2924 $enc = $wgEditEncoding;
2925 } else {
2926 $enc = 'UTF-8';
2928 if ( $enc == 'UTF-8' ) {
2929 return $s;
2930 } else {
2931 return $this->iconv( $enc, 'UTF-8', $s );
2936 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2937 * also cleans up certain backwards-compatible sequences, converting them
2938 * to the modern Unicode equivalent.
2940 * This is language-specific for performance reasons only.
2942 * @param string $s
2944 * @return string
2946 function normalize( $s ) {
2947 global $wgAllUnicodeFixes;
2948 $s = UtfNormal::cleanUp( $s );
2949 if ( $wgAllUnicodeFixes ) {
2950 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2951 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2954 return $s;
2958 * Transform a string using serialized data stored in the given file (which
2959 * must be in the serialized subdirectory of $IP). The file contains pairs
2960 * mapping source characters to destination characters.
2962 * The data is cached in process memory. This will go faster if you have the
2963 * FastStringSearch extension.
2965 * @param string $file
2966 * @param string $string
2968 * @throws MWException
2969 * @return string
2971 function transformUsingPairFile( $file, $string ) {
2972 if ( !isset( $this->transformData[$file] ) ) {
2973 $data = wfGetPrecompiledData( $file );
2974 if ( $data === false ) {
2975 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2977 $this->transformData[$file] = new ReplacementArray( $data );
2979 return $this->transformData[$file]->replace( $string );
2983 * For right-to-left language support
2985 * @return bool
2987 function isRTL() {
2988 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2992 * Return the correct HTML 'dir' attribute value for this language.
2993 * @return string
2995 function getDir() {
2996 return $this->isRTL() ? 'rtl' : 'ltr';
3000 * Return 'left' or 'right' as appropriate alignment for line-start
3001 * for this language's text direction.
3003 * Should be equivalent to CSS3 'start' text-align value....
3005 * @return string
3007 function alignStart() {
3008 return $this->isRTL() ? 'right' : 'left';
3012 * Return 'right' or 'left' as appropriate alignment for line-end
3013 * for this language's text direction.
3015 * Should be equivalent to CSS3 'end' text-align value....
3017 * @return string
3019 function alignEnd() {
3020 return $this->isRTL() ? 'left' : 'right';
3024 * A hidden direction mark (LRM or RLM), depending on the language direction.
3025 * Unlike getDirMark(), this function returns the character as an HTML entity.
3026 * This function should be used when the output is guaranteed to be HTML,
3027 * because it makes the output HTML source code more readable. When
3028 * the output is plain text or can be escaped, getDirMark() should be used.
3030 * @param bool $opposite Get the direction mark opposite to your language
3031 * @return string
3032 * @since 1.20
3034 function getDirMarkEntity( $opposite = false ) {
3035 if ( $opposite ) {
3036 return $this->isRTL() ? '&lrm;' : '&rlm;';
3038 return $this->isRTL() ? '&rlm;' : '&lrm;';
3042 * A hidden direction mark (LRM or RLM), depending on the language direction.
3043 * This function produces them as invisible Unicode characters and
3044 * the output may be hard to read and debug, so it should only be used
3045 * when the output is plain text or can be escaped. When the output is
3046 * HTML, use getDirMarkEntity() instead.
3048 * @param bool $opposite Get the direction mark opposite to your language
3049 * @return string
3051 function getDirMark( $opposite = false ) {
3052 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3053 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3054 if ( $opposite ) {
3055 return $this->isRTL() ? $lrm : $rlm;
3057 return $this->isRTL() ? $rlm : $lrm;
3061 * @return array
3063 function capitalizeAllNouns() {
3064 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3068 * An arrow, depending on the language direction.
3070 * @param string $direction The direction of the arrow: forwards (default),
3071 * backwards, left, right, up, down.
3072 * @return string
3074 function getArrow( $direction = 'forwards' ) {
3075 switch ( $direction ) {
3076 case 'forwards':
3077 return $this->isRTL() ? '←' : '→';
3078 case 'backwards':
3079 return $this->isRTL() ? '→' : '←';
3080 case 'left':
3081 return '←';
3082 case 'right':
3083 return '→';
3084 case 'up':
3085 return '↑';
3086 case 'down':
3087 return '↓';
3092 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3094 * @return bool
3096 function linkPrefixExtension() {
3097 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
3101 * Get all magic words from cache.
3102 * @return array
3104 function getMagicWords() {
3105 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
3109 * Run the LanguageGetMagic hook once.
3111 protected function doMagicHook() {
3112 if ( $this->mMagicHookDone ) {
3113 return;
3115 $this->mMagicHookDone = true;
3116 wfProfileIn( 'LanguageGetMagic' );
3117 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3118 wfProfileOut( 'LanguageGetMagic' );
3122 * Fill a MagicWord object with data from here
3124 * @param MagicWord $mw
3126 function getMagic( $mw ) {
3127 // Saves a function call
3128 if ( ! $this->mMagicHookDone ) {
3129 $this->doMagicHook();
3132 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3133 $rawEntry = $this->mMagicExtensions[$mw->mId];
3134 } else {
3135 $rawEntry = self::$dataCache->getSubitem(
3136 $this->mCode, 'magicWords', $mw->mId );
3139 if ( !is_array( $rawEntry ) ) {
3140 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3141 } else {
3142 $mw->mCaseSensitive = $rawEntry[0];
3143 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3148 * Add magic words to the extension array
3150 * @param array $newWords
3152 function addMagicWordsByLang( $newWords ) {
3153 $fallbackChain = $this->getFallbackLanguages();
3154 $fallbackChain = array_reverse( $fallbackChain );
3155 foreach ( $fallbackChain as $code ) {
3156 if ( isset( $newWords[$code] ) ) {
3157 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3163 * Get special page names, as an associative array
3164 * case folded alias => real name
3165 * @return array
3167 function getSpecialPageAliases() {
3168 // Cache aliases because it may be slow to load them
3169 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3170 // Initialise array
3171 $this->mExtendedSpecialPageAliases =
3172 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3173 wfRunHooks( 'LanguageGetSpecialPageAliases',
3174 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3177 return $this->mExtendedSpecialPageAliases;
3181 * Italic is unsuitable for some languages
3183 * @param string $text The text to be emphasized.
3184 * @return string
3186 function emphasize( $text ) {
3187 return "<em>$text</em>";
3191 * Normally we output all numbers in plain en_US style, that is
3192 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3193 * point twohundredthirtyfive. However this is not suitable for all
3194 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3195 * Icelandic just want to use commas instead of dots, and dots instead
3196 * of commas like "293.291,235".
3198 * An example of this function being called:
3199 * <code>
3200 * wfMessage( 'message' )->numParams( $num )->text()
3201 * </code>
3203 * See $separatorTransformTable on MessageIs.php for
3204 * the , => . and . => , implementation.
3206 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3207 * @param int|float $number The string to be formatted, should be an integer
3208 * or a floating point number.
3209 * @param bool $nocommafy Set to true for special numbers like dates
3210 * @return string
3212 public function formatNum( $number, $nocommafy = false ) {
3213 global $wgTranslateNumerals;
3214 if ( !$nocommafy ) {
3215 $number = $this->commafy( $number );
3216 $s = $this->separatorTransformTable();
3217 if ( $s ) {
3218 $number = strtr( $number, $s );
3222 if ( $wgTranslateNumerals ) {
3223 $s = $this->digitTransformTable();
3224 if ( $s ) {
3225 $number = strtr( $number, $s );
3229 return $number;
3233 * Front-end for non-commafied formatNum
3235 * @param int|float $number The string to be formatted, should be an integer
3236 * or a floating point number.
3237 * @since 1.21
3238 * @return string
3240 public function formatNumNoSeparators( $number ) {
3241 return $this->formatNum( $number, true );
3245 * @param string $number
3246 * @return string
3248 public function parseFormattedNumber( $number ) {
3249 $s = $this->digitTransformTable();
3250 if ( $s ) {
3251 // eliminate empty array values such as ''. (bug 64347)
3252 $s = array_filter( $s );
3253 $number = strtr( $number, array_flip( $s ) );
3256 $s = $this->separatorTransformTable();
3257 if ( $s ) {
3258 // eliminate empty array values such as ''. (bug 64347)
3259 $s = array_filter( $s );
3260 $number = strtr( $number, array_flip( $s ) );
3263 $number = strtr( $number, array( ',' => '' ) );
3264 return $number;
3268 * Adds commas to a given number
3269 * @since 1.19
3270 * @param mixed $number
3271 * @return string
3273 function commafy( $number ) {
3274 $digitGroupingPattern = $this->digitGroupingPattern();
3275 if ( $number === null ) {
3276 return '';
3279 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3280 // default grouping is at thousands, use the same for ###,###,### pattern too.
3281 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3282 } else {
3283 // Ref: http://cldr.unicode.org/translation/number-patterns
3284 $sign = "";
3285 if ( intval( $number ) < 0 ) {
3286 // For negative numbers apply the algorithm like positive number and add sign.
3287 $sign = "-";
3288 $number = substr( $number, 1 );
3290 $integerPart = array();
3291 $decimalPart = array();
3292 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3293 preg_match( "/\d+/", $number, $integerPart );
3294 preg_match( "/\.\d*/", $number, $decimalPart );
3295 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3296 if ( $groupedNumber === $number ) {
3297 // the string does not have any number part. Eg: .12345
3298 return $sign . $groupedNumber;
3300 $start = $end = strlen( $integerPart[0] );
3301 while ( $start > 0 ) {
3302 $match = $matches[0][$numMatches - 1];
3303 $matchLen = strlen( $match );
3304 $start = $end - $matchLen;
3305 if ( $start < 0 ) {
3306 $start = 0;
3308 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3309 $end = $start;
3310 if ( $numMatches > 1 ) {
3311 // use the last pattern for the rest of the number
3312 $numMatches--;
3314 if ( $start > 0 ) {
3315 $groupedNumber = "," . $groupedNumber;
3318 return $sign . $groupedNumber;
3323 * @return string
3325 function digitGroupingPattern() {
3326 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3330 * @return array
3332 function digitTransformTable() {
3333 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3337 * @return array
3339 function separatorTransformTable() {
3340 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3344 * Take a list of strings and build a locale-friendly comma-separated
3345 * list, using the local comma-separator message.
3346 * The last two strings are chained with an "and".
3347 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3349 * @param string[] $l
3350 * @return string
3352 function listToText( array $l ) {
3353 $m = count( $l ) - 1;
3354 if ( $m < 0 ) {
3355 return '';
3357 if ( $m > 0 ) {
3358 $and = $this->getMessageFromDB( 'and' );
3359 $space = $this->getMessageFromDB( 'word-separator' );
3360 if ( $m > 1 ) {
3361 $comma = $this->getMessageFromDB( 'comma-separator' );
3364 $s = $l[$m];
3365 for ( $i = $m - 1; $i >= 0; $i-- ) {
3366 if ( $i == $m - 1 ) {
3367 $s = $l[$i] . $and . $space . $s;
3368 } else {
3369 $s = $l[$i] . $comma . $s;
3372 return $s;
3376 * Take a list of strings and build a locale-friendly comma-separated
3377 * list, using the local comma-separator message.
3378 * @param string[] $list Array of strings to put in a comma list
3379 * @return string
3381 function commaList( array $list ) {
3382 return implode(
3383 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3384 $list
3389 * Take a list of strings and build a locale-friendly semicolon-separated
3390 * list, using the local semicolon-separator message.
3391 * @param string[] $list Array of strings to put in a semicolon list
3392 * @return string
3394 function semicolonList( array $list ) {
3395 return implode(
3396 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3397 $list
3402 * Same as commaList, but separate it with the pipe instead.
3403 * @param string[] $list Array of strings to put in a pipe list
3404 * @return string
3406 function pipeList( array $list ) {
3407 return implode(
3408 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3409 $list
3414 * Truncate a string to a specified length in bytes, appending an optional
3415 * string (e.g. for ellipses)
3417 * The database offers limited byte lengths for some columns in the database;
3418 * multi-byte character sets mean we need to ensure that only whole characters
3419 * are included, otherwise broken characters can be passed to the user
3421 * If $length is negative, the string will be truncated from the beginning
3423 * @param string $string String to truncate
3424 * @param int $length Maximum length (including ellipses)
3425 * @param string $ellipsis String to append to the truncated text
3426 * @param bool $adjustLength Subtract length of ellipsis from $length.
3427 * $adjustLength was introduced in 1.18, before that behaved as if false.
3428 * @return string
3430 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3431 # Use the localized ellipsis character
3432 if ( $ellipsis == '...' ) {
3433 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3435 # Check if there is no need to truncate
3436 if ( $length == 0 ) {
3437 return $ellipsis; // convention
3438 } elseif ( strlen( $string ) <= abs( $length ) ) {
3439 return $string; // no need to truncate
3441 $stringOriginal = $string;
3442 # If ellipsis length is >= $length then we can't apply $adjustLength
3443 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3444 $string = $ellipsis; // this can be slightly unexpected
3445 # Otherwise, truncate and add ellipsis...
3446 } else {
3447 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3448 if ( $length > 0 ) {
3449 $length -= $eLength;
3450 $string = substr( $string, 0, $length ); // xyz...
3451 $string = $this->removeBadCharLast( $string );
3452 $string = rtrim( $string );
3453 $string = $string . $ellipsis;
3454 } else {
3455 $length += $eLength;
3456 $string = substr( $string, $length ); // ...xyz
3457 $string = $this->removeBadCharFirst( $string );
3458 $string = ltrim( $string );
3459 $string = $ellipsis . $string;
3462 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3463 # This check is *not* redundant if $adjustLength, due to the single case where
3464 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3465 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3466 return $string;
3467 } else {
3468 return $stringOriginal;
3473 * Remove bytes that represent an incomplete Unicode character
3474 * at the end of string (e.g. bytes of the char are missing)
3476 * @param string $string
3477 * @return string
3479 protected function removeBadCharLast( $string ) {
3480 if ( $string != '' ) {
3481 $char = ord( $string[strlen( $string ) - 1] );
3482 $m = array();
3483 if ( $char >= 0xc0 ) {
3484 # We got the first byte only of a multibyte char; remove it.
3485 $string = substr( $string, 0, -1 );
3486 } elseif ( $char >= 0x80 &&
3487 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3488 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3490 # We chopped in the middle of a character; remove it
3491 $string = $m[1];
3494 return $string;
3498 * Remove bytes that represent an incomplete Unicode character
3499 * at the start of string (e.g. bytes of the char are missing)
3501 * @param string $string
3502 * @return string
3504 protected function removeBadCharFirst( $string ) {
3505 if ( $string != '' ) {
3506 $char = ord( $string[0] );
3507 if ( $char >= 0x80 && $char < 0xc0 ) {
3508 # We chopped in the middle of a character; remove the whole thing
3509 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3512 return $string;
3516 * Truncate a string of valid HTML to a specified length in bytes,
3517 * appending an optional string (e.g. for ellipses), and return valid HTML
3519 * This is only intended for styled/linked text, such as HTML with
3520 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3521 * Also, this will not detect things like "display:none" CSS.
3523 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3525 * @param string $text HTML string to truncate
3526 * @param int $length (zero/positive) Maximum length (including ellipses)
3527 * @param string $ellipsis String to append to the truncated text
3528 * @return string
3530 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3531 # Use the localized ellipsis character
3532 if ( $ellipsis == '...' ) {
3533 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3535 # Check if there is clearly no need to truncate
3536 if ( $length <= 0 ) {
3537 return $ellipsis; // no text shown, nothing to format (convention)
3538 } elseif ( strlen( $text ) <= $length ) {
3539 return $text; // string short enough even *with* HTML (short-circuit)
3542 $dispLen = 0; // innerHTML legth so far
3543 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3544 $tagType = 0; // 0-open, 1-close
3545 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3546 $entityState = 0; // 0-not entity, 1-entity
3547 $tag = $ret = ''; // accumulated tag name, accumulated result string
3548 $openTags = array(); // open tag stack
3549 $maybeState = null; // possible truncation state
3551 $textLen = strlen( $text );
3552 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3553 for ( $pos = 0; true; ++$pos ) {
3554 # Consider truncation once the display length has reached the maximim.
3555 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3556 # Check that we're not in the middle of a bracket/entity...
3557 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3558 if ( !$testingEllipsis ) {
3559 $testingEllipsis = true;
3560 # Save where we are; we will truncate here unless there turn out to
3561 # be so few remaining characters that truncation is not necessary.
3562 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3563 $maybeState = array( $ret, $openTags ); // save state
3565 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3566 # String in fact does need truncation, the truncation point was OK.
3567 list( $ret, $openTags ) = $maybeState; // reload state
3568 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3569 $ret .= $ellipsis; // add ellipsis
3570 break;
3573 if ( $pos >= $textLen ) {
3574 break; // extra iteration just for above checks
3577 # Read the next char...
3578 $ch = $text[$pos];
3579 $lastCh = $pos ? $text[$pos - 1] : '';
3580 $ret .= $ch; // add to result string
3581 if ( $ch == '<' ) {
3582 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3583 $entityState = 0; // for bad HTML
3584 $bracketState = 1; // tag started (checking for backslash)
3585 } elseif ( $ch == '>' ) {
3586 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3587 $entityState = 0; // for bad HTML
3588 $bracketState = 0; // out of brackets
3589 } elseif ( $bracketState == 1 ) {
3590 if ( $ch == '/' ) {
3591 $tagType = 1; // close tag (e.g. "</span>")
3592 } else {
3593 $tagType = 0; // open tag (e.g. "<span>")
3594 $tag .= $ch;
3596 $bracketState = 2; // building tag name
3597 } elseif ( $bracketState == 2 ) {
3598 if ( $ch != ' ' ) {
3599 $tag .= $ch;
3600 } else {
3601 // Name found (e.g. "<a href=..."), add on tag attributes...
3602 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3604 } elseif ( $bracketState == 0 ) {
3605 if ( $entityState ) {
3606 if ( $ch == ';' ) {
3607 $entityState = 0;
3608 $dispLen++; // entity is one displayed char
3610 } else {
3611 if ( $neLength == 0 && !$maybeState ) {
3612 // Save state without $ch. We want to *hit* the first
3613 // display char (to get tags) but not *use* it if truncating.
3614 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3616 if ( $ch == '&' ) {
3617 $entityState = 1; // entity found, (e.g. "&#160;")
3618 } else {
3619 $dispLen++; // this char is displayed
3620 // Add the next $max display text chars after this in one swoop...
3621 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3622 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3623 $dispLen += $skipped;
3624 $pos += $skipped;
3629 // Close the last tag if left unclosed by bad HTML
3630 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3631 while ( count( $openTags ) > 0 ) {
3632 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3634 return $ret;
3638 * truncateHtml() helper function
3639 * like strcspn() but adds the skipped chars to $ret
3641 * @param string $ret
3642 * @param string $text
3643 * @param string $search
3644 * @param int $start
3645 * @param null|int $len
3646 * @return int
3648 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3649 if ( $len === null ) {
3650 $len = -1; // -1 means "no limit" for strcspn
3651 } elseif ( $len < 0 ) {
3652 $len = 0; // sanity
3654 $skipCount = 0;
3655 if ( $start < strlen( $text ) ) {
3656 $skipCount = strcspn( $text, $search, $start, $len );
3657 $ret .= substr( $text, $start, $skipCount );
3659 return $skipCount;
3663 * truncateHtml() helper function
3664 * (a) push or pop $tag from $openTags as needed
3665 * (b) clear $tag value
3666 * @param string &$tag Current HTML tag name we are looking at
3667 * @param int $tagType (0-open tag, 1-close tag)
3668 * @param string $lastCh Character before the '>' that ended this tag
3669 * @param array &$openTags Open tag stack (not accounting for $tag)
3671 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3672 $tag = ltrim( $tag );
3673 if ( $tag != '' ) {
3674 if ( $tagType == 0 && $lastCh != '/' ) {
3675 $openTags[] = $tag; // tag opened (didn't close itself)
3676 } elseif ( $tagType == 1 ) {
3677 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3678 array_pop( $openTags ); // tag closed
3681 $tag = '';
3686 * Grammatical transformations, needed for inflected languages
3687 * Invoked by putting {{grammar:case|word}} in a message
3689 * @param string $word
3690 * @param string $case
3691 * @return string
3693 function convertGrammar( $word, $case ) {
3694 global $wgGrammarForms;
3695 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3696 return $wgGrammarForms[$this->getCode()][$case][$word];
3699 return $word;
3702 * Get the grammar forms for the content language
3703 * @return array Array of grammar forms
3704 * @since 1.20
3706 function getGrammarForms() {
3707 global $wgGrammarForms;
3708 if ( isset( $wgGrammarForms[$this->getCode()] )
3709 && is_array( $wgGrammarForms[$this->getCode()] )
3711 return $wgGrammarForms[$this->getCode()];
3714 return array();
3717 * Provides an alternative text depending on specified gender.
3718 * Usage {{gender:username|masculine|feminine|unknown}}.
3719 * username is optional, in which case the gender of current user is used,
3720 * but only in (some) interface messages; otherwise default gender is used.
3722 * If no forms are given, an empty string is returned. If only one form is
3723 * given, it will be returned unconditionally. These details are implied by
3724 * the caller and cannot be overridden in subclasses.
3726 * If three forms are given, the default is to use the third (unknown) form.
3727 * If fewer than three forms are given, the default is to use the first (masculine) form.
3728 * These details can be overridden in subclasses.
3730 * @param string $gender
3731 * @param array $forms
3733 * @return string
3735 function gender( $gender, $forms ) {
3736 if ( !count( $forms ) ) {
3737 return '';
3739 $forms = $this->preConvertPlural( $forms, 2 );
3740 if ( $gender === 'male' ) {
3741 return $forms[0];
3743 if ( $gender === 'female' ) {
3744 return $forms[1];
3746 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3750 * Plural form transformations, needed for some languages.
3751 * For example, there are 3 form of plural in Russian and Polish,
3752 * depending on "count mod 10". See [[w:Plural]]
3753 * For English it is pretty simple.
3755 * Invoked by putting {{plural:count|wordform1|wordform2}}
3756 * or {{plural:count|wordform1|wordform2|wordform3}}
3758 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3760 * @param int $count Non-localized number
3761 * @param array $forms Different plural forms
3762 * @return string Correct form of plural for $count in this language
3764 function convertPlural( $count, $forms ) {
3765 // Handle explicit n=pluralform cases
3766 $forms = $this->handleExplicitPluralForms( $count, $forms );
3767 if ( is_string( $forms ) ) {
3768 return $forms;
3770 if ( !count( $forms ) ) {
3771 return '';
3774 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3775 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3776 return $forms[$pluralForm];
3780 * Handles explicit plural forms for Language::convertPlural()
3782 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3783 * If an explicitly defined plural form matches the $count, then
3784 * string value returned, otherwise array returned for further consideration
3785 * by CLDR rules or overridden convertPlural().
3787 * @since 1.23
3789 * @param int $count non-localized number
3790 * @param array $forms different plural forms
3792 * @return array|string
3794 protected function handleExplicitPluralForms( $count, array $forms ) {
3795 foreach ( $forms as $index => $form ) {
3796 if ( preg_match( '/\d+=/i', $form ) ) {
3797 $pos = strpos( $form, '=' );
3798 if ( substr( $form, 0, $pos ) === (string) $count ) {
3799 return substr( $form, $pos + 1 );
3801 unset( $forms[$index] );
3804 return array_values( $forms );
3808 * Checks that convertPlural was given an array and pads it to requested
3809 * amount of forms by copying the last one.
3811 * @param int $count How many forms should there be at least
3812 * @param array $forms Array of forms given to convertPlural
3813 * @return array Padded array of forms or an exception if not an array
3815 protected function preConvertPlural( /* Array */ $forms, $count ) {
3816 while ( count( $forms ) < $count ) {
3817 $forms[] = $forms[count( $forms ) - 1];
3819 return $forms;
3823 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3824 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3825 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3826 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3827 * match up with it.
3829 * @param string $str The validated block duration in English
3830 * @return string Somehow translated block duration
3831 * @see LanguageFi.php for example implementation
3833 function translateBlockExpiry( $str ) {
3834 $duration = SpecialBlock::getSuggestedDurations( $this );
3835 foreach ( $duration as $show => $value ) {
3836 if ( strcmp( $str, $value ) == 0 ) {
3837 return htmlspecialchars( trim( $show ) );
3841 // Since usually only infinite or indefinite is only on list, so try
3842 // equivalents if still here.
3843 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3844 if ( in_array( $str, $indefs ) ) {
3845 foreach ( $indefs as $val ) {
3846 $show = array_search( $val, $duration, true );
3847 if ( $show !== false ) {
3848 return htmlspecialchars( trim( $show ) );
3853 // If all else fails, return a standard duration or timestamp description.
3854 $time = strtotime( $str, 0 );
3855 if ( $time === false ) { // Unknown format. Return it as-is in case.
3856 return $str;
3857 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3858 // $time is relative to 0 so it's a duration length.
3859 return $this->formatDuration( $time );
3860 } else { // It's an absolute timestamp.
3861 if ( $time === 0 ) {
3862 // wfTimestamp() handles 0 as current time instead of epoch.
3863 return $this->timeanddate( '19700101000000' );
3864 } else {
3865 return $this->timeanddate( $time );
3871 * languages like Chinese need to be segmented in order for the diff
3872 * to be of any use
3874 * @param string $text
3875 * @return string
3877 public function segmentForDiff( $text ) {
3878 return $text;
3882 * and unsegment to show the result
3884 * @param string $text
3885 * @return string
3887 public function unsegmentForDiff( $text ) {
3888 return $text;
3892 * Return the LanguageConverter used in the Language
3894 * @since 1.19
3895 * @return LanguageConverter
3897 public function getConverter() {
3898 return $this->mConverter;
3902 * convert text to all supported variants
3904 * @param string $text
3905 * @return array
3907 public function autoConvertToAllVariants( $text ) {
3908 return $this->mConverter->autoConvertToAllVariants( $text );
3912 * convert text to different variants of a language.
3914 * @param string $text
3915 * @return string
3917 public function convert( $text ) {
3918 return $this->mConverter->convert( $text );
3922 * Convert a Title object to a string in the preferred variant
3924 * @param Title $title
3925 * @return string
3927 public function convertTitle( $title ) {
3928 return $this->mConverter->convertTitle( $title );
3932 * Convert a namespace index to a string in the preferred variant
3934 * @param int $ns
3935 * @return string
3937 public function convertNamespace( $ns ) {
3938 return $this->mConverter->convertNamespace( $ns );
3942 * Check if this is a language with variants
3944 * @return bool
3946 public function hasVariants() {
3947 return count( $this->getVariants() ) > 1;
3951 * Check if the language has the specific variant
3953 * @since 1.19
3954 * @param string $variant
3955 * @return bool
3957 public function hasVariant( $variant ) {
3958 return (bool)$this->mConverter->validateVariant( $variant );
3962 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3964 * @param string $text
3965 * @return string
3966 * @deprecated since 1.22 is no longer used
3968 public function armourMath( $text ) {
3969 return $this->mConverter->armourMath( $text );
3973 * Perform output conversion on a string, and encode for safe HTML output.
3974 * @param string $text Text to be converted
3975 * @param bool $isTitle Whether this conversion is for the article title
3976 * @return string
3977 * @todo this should get integrated somewhere sane
3979 public function convertHtml( $text, $isTitle = false ) {
3980 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3984 * @param string $key
3985 * @return string
3987 public function convertCategoryKey( $key ) {
3988 return $this->mConverter->convertCategoryKey( $key );
3992 * Get the list of variants supported by this language
3993 * see sample implementation in LanguageZh.php
3995 * @return array an array of language codes
3997 public function getVariants() {
3998 return $this->mConverter->getVariants();
4002 * @return string
4004 public function getPreferredVariant() {
4005 return $this->mConverter->getPreferredVariant();
4009 * @return string
4011 public function getDefaultVariant() {
4012 return $this->mConverter->getDefaultVariant();
4016 * @return string
4018 public function getURLVariant() {
4019 return $this->mConverter->getURLVariant();
4023 * If a language supports multiple variants, it is
4024 * possible that non-existing link in one variant
4025 * actually exists in another variant. this function
4026 * tries to find it. See e.g. LanguageZh.php
4028 * @param string $link The name of the link
4029 * @param Title $nt The title object of the link
4030 * @param bool $ignoreOtherCond To disable other conditions when
4031 * we need to transclude a template or update a category's link
4032 * @return null the input parameters may be modified upon return
4034 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4035 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4039 * returns language specific options used by User::getPageRenderHash()
4040 * for example, the preferred language variant
4042 * @return string
4044 function getExtraHashOptions() {
4045 return $this->mConverter->getExtraHashOptions();
4049 * For languages that support multiple variants, the title of an
4050 * article may be displayed differently in different variants. this
4051 * function returns the apporiate title defined in the body of the article.
4053 * @return string
4055 public function getParsedTitle() {
4056 return $this->mConverter->getParsedTitle();
4060 * Prepare external link text for conversion. When the text is
4061 * a URL, it shouldn't be converted, and it'll be wrapped in
4062 * the "raw" tag (-{R| }-) to prevent conversion.
4064 * This function is called "markNoConversion" for historical
4065 * reasons.
4067 * @param string $text Text to be used for external link
4068 * @param bool $noParse Wrap it without confirming it's a real URL first
4069 * @return string The tagged text
4071 public function markNoConversion( $text, $noParse = false ) {
4072 // Excluding protocal-relative URLs may avoid many false positives.
4073 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4074 return $this->mConverter->markNoConversion( $text );
4075 } else {
4076 return $text;
4081 * A regular expression to match legal word-trailing characters
4082 * which should be merged onto a link of the form [[foo]]bar.
4084 * @return string
4086 public function linkTrail() {
4087 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
4091 * A regular expression character set to match legal word-prefixing
4092 * characters which should be merged onto a link of the form foo[[bar]].
4094 * @return string
4096 public function linkPrefixCharset() {
4097 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
4101 * @deprecated since 1.24, will be removed in 1.25
4102 * @return Language
4104 function getLangObj() {
4105 wfDeprecated( __METHOD__, '1.24' );
4106 return $this;
4110 * Get the "parent" language which has a converter to convert a "compatible" language
4111 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4113 * @return Language|null
4114 * @since 1.22
4116 public function getParentLanguage() {
4117 if ( $this->mParentLanguage !== false ) {
4118 return $this->mParentLanguage;
4121 $pieces = explode( '-', $this->getCode() );
4122 $code = $pieces[0];
4123 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4124 $this->mParentLanguage = null;
4125 return null;
4127 $lang = Language::factory( $code );
4128 if ( !$lang->hasVariant( $this->getCode() ) ) {
4129 $this->mParentLanguage = null;
4130 return null;
4133 $this->mParentLanguage = $lang;
4134 return $lang;
4138 * Get the RFC 3066 code for this language object
4140 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4141 * htmlspecialchars() or similar
4143 * @return string
4145 public function getCode() {
4146 return $this->mCode;
4150 * Get the code in Bcp47 format which we can use
4151 * inside of html lang="" tags.
4153 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4154 * htmlspecialchars() or similar.
4156 * @since 1.19
4157 * @return string
4159 public function getHtmlCode() {
4160 if ( is_null( $this->mHtmlCode ) ) {
4161 $this->mHtmlCode = wfBCP47( $this->getCode() );
4163 return $this->mHtmlCode;
4167 * @param string $code
4169 public function setCode( $code ) {
4170 $this->mCode = $code;
4171 // Ensure we don't leave incorrect cached data lying around
4172 $this->mHtmlCode = null;
4173 $this->mParentLanguage = false;
4177 * Get the name of a file for a certain language code
4178 * @param string $prefix Prepend this to the filename
4179 * @param string $code Language code
4180 * @param string $suffix Append this to the filename
4181 * @throws MWException
4182 * @return string $prefix . $mangledCode . $suffix
4184 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4185 if ( !self::isValidBuiltInCode( $code ) ) {
4186 throw new MWException( "Invalid language code \"$code\"" );
4189 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4193 * Get the language code from a file name. Inverse of getFileName()
4194 * @param string $filename $prefix . $languageCode . $suffix
4195 * @param string $prefix Prefix before the language code
4196 * @param string $suffix Suffix after the language code
4197 * @return string Language code, or false if $prefix or $suffix isn't found
4199 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4200 $m = null;
4201 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4202 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4203 if ( !count( $m ) ) {
4204 return false;
4206 return str_replace( '_', '-', strtolower( $m[1] ) );
4210 * @param string $code
4211 * @return string
4213 public static function getMessagesFileName( $code ) {
4214 global $IP;
4215 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4216 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4217 return $file;
4221 * @param string $code
4222 * @return string
4223 * @since 1.23
4225 public static function getJsonMessagesFileName( $code ) {
4226 global $IP;
4228 if ( !self::isValidBuiltInCode( $code ) ) {
4229 throw new MWException( "Invalid language code \"$code\"" );
4232 return "$IP/languages/i18n/$code.json";
4236 * @param string $code
4237 * @return string
4239 public static function getClassFileName( $code ) {
4240 global $IP;
4241 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4245 * Get the first fallback for a given language.
4247 * @param string $code
4249 * @return bool|string
4251 public static function getFallbackFor( $code ) {
4252 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4253 return false;
4254 } else {
4255 $fallbacks = self::getFallbacksFor( $code );
4256 $first = array_shift( $fallbacks );
4257 return $first;
4262 * Get the ordered list of fallback languages.
4264 * @since 1.19
4265 * @param string $code Language code
4266 * @return array
4268 public static function getFallbacksFor( $code ) {
4269 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4270 return array();
4271 } else {
4272 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4273 $v = array_map( 'trim', explode( ',', $v ) );
4274 if ( $v[count( $v ) - 1] !== 'en' ) {
4275 $v[] = 'en';
4277 return $v;
4282 * Get the ordered list of fallback languages, ending with the fallback
4283 * language chain for the site language.
4285 * @since 1.22
4286 * @param string $code Language code
4287 * @return array array( fallbacks, site fallbacks )
4289 public static function getFallbacksIncludingSiteLanguage( $code ) {
4290 global $wgLanguageCode;
4292 // Usually, we will only store a tiny number of fallback chains, so we
4293 // keep them in static memory.
4294 $cacheKey = "{$code}-{$wgLanguageCode}";
4296 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4297 $fallbacks = self::getFallbacksFor( $code );
4299 // Append the site's fallback chain, including the site language itself
4300 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4301 array_unshift( $siteFallbacks, $wgLanguageCode );
4303 // Eliminate any languages already included in the chain
4304 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4306 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4308 return self::$fallbackLanguageCache[$cacheKey];
4312 * Get all messages for a given language
4313 * WARNING: this may take a long time. If you just need all message *keys*
4314 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4316 * @param string $code
4318 * @return array
4320 public static function getMessagesFor( $code ) {
4321 return self::getLocalisationCache()->getItem( $code, 'messages' );
4325 * Get a message for a given language
4327 * @param string $key
4328 * @param string $code
4330 * @return string
4332 public static function getMessageFor( $key, $code ) {
4333 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4337 * Get all message keys for a given language. This is a faster alternative to
4338 * array_keys( Language::getMessagesFor( $code ) )
4340 * @since 1.19
4341 * @param string $code Language code
4342 * @return array of message keys (strings)
4344 public static function getMessageKeysFor( $code ) {
4345 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4349 * @param string $talk
4350 * @return mixed
4352 function fixVariableInNamespace( $talk ) {
4353 if ( strpos( $talk, '$1' ) === false ) {
4354 return $talk;
4357 global $wgMetaNamespace;
4358 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4360 # Allow grammar transformations
4361 # Allowing full message-style parsing would make simple requests
4362 # such as action=raw much more expensive than they need to be.
4363 # This will hopefully cover most cases.
4364 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4365 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4366 return str_replace( ' ', '_', $talk );
4370 * @param string $m
4371 * @return string
4373 function replaceGrammarInNamespace( $m ) {
4374 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4378 * @throws MWException
4379 * @return array
4381 static function getCaseMaps() {
4382 static $wikiUpperChars, $wikiLowerChars;
4383 if ( isset( $wikiUpperChars ) ) {
4384 return array( $wikiUpperChars, $wikiLowerChars );
4387 wfProfileIn( __METHOD__ );
4388 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4389 if ( $arr === false ) {
4390 throw new MWException(
4391 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4393 $wikiUpperChars = $arr['wikiUpperChars'];
4394 $wikiLowerChars = $arr['wikiLowerChars'];
4395 wfProfileOut( __METHOD__ );
4396 return array( $wikiUpperChars, $wikiLowerChars );
4400 * Decode an expiry (block, protection, etc) which has come from the DB
4402 * @todo FIXME: why are we returnings DBMS-dependent strings???
4404 * @param string $expiry Database expiry String
4405 * @param bool|int $format True to process using language functions, or TS_ constant
4406 * to return the expiry in a given timestamp
4407 * @return string
4408 * @since 1.18
4410 public function formatExpiry( $expiry, $format = true ) {
4411 static $infinity;
4412 if ( $infinity === null ) {
4413 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4416 if ( $expiry == '' || $expiry == $infinity ) {
4417 return $format === true
4418 ? $this->getMessageFromDB( 'infiniteblock' )
4419 : $infinity;
4420 } else {
4421 return $format === true
4422 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4423 : wfTimestamp( $format, $expiry );
4428 * @todo Document
4429 * @param int|float $seconds
4430 * @param array $format Optional
4431 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4432 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4433 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4434 * and friends.
4435 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4436 * or 'avoidminutes'.
4437 * @return string
4439 function formatTimePeriod( $seconds, $format = array() ) {
4440 if ( !is_array( $format ) ) {
4441 $format = array( 'avoid' => $format ); // For backwards compatibility
4443 if ( !isset( $format['avoid'] ) ) {
4444 $format['avoid'] = false;
4446 if ( !isset( $format['noabbrevs' ] ) ) {
4447 $format['noabbrevs'] = false;
4449 $secondsMsg = wfMessage(
4450 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4451 $minutesMsg = wfMessage(
4452 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4453 $hoursMsg = wfMessage(
4454 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4455 $daysMsg = wfMessage(
4456 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4458 if ( round( $seconds * 10 ) < 100 ) {
4459 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4460 $s = $secondsMsg->params( $s )->text();
4461 } elseif ( round( $seconds ) < 60 ) {
4462 $s = $this->formatNum( round( $seconds ) );
4463 $s = $secondsMsg->params( $s )->text();
4464 } elseif ( round( $seconds ) < 3600 ) {
4465 $minutes = floor( $seconds / 60 );
4466 $secondsPart = round( fmod( $seconds, 60 ) );
4467 if ( $secondsPart == 60 ) {
4468 $secondsPart = 0;
4469 $minutes++;
4471 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4472 $s .= ' ';
4473 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4474 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4475 $hours = floor( $seconds / 3600 );
4476 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4477 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4478 if ( $secondsPart == 60 ) {
4479 $secondsPart = 0;
4480 $minutes++;
4482 if ( $minutes == 60 ) {
4483 $minutes = 0;
4484 $hours++;
4486 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4487 $s .= ' ';
4488 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4489 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4490 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4492 } else {
4493 $days = floor( $seconds / 86400 );
4494 if ( $format['avoid'] === 'avoidminutes' ) {
4495 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4496 if ( $hours == 24 ) {
4497 $hours = 0;
4498 $days++;
4500 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4501 $s .= ' ';
4502 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4503 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4504 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4505 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4506 if ( $minutes == 60 ) {
4507 $minutes = 0;
4508 $hours++;
4510 if ( $hours == 24 ) {
4511 $hours = 0;
4512 $days++;
4514 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4515 $s .= ' ';
4516 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4517 $s .= ' ';
4518 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4519 } else {
4520 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4521 $s .= ' ';
4522 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4525 return $s;
4529 * Format a bitrate for output, using an appropriate
4530 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4531 * the magnitude in question.
4533 * This use base 1000. For base 1024 use formatSize(), for another base
4534 * see formatComputingNumbers().
4536 * @param int $bps
4537 * @return string
4539 function formatBitrate( $bps ) {
4540 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4544 * @param int $size Size of the unit
4545 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4546 * @param string $messageKey Message key to be uesd
4547 * @return string
4549 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4550 if ( $size <= 0 ) {
4551 return str_replace( '$1', $this->formatNum( $size ),
4552 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4555 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4556 $index = 0;
4558 $maxIndex = count( $sizes ) - 1;
4559 while ( $size >= $boundary && $index < $maxIndex ) {
4560 $index++;
4561 $size /= $boundary;
4564 // For small sizes no decimal places necessary
4565 $round = 0;
4566 if ( $index > 1 ) {
4567 // For MB and bigger two decimal places are smarter
4568 $round = 2;
4570 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4572 $size = round( $size, $round );
4573 $text = $this->getMessageFromDB( $msg );
4574 return str_replace( '$1', $this->formatNum( $size ), $text );
4578 * Format a size in bytes for output, using an appropriate
4579 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4581 * This method use base 1024. For base 1000 use formatBitrate(), for
4582 * another base see formatComputingNumbers()
4584 * @param int $size Size to format
4585 * @return string Plain text (not HTML)
4587 function formatSize( $size ) {
4588 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4592 * Make a list item, used by various special pages
4594 * @param string $page Page link
4595 * @param string $details Text between brackets
4596 * @param bool $oppositedm Add the direction mark opposite to your
4597 * language, to display text properly
4598 * @return string
4600 function specialList( $page, $details, $oppositedm = true ) {
4601 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4602 $this->getDirMark();
4603 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4604 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4605 return $page . $details;
4609 * Generate (prev x| next x) (20|50|100...) type links for paging
4611 * @param Title $title Title object to link
4612 * @param int $offset
4613 * @param int $limit
4614 * @param array|string $query Optional URL query parameter string
4615 * @param bool $atend Optional param for specified if this is the last page
4616 * @return string
4618 public function viewPrevNext( Title $title, $offset, $limit,
4619 array $query = array(), $atend = false
4621 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4623 # Make 'previous' link
4624 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4625 if ( $offset > 0 ) {
4626 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4627 $query, $prev, 'prevn-title', 'mw-prevlink' );
4628 } else {
4629 $plink = htmlspecialchars( $prev );
4632 # Make 'next' link
4633 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4634 if ( $atend ) {
4635 $nlink = htmlspecialchars( $next );
4636 } else {
4637 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4638 $query, $next, 'nextn-title', 'mw-nextlink' );
4641 # Make links to set number of items per page
4642 $numLinks = array();
4643 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4644 $numLinks[] = $this->numLink( $title, $offset, $num,
4645 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4648 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4649 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4653 * Helper function for viewPrevNext() that generates links
4655 * @param Title $title Title object to link
4656 * @param int $offset
4657 * @param int $limit
4658 * @param array $query Extra query parameters
4659 * @param string $link Text to use for the link; will be escaped
4660 * @param string $tooltipMsg Name of the message to use as tooltip
4661 * @param string $class Value of the "class" attribute of the link
4662 * @return string HTML fragment
4664 private function numLink( Title $title, $offset, $limit, array $query, $link,
4665 $tooltipMsg, $class
4667 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4668 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4669 ->numParams( $limit )->text();
4671 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4672 'title' => $tooltip, 'class' => $class ), $link );
4676 * Get the conversion rule title, if any.
4678 * @return string
4680 public function getConvRuleTitle() {
4681 return $this->mConverter->getConvRuleTitle();
4685 * Get the compiled plural rules for the language
4686 * @since 1.20
4687 * @return array Associative array with plural form, and plural rule as key-value pairs
4689 public function getCompiledPluralRules() {
4690 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4691 $fallbacks = Language::getFallbacksFor( $this->mCode );
4692 if ( !$pluralRules ) {
4693 foreach ( $fallbacks as $fallbackCode ) {
4694 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4695 if ( $pluralRules ) {
4696 break;
4700 return $pluralRules;
4704 * Get the plural rules for the language
4705 * @since 1.20
4706 * @return array Associative array with plural form number and plural rule as key-value pairs
4708 public function getPluralRules() {
4709 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4710 $fallbacks = Language::getFallbacksFor( $this->mCode );
4711 if ( !$pluralRules ) {
4712 foreach ( $fallbacks as $fallbackCode ) {
4713 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4714 if ( $pluralRules ) {
4715 break;
4719 return $pluralRules;
4723 * Get the plural rule types for the language
4724 * @since 1.22
4725 * @return array Associative array with plural form number and plural rule type as key-value pairs
4727 public function getPluralRuleTypes() {
4728 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4729 $fallbacks = Language::getFallbacksFor( $this->mCode );
4730 if ( !$pluralRuleTypes ) {
4731 foreach ( $fallbacks as $fallbackCode ) {
4732 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4733 if ( $pluralRuleTypes ) {
4734 break;
4738 return $pluralRuleTypes;
4742 * Find the index number of the plural rule appropriate for the given number
4743 * @return int The index number of the plural rule
4745 public function getPluralRuleIndexNumber( $number ) {
4746 $pluralRules = $this->getCompiledPluralRules();
4747 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4748 return $form;
4752 * Find the plural rule type appropriate for the given number
4753 * For example, if the language is set to Arabic, getPluralType(5) should
4754 * return 'few'.
4755 * @since 1.22
4756 * @return string The name of the plural rule type, e.g. one, two, few, many
4758 public function getPluralRuleType( $number ) {
4759 $index = $this->getPluralRuleIndexNumber( $number );
4760 $pluralRuleTypes = $this->getPluralRuleTypes();
4761 if ( isset( $pluralRuleTypes[$index] ) ) {
4762 return $pluralRuleTypes[$index];
4763 } else {
4764 return 'other';