Merge "UploadFromUrlTest: Don't reference skins/common/ (via bits.wm.o)"
[mediawiki.git] / languages / Language.php
blob2bc4554e5dc711050ffb787d6e5d645fa82d2d5f
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 $tag
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()
1029 * @param DateTime|bool|null &$dateTimeObj
1030 * @param string $ts
1031 * @param DateTimeZone|bool|null $zone
1032 * @param string $code
1033 * @return string
1035 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1036 if ( !$dateTimeObj ) {
1037 $dateTimeObj = DateTime::createFromFormat(
1038 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1041 return $dateTimeObj->format( $code );
1045 * This is a workalike of PHP's date() function, but with better
1046 * internationalisation, a reduced set of format characters, and a better
1047 * escaping format.
1049 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1050 * the PHP manual for definitions. There are a number of extensions, which
1051 * start with "x":
1053 * xn Do not translate digits of the next numeric format character
1054 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1055 * xr Use roman numerals for the next numeric format character
1056 * xh Use hebrew numerals for the next numeric format character
1057 * xx Literal x
1058 * xg Genitive month name
1060 * xij j (day number) in Iranian calendar
1061 * xiF F (month name) in Iranian calendar
1062 * xin n (month number) in Iranian calendar
1063 * xiy y (two digit year) in Iranian calendar
1064 * xiY Y (full year) in Iranian calendar
1066 * xjj j (day number) in Hebrew calendar
1067 * xjF F (month name) in Hebrew calendar
1068 * xjt t (days in month) in Hebrew calendar
1069 * xjx xg (genitive month name) in Hebrew calendar
1070 * xjn n (month number) in Hebrew calendar
1071 * xjY Y (full year) in Hebrew calendar
1073 * xmj j (day number) in Hijri calendar
1074 * xmF F (month name) in Hijri calendar
1075 * xmn n (month number) in Hijri calendar
1076 * xmY Y (full year) in Hijri calendar
1078 * xkY Y (full year) in Thai solar calendar. Months and days are
1079 * identical to the Gregorian calendar
1080 * xoY Y (full year) in Minguo calendar or Juche year.
1081 * Months and days are identical to the
1082 * Gregorian calendar
1083 * xtY Y (full year) in Japanese nengo. Months and days are
1084 * identical to the Gregorian calendar
1086 * Characters enclosed in double quotes will be considered literal (with
1087 * the quotes themselves removed). Unmatched quotes will be considered
1088 * literal quotes. Example:
1090 * "The month is" F => The month is January
1091 * i's" => 20'11"
1093 * Backslash escaping is also supported.
1095 * Input timestamp is assumed to be pre-normalized to the desired local
1096 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1097 * $ts is UTC if $zone is not given.
1099 * @param string $format
1100 * @param string $ts 14-character timestamp
1101 * YYYYMMDDHHMMSS
1102 * 01234567890123
1103 * @param DateTimeZone $zone Timezone of $ts
1104 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1105 * Only makes sense if $ts is the current time.
1106 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1108 * @throws MWException
1109 * @return string
1111 function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = null ) {
1112 $s = '';
1113 $raw = false;
1114 $roman = false;
1115 $hebrewNum = false;
1116 $dateTimeObj = false;
1117 $rawToggle = false;
1118 $iranian = false;
1119 $hebrew = false;
1120 $hijri = false;
1121 $thai = false;
1122 $minguo = false;
1123 $tenno = false;
1125 $usedSecond = false;
1126 $usedMinute = false;
1127 $usedHour = false;
1128 $usedAMPM = false;
1129 $usedDay = false;
1130 $usedWeek = false;
1131 $usedMonth = false;
1132 $usedYear = false;
1133 $usedISOYear = false;
1134 $usedIsLeapYear = false;
1136 $usedHebrewMonth = false;
1137 $usedIranianMonth = false;
1138 $usedHijriMonth = false;
1139 $usedHebrewYear = false;
1140 $usedIranianYear = false;
1141 $usedHijriYear = false;
1142 $usedTennoYear = false;
1144 if ( strlen( $ts ) !== 14 ) {
1145 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1148 if ( !ctype_digit( $ts ) ) {
1149 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1152 $formatLength = strlen( $format );
1153 for ( $p = 0; $p < $formatLength; $p++ ) {
1154 $num = false;
1155 $code = $format[$p];
1156 if ( $code == 'x' && $p < $formatLength - 1 ) {
1157 $code .= $format[++$p];
1160 if ( ( $code === 'xi'
1161 || $code === 'xj'
1162 || $code === 'xk'
1163 || $code === 'xm'
1164 || $code === 'xo'
1165 || $code === 'xt' )
1166 && $p < $formatLength - 1 ) {
1167 $code .= $format[++$p];
1170 switch ( $code ) {
1171 case 'xx':
1172 $s .= 'x';
1173 break;
1174 case 'xn':
1175 $raw = true;
1176 break;
1177 case 'xN':
1178 $rawToggle = !$rawToggle;
1179 break;
1180 case 'xr':
1181 $roman = true;
1182 break;
1183 case 'xh':
1184 $hebrewNum = true;
1185 break;
1186 case 'xg':
1187 $usedMonth = true;
1188 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1189 break;
1190 case 'xjx':
1191 $usedHebrewMonth = true;
1192 if ( !$hebrew ) {
1193 $hebrew = self::tsToHebrew( $ts );
1195 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1196 break;
1197 case 'd':
1198 $usedDay = true;
1199 $num = substr( $ts, 6, 2 );
1200 break;
1201 case 'D':
1202 $usedDay = true;
1203 $s .= $this->getWeekdayAbbreviation( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1204 break;
1205 case 'j':
1206 $usedDay = true;
1207 $num = intval( substr( $ts, 6, 2 ) );
1208 break;
1209 case 'xij':
1210 $usedDay = true;
1211 if ( !$iranian ) {
1212 $iranian = self::tsToIranian( $ts );
1214 $num = $iranian[2];
1215 break;
1216 case 'xmj':
1217 $usedDay = true;
1218 if ( !$hijri ) {
1219 $hijri = self::tsToHijri( $ts );
1221 $num = $hijri[2];
1222 break;
1223 case 'xjj':
1224 $usedDay = true;
1225 if ( !$hebrew ) {
1226 $hebrew = self::tsToHebrew( $ts );
1228 $num = $hebrew[2];
1229 break;
1230 case 'l':
1231 $usedDay = true;
1232 $s .= $this->getWeekdayName( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 );
1233 break;
1234 case 'F':
1235 $usedMonth = true;
1236 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1237 break;
1238 case 'xiF':
1239 $usedIranianMonth = true;
1240 if ( !$iranian ) {
1241 $iranian = self::tsToIranian( $ts );
1243 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1244 break;
1245 case 'xmF':
1246 $usedHijriMonth = true;
1247 if ( !$hijri ) {
1248 $hijri = self::tsToHijri( $ts );
1250 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1251 break;
1252 case 'xjF':
1253 $usedHebrewMonth = true;
1254 if ( !$hebrew ) {
1255 $hebrew = self::tsToHebrew( $ts );
1257 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1258 break;
1259 case 'm':
1260 $usedMonth = true;
1261 $num = substr( $ts, 4, 2 );
1262 break;
1263 case 'M':
1264 $usedMonth = true;
1265 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1266 break;
1267 case 'n':
1268 $usedMonth = true;
1269 $num = intval( substr( $ts, 4, 2 ) );
1270 break;
1271 case 'xin':
1272 $usedIranianMonth = true;
1273 if ( !$iranian ) {
1274 $iranian = self::tsToIranian( $ts );
1276 $num = $iranian[1];
1277 break;
1278 case 'xmn':
1279 $usedHijriMonth = true;
1280 if ( !$hijri ) {
1281 $hijri = self::tsToHijri ( $ts );
1283 $num = $hijri[1];
1284 break;
1285 case 'xjn':
1286 $usedHebrewMonth = true;
1287 if ( !$hebrew ) {
1288 $hebrew = self::tsToHebrew( $ts );
1290 $num = $hebrew[1];
1291 break;
1292 case 'xjt':
1293 $usedHebrewMonth = true;
1294 if ( !$hebrew ) {
1295 $hebrew = self::tsToHebrew( $ts );
1297 $num = $hebrew[3];
1298 break;
1299 case 'Y':
1300 $usedYear = true;
1301 $num = substr( $ts, 0, 4 );
1302 break;
1303 case 'xiY':
1304 $usedIranianYear = true;
1305 if ( !$iranian ) {
1306 $iranian = self::tsToIranian( $ts );
1308 $num = $iranian[0];
1309 break;
1310 case 'xmY':
1311 $usedHijriYear = true;
1312 if ( !$hijri ) {
1313 $hijri = self::tsToHijri( $ts );
1315 $num = $hijri[0];
1316 break;
1317 case 'xjY':
1318 $usedHebrewYear = true;
1319 if ( !$hebrew ) {
1320 $hebrew = self::tsToHebrew( $ts );
1322 $num = $hebrew[0];
1323 break;
1324 case 'xkY':
1325 $usedYear = true;
1326 if ( !$thai ) {
1327 $thai = self::tsToYear( $ts, 'thai' );
1329 $num = $thai[0];
1330 break;
1331 case 'xoY':
1332 $usedYear = true;
1333 if ( !$minguo ) {
1334 $minguo = self::tsToYear( $ts, 'minguo' );
1336 $num = $minguo[0];
1337 break;
1338 case 'xtY':
1339 $usedTennoYear = true;
1340 if ( !$tenno ) {
1341 $tenno = self::tsToYear( $ts, 'tenno' );
1343 $num = $tenno[0];
1344 break;
1345 case 'y':
1346 $usedYear = true;
1347 $num = substr( $ts, 2, 2 );
1348 break;
1349 case 'xiy':
1350 $usedIranianYear = true;
1351 if ( !$iranian ) {
1352 $iranian = self::tsToIranian( $ts );
1354 $num = substr( $iranian[0], -2 );
1355 break;
1356 case 'a':
1357 $usedAMPM = true;
1358 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1359 break;
1360 case 'A':
1361 $usedAMPM = true;
1362 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1363 break;
1364 case 'g':
1365 $usedHour = true;
1366 $h = substr( $ts, 8, 2 );
1367 $num = $h % 12 ? $h % 12 : 12;
1368 break;
1369 case 'G':
1370 $usedHour = true;
1371 $num = intval( substr( $ts, 8, 2 ) );
1372 break;
1373 case 'h':
1374 $usedHour = true;
1375 $h = substr( $ts, 8, 2 );
1376 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1377 break;
1378 case 'H':
1379 $usedHour = true;
1380 $num = substr( $ts, 8, 2 );
1381 break;
1382 case 'i':
1383 $usedMinute = true;
1384 $num = substr( $ts, 10, 2 );
1385 break;
1386 case 's':
1387 $usedSecond = true;
1388 $num = substr( $ts, 12, 2 );
1389 break;
1390 case 'c':
1391 case 'r':
1392 $usedSecond = true;
1393 // fall through
1394 case 'e':
1395 case 'O':
1396 case 'P':
1397 case 'T':
1398 $s .= Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1399 break;
1400 case 'w':
1401 case 'N':
1402 case 'z':
1403 $usedDay = true;
1404 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1405 break;
1406 case 'W':
1407 $usedWeek = true;
1408 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1409 break;
1410 case 't':
1411 $usedMonth = true;
1412 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1413 break;
1414 case 'L':
1415 $usedIsLeapYear = true;
1416 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1417 break;
1418 case 'o':
1419 $usedISOYear = true;
1420 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1421 break;
1422 case 'U':
1423 $usedSecond = true;
1424 // fall through
1425 case 'I':
1426 case 'Z':
1427 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1428 break;
1429 case '\\':
1430 # Backslash escaping
1431 if ( $p < $formatLength - 1 ) {
1432 $s .= $format[++$p];
1433 } else {
1434 $s .= '\\';
1436 break;
1437 case '"':
1438 # Quoted literal
1439 if ( $p < $formatLength - 1 ) {
1440 $endQuote = strpos( $format, '"', $p + 1 );
1441 if ( $endQuote === false ) {
1442 # No terminating quote, assume literal "
1443 $s .= '"';
1444 } else {
1445 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1446 $p = $endQuote;
1448 } else {
1449 # Quote at end of string, assume literal "
1450 $s .= '"';
1452 break;
1453 default:
1454 $s .= $format[$p];
1456 if ( $num !== false ) {
1457 if ( $rawToggle || $raw ) {
1458 $s .= $num;
1459 $raw = false;
1460 } elseif ( $roman ) {
1461 $s .= Language::romanNumeral( $num );
1462 $roman = false;
1463 } elseif ( $hebrewNum ) {
1464 $s .= self::hebrewNumeral( $num );
1465 $hebrewNum = false;
1466 } else {
1467 $s .= $this->formatNum( $num, true );
1472 if ( $usedSecond ) {
1473 $ttl = 1;
1474 } elseif ( $usedMinute ) {
1475 $ttl = 60 - substr( $ts, 12, 2 );
1476 } elseif ( $usedHour ) {
1477 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1478 } elseif ( $usedAMPM ) {
1479 $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1480 } elseif ( $usedDay || $usedHebrewMonth || $usedIranianMonth || $usedHijriMonth || $usedHebrewYear || $usedIranianYear || $usedHijriYear || $usedTennoYear ) {
1481 // @todo Someone who understands the non-Gregorian calendars should write proper logic for them
1482 // so that they don't need purged every day.
1483 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1484 } else {
1485 $possibleTtls = array();
1486 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1487 if ( $usedWeek ) {
1488 $possibleTtls[] = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1489 } elseif ( $usedISOYear ) {
1490 // December 28th falls on the last ISO week of the year, every year.
1491 // The last ISO week of a year can be 52 or 53.
1492 $lastWeekOfISOYear = DateTime::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?: new DateTimeZone( 'UTC' ) )->format( 'W' );
1493 $currentISOWeek = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1494 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1495 $timeRemainingInWeek = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay;
1496 $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1499 if ( $usedMonth ) {
1500 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 + $timeRemainingInDay;
1501 } elseif ( $usedYear ) {
1502 $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1503 + $timeRemainingInDay;
1504 } elseif ( $usedIsLeapYear ) {
1505 $year = substr( $ts, 0, 4 );
1506 $timeRemainingInYear = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1507 + $timeRemainingInDay;
1508 $mod = $year % 4;
1509 if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1510 // this isn't a leap year. see when the next one starts
1511 $nextCandidate = $year - $mod + 4;
1512 if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1513 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 + $timeRemainingInYear;
1514 } else {
1515 $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 + $timeRemainingInYear;
1517 } else {
1518 // this is a leap year, so the next year isn't
1519 $possibleTtls[] = $timeRemainingInYear;
1523 if ( $possibleTtls ) {
1524 $ttl = min( $possibleTtls );
1528 return $s;
1531 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1532 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1535 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1536 * Gregorian dates to Iranian dates. Originally written in C, it
1537 * is released under the terms of GNU Lesser General Public
1538 * License. Conversion to PHP was performed by Niklas Laxström.
1540 * Link: http://www.farsiweb.info/jalali/jalali.c
1542 * @param string $ts
1544 * @return string
1546 private static function tsToIranian( $ts ) {
1547 $gy = substr( $ts, 0, 4 ) -1600;
1548 $gm = substr( $ts, 4, 2 ) -1;
1549 $gd = substr( $ts, 6, 2 ) -1;
1551 # Days passed from the beginning (including leap years)
1552 $gDayNo = 365 * $gy
1553 + floor( ( $gy + 3 ) / 4 )
1554 - floor( ( $gy + 99 ) / 100 )
1555 + floor( ( $gy + 399 ) / 400 );
1557 // Add days of the past months of this year
1558 for ( $i = 0; $i < $gm; $i++ ) {
1559 $gDayNo += self::$GREG_DAYS[$i];
1562 // Leap years
1563 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1564 $gDayNo++;
1567 // Days passed in current month
1568 $gDayNo += (int)$gd;
1570 $jDayNo = $gDayNo - 79;
1572 $jNp = floor( $jDayNo / 12053 );
1573 $jDayNo %= 12053;
1575 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1576 $jDayNo %= 1461;
1578 if ( $jDayNo >= 366 ) {
1579 $jy += floor( ( $jDayNo - 1 ) / 365 );
1580 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1583 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1584 $jDayNo -= self::$IRANIAN_DAYS[$i];
1587 $jm = $i + 1;
1588 $jd = $jDayNo + 1;
1590 return array( $jy, $jm, $jd );
1594 * Converting Gregorian dates to Hijri dates.
1596 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1598 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1600 * @param string $ts
1602 * @return string
1604 private static function tsToHijri( $ts ) {
1605 $year = substr( $ts, 0, 4 );
1606 $month = substr( $ts, 4, 2 );
1607 $day = substr( $ts, 6, 2 );
1609 $zyr = $year;
1610 $zd = $day;
1611 $zm = $month;
1612 $zy = $zyr;
1614 if (
1615 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1616 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1618 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1619 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1620 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1621 $zd - 32075;
1622 } else {
1623 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1624 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1627 $zl = $zjd -1948440 + 10632;
1628 $zn = (int)( ( $zl - 1 ) / 10631 );
1629 $zl = $zl - 10631 * $zn + 354;
1630 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1631 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1632 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1633 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1634 $zm = (int)( ( 24 * $zl ) / 709 );
1635 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1636 $zy = 30 * $zn + $zj - 30;
1638 return array( $zy, $zm, $zd );
1642 * Converting Gregorian dates to Hebrew dates.
1644 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1645 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1646 * to translate the relevant functions into PHP and release them under
1647 * GNU GPL.
1649 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1650 * and Adar II is 14. In a non-leap year, Adar is 6.
1652 * @param string $ts
1654 * @return string
1656 private static function tsToHebrew( $ts ) {
1657 # Parse date
1658 $year = substr( $ts, 0, 4 );
1659 $month = substr( $ts, 4, 2 );
1660 $day = substr( $ts, 6, 2 );
1662 # Calculate Hebrew year
1663 $hebrewYear = $year + 3760;
1665 # Month number when September = 1, August = 12
1666 $month += 4;
1667 if ( $month > 12 ) {
1668 # Next year
1669 $month -= 12;
1670 $year++;
1671 $hebrewYear++;
1674 # Calculate day of year from 1 September
1675 $dayOfYear = $day;
1676 for ( $i = 1; $i < $month; $i++ ) {
1677 if ( $i == 6 ) {
1678 # February
1679 $dayOfYear += 28;
1680 # Check if the year is leap
1681 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1682 $dayOfYear++;
1684 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1685 $dayOfYear += 30;
1686 } else {
1687 $dayOfYear += 31;
1691 # Calculate the start of the Hebrew year
1692 $start = self::hebrewYearStart( $hebrewYear );
1694 # Calculate next year's start
1695 if ( $dayOfYear <= $start ) {
1696 # Day is before the start of the year - it is the previous year
1697 # Next year's start
1698 $nextStart = $start;
1699 # Previous year
1700 $year--;
1701 $hebrewYear--;
1702 # Add days since previous year's 1 September
1703 $dayOfYear += 365;
1704 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1705 # Leap year
1706 $dayOfYear++;
1708 # Start of the new (previous) year
1709 $start = self::hebrewYearStart( $hebrewYear );
1710 } else {
1711 # Next year's start
1712 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1715 # Calculate Hebrew day of year
1716 $hebrewDayOfYear = $dayOfYear - $start;
1718 # Difference between year's days
1719 $diff = $nextStart - $start;
1720 # Add 12 (or 13 for leap years) days to ignore the difference between
1721 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1722 # difference is only about the year type
1723 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1724 $diff += 13;
1725 } else {
1726 $diff += 12;
1729 # Check the year pattern, and is leap year
1730 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1731 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1732 # and non-leap years
1733 $yearPattern = $diff % 30;
1734 # Check if leap year
1735 $isLeap = $diff >= 30;
1737 # Calculate day in the month from number of day in the Hebrew year
1738 # Don't check Adar - if the day is not in Adar, we will stop before;
1739 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1740 $hebrewDay = $hebrewDayOfYear;
1741 $hebrewMonth = 1;
1742 $days = 0;
1743 while ( $hebrewMonth <= 12 ) {
1744 # Calculate days in this month
1745 if ( $isLeap && $hebrewMonth == 6 ) {
1746 # Adar in a leap year
1747 if ( $isLeap ) {
1748 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1749 $days = 30;
1750 if ( $hebrewDay <= $days ) {
1751 # Day in Adar I
1752 $hebrewMonth = 13;
1753 } else {
1754 # Subtract the days of Adar I
1755 $hebrewDay -= $days;
1756 # Try Adar II
1757 $days = 29;
1758 if ( $hebrewDay <= $days ) {
1759 # Day in Adar II
1760 $hebrewMonth = 14;
1764 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1765 # Cheshvan in a complete year (otherwise as the rule below)
1766 $days = 30;
1767 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1768 # Kislev in an incomplete year (otherwise as the rule below)
1769 $days = 29;
1770 } else {
1771 # Odd months have 30 days, even have 29
1772 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1774 if ( $hebrewDay <= $days ) {
1775 # In the current month
1776 break;
1777 } else {
1778 # Subtract the days of the current month
1779 $hebrewDay -= $days;
1780 # Try in the next month
1781 $hebrewMonth++;
1785 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1789 * This calculates the Hebrew year start, as days since 1 September.
1790 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1791 * Used for Hebrew date.
1793 * @param int $year
1795 * @return string
1797 private static function hebrewYearStart( $year ) {
1798 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1799 $b = intval( ( $year - 1 ) % 4 );
1800 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1801 if ( $m < 0 ) {
1802 $m--;
1804 $Mar = intval( $m );
1805 if ( $m < 0 ) {
1806 $m++;
1808 $m -= $Mar;
1810 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1811 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1812 $Mar++;
1813 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1814 $Mar += 2;
1815 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1816 $Mar++;
1819 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1820 return $Mar;
1824 * Algorithm to convert Gregorian dates to Thai solar dates,
1825 * Minguo dates or Minguo dates.
1827 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1828 * http://en.wikipedia.org/wiki/Minguo_calendar
1829 * http://en.wikipedia.org/wiki/Japanese_era_name
1831 * @param string $ts 14-character timestamp
1832 * @param string $cName Calender name
1833 * @return array Converted year, month, day
1835 private static function tsToYear( $ts, $cName ) {
1836 $gy = substr( $ts, 0, 4 );
1837 $gm = substr( $ts, 4, 2 );
1838 $gd = substr( $ts, 6, 2 );
1840 if ( !strcmp( $cName, 'thai' ) ) {
1841 # Thai solar dates
1842 # Add 543 years to the Gregorian calendar
1843 # Months and days are identical
1844 $gy_offset = $gy + 543;
1845 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1846 # Minguo dates
1847 # Deduct 1911 years from the Gregorian calendar
1848 # Months and days are identical
1849 $gy_offset = $gy - 1911;
1850 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1851 # Nengō dates up to Meiji period
1852 # Deduct years from the Gregorian calendar
1853 # depending on the nengo periods
1854 # Months and days are identical
1855 if ( ( $gy < 1912 )
1856 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1857 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1859 # Meiji period
1860 $gy_gannen = $gy - 1868 + 1;
1861 $gy_offset = $gy_gannen;
1862 if ( $gy_gannen == 1 ) {
1863 $gy_offset = '元';
1865 $gy_offset = '明治' . $gy_offset;
1866 } elseif (
1867 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1868 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1869 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1870 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1871 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1873 # Taishō period
1874 $gy_gannen = $gy - 1912 + 1;
1875 $gy_offset = $gy_gannen;
1876 if ( $gy_gannen == 1 ) {
1877 $gy_offset = '元';
1879 $gy_offset = '大正' . $gy_offset;
1880 } elseif (
1881 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1882 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1883 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1885 # Shōwa period
1886 $gy_gannen = $gy - 1926 + 1;
1887 $gy_offset = $gy_gannen;
1888 if ( $gy_gannen == 1 ) {
1889 $gy_offset = '元';
1891 $gy_offset = '昭和' . $gy_offset;
1892 } else {
1893 # Heisei period
1894 $gy_gannen = $gy - 1989 + 1;
1895 $gy_offset = $gy_gannen;
1896 if ( $gy_gannen == 1 ) {
1897 $gy_offset = '元';
1899 $gy_offset = '平成' . $gy_offset;
1901 } else {
1902 $gy_offset = $gy;
1905 return array( $gy_offset, $gm, $gd );
1909 * Roman number formatting up to 10000
1911 * @param int $num
1913 * @return string
1915 static function romanNumeral( $num ) {
1916 static $table = array(
1917 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1918 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1919 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1920 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1921 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1924 $num = intval( $num );
1925 if ( $num > 10000 || $num <= 0 ) {
1926 return $num;
1929 $s = '';
1930 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1931 if ( $num >= $pow10 ) {
1932 $s .= $table[$i][(int)floor( $num / $pow10 )];
1934 $num = $num % $pow10;
1936 return $s;
1940 * Hebrew Gematria number formatting up to 9999
1942 * @param int $num
1944 * @return string
1946 static function hebrewNumeral( $num ) {
1947 static $table = array(
1948 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1949 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1950 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1951 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1954 $num = intval( $num );
1955 if ( $num > 9999 || $num <= 0 ) {
1956 return $num;
1959 $s = '';
1960 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1961 if ( $num >= $pow10 ) {
1962 if ( $num == 15 || $num == 16 ) {
1963 $s .= $table[0][9] . $table[0][$num - 9];
1964 $num = 0;
1965 } else {
1966 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1967 if ( $pow10 == 1000 ) {
1968 $s .= "'";
1972 $num = $num % $pow10;
1974 if ( strlen( $s ) == 2 ) {
1975 $str = $s . "'";
1976 } else {
1977 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1978 $str .= substr( $s, strlen( $s ) - 2, 2 );
1980 $start = substr( $str, 0, strlen( $str ) - 2 );
1981 $end = substr( $str, strlen( $str ) - 2 );
1982 switch ( $end ) {
1983 case 'כ':
1984 $str = $start . 'ך';
1985 break;
1986 case 'מ':
1987 $str = $start . 'ם';
1988 break;
1989 case 'נ':
1990 $str = $start . 'ן';
1991 break;
1992 case 'פ':
1993 $str = $start . 'ף';
1994 break;
1995 case 'צ':
1996 $str = $start . 'ץ';
1997 break;
1999 return $str;
2003 * Used by date() and time() to adjust the time output.
2005 * @param string $ts The time in date('YmdHis') format
2006 * @param mixed $tz Adjust the time by this amount (default false, mean we
2007 * get user timecorrection setting)
2008 * @return int
2010 function userAdjust( $ts, $tz = false ) {
2011 global $wgUser, $wgLocalTZoffset;
2013 if ( $tz === false ) {
2014 $tz = $wgUser->getOption( 'timecorrection' );
2017 $data = explode( '|', $tz, 3 );
2019 if ( $data[0] == 'ZoneInfo' ) {
2020 wfSuppressWarnings();
2021 $userTZ = timezone_open( $data[2] );
2022 wfRestoreWarnings();
2023 if ( $userTZ !== false ) {
2024 $date = date_create( $ts, timezone_open( 'UTC' ) );
2025 date_timezone_set( $date, $userTZ );
2026 $date = date_format( $date, 'YmdHis' );
2027 return $date;
2029 # Unrecognized timezone, default to 'Offset' with the stored offset.
2030 $data[0] = 'Offset';
2033 if ( $data[0] == 'System' || $tz == '' ) {
2034 # Global offset in minutes.
2035 $minDiff = $wgLocalTZoffset;
2036 } elseif ( $data[0] == 'Offset' ) {
2037 $minDiff = intval( $data[1] );
2038 } else {
2039 $data = explode( ':', $tz );
2040 if ( count( $data ) == 2 ) {
2041 $data[0] = intval( $data[0] );
2042 $data[1] = intval( $data[1] );
2043 $minDiff = abs( $data[0] ) * 60 + $data[1];
2044 if ( $data[0] < 0 ) {
2045 $minDiff = -$minDiff;
2047 } else {
2048 $minDiff = intval( $data[0] ) * 60;
2052 # No difference ? Return time unchanged
2053 if ( 0 == $minDiff ) {
2054 return $ts;
2057 wfSuppressWarnings(); // E_STRICT system time bitching
2058 # Generate an adjusted date; take advantage of the fact that mktime
2059 # will normalize out-of-range values so we don't have to split $minDiff
2060 # into hours and minutes.
2061 $t = mktime( (
2062 (int)substr( $ts, 8, 2 ) ), # Hours
2063 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2064 (int)substr( $ts, 12, 2 ), # Seconds
2065 (int)substr( $ts, 4, 2 ), # Month
2066 (int)substr( $ts, 6, 2 ), # Day
2067 (int)substr( $ts, 0, 4 ) ); # Year
2069 $date = date( 'YmdHis', $t );
2070 wfRestoreWarnings();
2072 return $date;
2076 * This is meant to be used by time(), date(), and timeanddate() to get
2077 * the date preference they're supposed to use, it should be used in
2078 * all children.
2080 *<code>
2081 * function timeanddate([...], $format = true) {
2082 * $datePreference = $this->dateFormat($format);
2083 * [...]
2085 *</code>
2087 * @param int|string|bool $usePrefs If true, the user's preference is used
2088 * if false, the site/language default is used
2089 * if int/string, assumed to be a format.
2090 * @return string
2092 function dateFormat( $usePrefs = true ) {
2093 global $wgUser;
2095 if ( is_bool( $usePrefs ) ) {
2096 if ( $usePrefs ) {
2097 $datePreference = $wgUser->getDatePreference();
2098 } else {
2099 $datePreference = (string)User::getDefaultOption( 'date' );
2101 } else {
2102 $datePreference = (string)$usePrefs;
2105 // return int
2106 if ( $datePreference == '' ) {
2107 return 'default';
2110 return $datePreference;
2114 * Get a format string for a given type and preference
2115 * @param string $type May be date, time or both
2116 * @param string $pref The format name as it appears in Messages*.php
2118 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2120 * @return string
2122 function getDateFormatString( $type, $pref ) {
2123 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2124 if ( $pref == 'default' ) {
2125 $pref = $this->getDefaultDateFormat();
2126 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2127 } else {
2128 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2130 if ( $type === 'pretty' && $df === null ) {
2131 $df = $this->getDateFormatString( 'date', $pref );
2134 if ( $df === null ) {
2135 $pref = $this->getDefaultDateFormat();
2136 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2139 $this->dateFormatStrings[$type][$pref] = $df;
2141 return $this->dateFormatStrings[$type][$pref];
2145 * @param string $ts The time format which needs to be turned into a
2146 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2147 * @param bool $adj Whether to adjust the time output according to the
2148 * user configured offset ($timecorrection)
2149 * @param mixed $format True to use user's date format preference
2150 * @param string|bool $timecorrection The time offset as returned by
2151 * validateTimeZone() in Special:Preferences
2152 * @return string
2154 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2155 $ts = wfTimestamp( TS_MW, $ts );
2156 if ( $adj ) {
2157 $ts = $this->userAdjust( $ts, $timecorrection );
2159 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2160 return $this->sprintfDate( $df, $ts );
2164 * @param string $ts The time format which needs to be turned into a
2165 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2166 * @param bool $adj Whether to adjust the time output according to the
2167 * user configured offset ($timecorrection)
2168 * @param mixed $format True to use user's date format preference
2169 * @param string|bool $timecorrection The time offset as returned by
2170 * validateTimeZone() in Special:Preferences
2171 * @return string
2173 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2174 $ts = wfTimestamp( TS_MW, $ts );
2175 if ( $adj ) {
2176 $ts = $this->userAdjust( $ts, $timecorrection );
2178 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2179 return $this->sprintfDate( $df, $ts );
2183 * @param string $ts The time format which needs to be turned into a
2184 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2185 * @param bool $adj Whether to adjust the time output according to the
2186 * user configured offset ($timecorrection)
2187 * @param mixed $format What format to return, if it's false output the
2188 * default one (default true)
2189 * @param string|bool $timecorrection The time offset as returned by
2190 * validateTimeZone() in Special:Preferences
2191 * @return string
2193 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2194 $ts = wfTimestamp( TS_MW, $ts );
2195 if ( $adj ) {
2196 $ts = $this->userAdjust( $ts, $timecorrection );
2198 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2199 return $this->sprintfDate( $df, $ts );
2203 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2205 * @since 1.20
2207 * @param int $seconds The amount of seconds.
2208 * @param array $chosenIntervals The intervals to enable.
2210 * @return string
2212 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2213 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2215 $segments = array();
2217 foreach ( $intervals as $intervalName => $intervalValue ) {
2218 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2219 // duration-years, duration-decades, duration-centuries, duration-millennia
2220 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2221 $segments[] = $message->inLanguage( $this )->escaped();
2224 return $this->listToText( $segments );
2228 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2229 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2231 * @since 1.20
2233 * @param int $seconds The amount of seconds.
2234 * @param array $chosenIntervals The intervals to enable.
2236 * @return array
2238 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2239 if ( empty( $chosenIntervals ) ) {
2240 $chosenIntervals = array(
2241 'millennia',
2242 'centuries',
2243 'decades',
2244 'years',
2245 'days',
2246 'hours',
2247 'minutes',
2248 'seconds'
2252 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2253 $sortedNames = array_keys( $intervals );
2254 $smallestInterval = array_pop( $sortedNames );
2256 $segments = array();
2258 foreach ( $intervals as $name => $length ) {
2259 $value = floor( $seconds / $length );
2261 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2262 $seconds -= $value * $length;
2263 $segments[$name] = $value;
2267 return $segments;
2271 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2273 * @param string $type Can be 'date', 'time' or 'both'
2274 * @param string $ts The time format which needs to be turned into a
2275 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2276 * @param User $user User object used to get preferences for timezone and format
2277 * @param array $options Array, can contain the following keys:
2278 * - 'timecorrection': time correction, can have the following values:
2279 * - true: use user's preference
2280 * - false: don't use time correction
2281 * - int: value of time correction in minutes
2282 * - 'format': format to use, can have the following values:
2283 * - true: use user's preference
2284 * - false: use default preference
2285 * - string: format to use
2286 * @since 1.19
2287 * @return string
2289 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2290 $ts = wfTimestamp( TS_MW, $ts );
2291 $options += array( 'timecorrection' => true, 'format' => true );
2292 if ( $options['timecorrection'] !== false ) {
2293 if ( $options['timecorrection'] === true ) {
2294 $offset = $user->getOption( 'timecorrection' );
2295 } else {
2296 $offset = $options['timecorrection'];
2298 $ts = $this->userAdjust( $ts, $offset );
2300 if ( $options['format'] === true ) {
2301 $format = $user->getDatePreference();
2302 } else {
2303 $format = $options['format'];
2305 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2306 return $this->sprintfDate( $df, $ts );
2310 * Get the formatted date for the given timestamp and formatted for
2311 * the given user.
2313 * @param mixed $ts Mixed: the time format which needs to be turned into a
2314 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2315 * @param User $user User object used to get preferences for timezone and format
2316 * @param array $options Array, can contain the following keys:
2317 * - 'timecorrection': time correction, can have the following values:
2318 * - true: use user's preference
2319 * - false: don't use time correction
2320 * - int: value of time correction in minutes
2321 * - 'format': format to use, can have the following values:
2322 * - true: use user's preference
2323 * - false: use default preference
2324 * - string: format to use
2325 * @since 1.19
2326 * @return string
2328 public function userDate( $ts, User $user, array $options = array() ) {
2329 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2333 * Get the formatted time for the given timestamp and formatted for
2334 * the given user.
2336 * @param mixed $ts The time format which needs to be turned into a
2337 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2338 * @param User $user User object used to get preferences for timezone and format
2339 * @param array $options Array, can contain the following keys:
2340 * - 'timecorrection': time correction, can have the following values:
2341 * - true: use user's preference
2342 * - false: don't use time correction
2343 * - int: value of time correction in minutes
2344 * - 'format': format to use, can have the following values:
2345 * - true: use user's preference
2346 * - false: use default preference
2347 * - string: format to use
2348 * @since 1.19
2349 * @return string
2351 public function userTime( $ts, User $user, array $options = array() ) {
2352 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2356 * Get the formatted date and time for the given timestamp and formatted for
2357 * the given user.
2359 * @param mixed $ts The time format which needs to be turned into a
2360 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2361 * @param User $user User object used to get preferences for timezone and format
2362 * @param array $options Array, can contain the following keys:
2363 * - 'timecorrection': time correction, can have the following values:
2364 * - true: use user's preference
2365 * - false: don't use time correction
2366 * - int: value of time correction in minutes
2367 * - 'format': format to use, can have the following values:
2368 * - true: use user's preference
2369 * - false: use default preference
2370 * - string: format to use
2371 * @since 1.19
2372 * @return string
2374 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2375 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2379 * Convert an MWTimestamp into a pretty human-readable timestamp using
2380 * the given user preferences and relative base time.
2382 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2383 * on your timestamp object, which will then call this function. Calling
2384 * this function directly will cause hooks to be skipped over.
2386 * @see MWTimestamp::getHumanTimestamp
2387 * @param MWTimestamp $ts Timestamp to prettify
2388 * @param MWTimestamp $relativeTo Base timestamp
2389 * @param User $user User preferences to use
2390 * @return string Human timestamp
2391 * @since 1.22
2393 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2394 $diff = $ts->diff( $relativeTo );
2395 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2396 (int)$relativeTo->timestamp->format( 'w' ) );
2397 $days = $diff->days ?: (int)$diffDay;
2398 if ( $diff->invert || $days > 5
2399 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2401 // Timestamps are in different years: use full timestamp
2402 // Also do full timestamp for future dates
2404 * @todo FIXME: Add better handling of future timestamps.
2406 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2407 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2408 } elseif ( $days > 5 ) {
2409 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2410 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2411 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2412 } elseif ( $days > 1 ) {
2413 // Timestamp within the past week: show the day of the week and time
2414 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2415 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2416 // Messages:
2417 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2418 $ts = wfMessage( "$weekday-at" )
2419 ->inLanguage( $this )
2420 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2421 ->text();
2422 } elseif ( $days == 1 ) {
2423 // Timestamp was yesterday: say 'yesterday' and the time.
2424 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2425 $ts = wfMessage( 'yesterday-at' )
2426 ->inLanguage( $this )
2427 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2428 ->text();
2429 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2430 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2431 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2432 $ts = wfMessage( 'today-at' )
2433 ->inLanguage( $this )
2434 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2435 ->text();
2437 // From here on in, the timestamp was soon enough ago so that we can simply say
2438 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2439 } elseif ( $diff->h == 1 ) {
2440 // Less than 90 minutes, but more than an hour ago.
2441 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2442 } elseif ( $diff->i >= 1 ) {
2443 // A few minutes ago.
2444 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2445 } elseif ( $diff->s >= 30 ) {
2446 // Less than a minute, but more than 30 sec ago.
2447 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2448 } else {
2449 // Less than 30 seconds ago.
2450 $ts = wfMessage( 'just-now' )->text();
2453 return $ts;
2457 * @param string $key
2458 * @return array|null
2460 function getMessage( $key ) {
2461 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2465 * @return array
2467 function getAllMessages() {
2468 return self::$dataCache->getItem( $this->mCode, 'messages' );
2472 * @param string $in
2473 * @param string $out
2474 * @param string $string
2475 * @return string
2477 function iconv( $in, $out, $string ) {
2478 # This is a wrapper for iconv in all languages except esperanto,
2479 # which does some nasty x-conversions beforehand
2481 # Even with //IGNORE iconv can whine about illegal characters in
2482 # *input* string. We just ignore those too.
2483 # REF: http://bugs.php.net/bug.php?id=37166
2484 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2485 wfSuppressWarnings();
2486 $text = iconv( $in, $out . '//IGNORE', $string );
2487 wfRestoreWarnings();
2488 return $text;
2491 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2494 * @param array $matches
2495 * @return mixed|string
2497 function ucwordbreaksCallbackAscii( $matches ) {
2498 return $this->ucfirst( $matches[1] );
2502 * @param array $matches
2503 * @return string
2505 function ucwordbreaksCallbackMB( $matches ) {
2506 return mb_strtoupper( $matches[0] );
2510 * @param array $matches
2511 * @return string
2513 function ucCallback( $matches ) {
2514 list( $wikiUpperChars ) = self::getCaseMaps();
2515 return strtr( $matches[1], $wikiUpperChars );
2519 * @param array $matches
2520 * @return string
2522 function lcCallback( $matches ) {
2523 list( , $wikiLowerChars ) = self::getCaseMaps();
2524 return strtr( $matches[1], $wikiLowerChars );
2528 * @param array $matches
2529 * @return string
2531 function ucwordsCallbackMB( $matches ) {
2532 return mb_strtoupper( $matches[0] );
2536 * @param array $matches
2537 * @return string
2539 function ucwordsCallbackWiki( $matches ) {
2540 list( $wikiUpperChars ) = self::getCaseMaps();
2541 return strtr( $matches[0], $wikiUpperChars );
2545 * Make a string's first character uppercase
2547 * @param string $str
2549 * @return string
2551 function ucfirst( $str ) {
2552 $o = ord( $str );
2553 if ( $o < 96 ) { // if already uppercase...
2554 return $str;
2555 } elseif ( $o < 128 ) {
2556 return ucfirst( $str ); // use PHP's ucfirst()
2557 } else {
2558 // fall back to more complex logic in case of multibyte strings
2559 return $this->uc( $str, true );
2564 * Convert a string to uppercase
2566 * @param string $str
2567 * @param bool $first
2569 * @return string
2571 function uc( $str, $first = false ) {
2572 if ( function_exists( 'mb_strtoupper' ) ) {
2573 if ( $first ) {
2574 if ( $this->isMultibyte( $str ) ) {
2575 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2576 } else {
2577 return ucfirst( $str );
2579 } else {
2580 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2582 } else {
2583 if ( $this->isMultibyte( $str ) ) {
2584 $x = $first ? '^' : '';
2585 return preg_replace_callback(
2586 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2587 array( $this, 'ucCallback' ),
2588 $str
2590 } else {
2591 return $first ? ucfirst( $str ) : strtoupper( $str );
2597 * @param string $str
2598 * @return mixed|string
2600 function lcfirst( $str ) {
2601 $o = ord( $str );
2602 if ( !$o ) {
2603 return strval( $str );
2604 } elseif ( $o >= 128 ) {
2605 return $this->lc( $str, true );
2606 } elseif ( $o > 96 ) {
2607 return $str;
2608 } else {
2609 $str[0] = strtolower( $str[0] );
2610 return $str;
2615 * @param string $str
2616 * @param bool $first
2617 * @return mixed|string
2619 function lc( $str, $first = false ) {
2620 if ( function_exists( 'mb_strtolower' ) ) {
2621 if ( $first ) {
2622 if ( $this->isMultibyte( $str ) ) {
2623 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2624 } else {
2625 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2627 } else {
2628 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2630 } else {
2631 if ( $this->isMultibyte( $str ) ) {
2632 $x = $first ? '^' : '';
2633 return preg_replace_callback(
2634 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2635 array( $this, 'lcCallback' ),
2636 $str
2638 } else {
2639 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2645 * @param string $str
2646 * @return bool
2648 function isMultibyte( $str ) {
2649 return (bool)preg_match( '/[\x80-\xff]/', $str );
2653 * @param string $str
2654 * @return mixed|string
2656 function ucwords( $str ) {
2657 if ( $this->isMultibyte( $str ) ) {
2658 $str = $this->lc( $str );
2660 // regexp to find first letter in each word (i.e. after each space)
2661 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2663 // function to use to capitalize a single char
2664 if ( function_exists( 'mb_strtoupper' ) ) {
2665 return preg_replace_callback(
2666 $replaceRegexp,
2667 array( $this, 'ucwordsCallbackMB' ),
2668 $str
2670 } else {
2671 return preg_replace_callback(
2672 $replaceRegexp,
2673 array( $this, 'ucwordsCallbackWiki' ),
2674 $str
2677 } else {
2678 return ucwords( strtolower( $str ) );
2683 * capitalize words at word breaks
2685 * @param string $str
2686 * @return mixed
2688 function ucwordbreaks( $str ) {
2689 if ( $this->isMultibyte( $str ) ) {
2690 $str = $this->lc( $str );
2692 // since \b doesn't work for UTF-8, we explicitely define word break chars
2693 $breaks = "[ \-\(\)\}\{\.,\?!]";
2695 // find first letter after word break
2696 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2697 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2699 if ( function_exists( 'mb_strtoupper' ) ) {
2700 return preg_replace_callback(
2701 $replaceRegexp,
2702 array( $this, 'ucwordbreaksCallbackMB' ),
2703 $str
2705 } else {
2706 return preg_replace_callback(
2707 $replaceRegexp,
2708 array( $this, 'ucwordsCallbackWiki' ),
2709 $str
2712 } else {
2713 return preg_replace_callback(
2714 '/\b([\w\x80-\xff]+)\b/',
2715 array( $this, 'ucwordbreaksCallbackAscii' ),
2716 $str
2722 * Return a case-folded representation of $s
2724 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2725 * and $s2 are the same except for the case of their characters. It is not
2726 * necessary for the value returned to make sense when displayed.
2728 * Do *not* perform any other normalisation in this function. If a caller
2729 * uses this function when it should be using a more general normalisation
2730 * function, then fix the caller.
2732 * @param string $s
2734 * @return string
2736 function caseFold( $s ) {
2737 return $this->uc( $s );
2741 * @param string $s
2742 * @return string
2744 function checkTitleEncoding( $s ) {
2745 if ( is_array( $s ) ) {
2746 throw new MWException( 'Given array to checkTitleEncoding.' );
2748 if ( StringUtils::isUtf8( $s ) ) {
2749 return $s;
2752 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2756 * @return array
2758 function fallback8bitEncoding() {
2759 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2763 * Most writing systems use whitespace to break up words.
2764 * Some languages such as Chinese don't conventionally do this,
2765 * which requires special handling when breaking up words for
2766 * searching etc.
2768 * @return bool
2770 function hasWordBreaks() {
2771 return true;
2775 * Some languages such as Chinese require word segmentation,
2776 * Specify such segmentation when overridden in derived class.
2778 * @param string $string
2779 * @return string
2781 function segmentByWord( $string ) {
2782 return $string;
2786 * Some languages have special punctuation need to be normalized.
2787 * Make such changes here.
2789 * @param string $string
2790 * @return string
2792 function normalizeForSearch( $string ) {
2793 return self::convertDoubleWidth( $string );
2797 * convert double-width roman characters to single-width.
2798 * range: ff00-ff5f ~= 0020-007f
2800 * @param string $string
2802 * @return string
2804 protected static function convertDoubleWidth( $string ) {
2805 static $full = null;
2806 static $half = null;
2808 if ( $full === null ) {
2809 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2810 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2811 $full = str_split( $fullWidth, 3 );
2812 $half = str_split( $halfWidth );
2815 $string = str_replace( $full, $half, $string );
2816 return $string;
2820 * @param string $string
2821 * @param string $pattern
2822 * @return string
2824 protected static function insertSpace( $string, $pattern ) {
2825 $string = preg_replace( $pattern, " $1 ", $string );
2826 $string = preg_replace( '/ +/', ' ', $string );
2827 return $string;
2831 * @param array $termsArray
2832 * @return array
2834 function convertForSearchResult( $termsArray ) {
2835 # some languages, e.g. Chinese, need to do a conversion
2836 # in order for search results to be displayed correctly
2837 return $termsArray;
2841 * Get the first character of a string.
2843 * @param string $s
2844 * @return string
2846 function firstChar( $s ) {
2847 $matches = array();
2848 preg_match(
2849 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2850 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2852 $matches
2855 if ( isset( $matches[1] ) ) {
2856 if ( strlen( $matches[1] ) != 3 ) {
2857 return $matches[1];
2860 // Break down Hangul syllables to grab the first jamo
2861 $code = utf8ToCodepoint( $matches[1] );
2862 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2863 return $matches[1];
2864 } elseif ( $code < 0xb098 ) {
2865 return "\xe3\x84\xb1";
2866 } elseif ( $code < 0xb2e4 ) {
2867 return "\xe3\x84\xb4";
2868 } elseif ( $code < 0xb77c ) {
2869 return "\xe3\x84\xb7";
2870 } elseif ( $code < 0xb9c8 ) {
2871 return "\xe3\x84\xb9";
2872 } elseif ( $code < 0xbc14 ) {
2873 return "\xe3\x85\x81";
2874 } elseif ( $code < 0xc0ac ) {
2875 return "\xe3\x85\x82";
2876 } elseif ( $code < 0xc544 ) {
2877 return "\xe3\x85\x85";
2878 } elseif ( $code < 0xc790 ) {
2879 return "\xe3\x85\x87";
2880 } elseif ( $code < 0xcc28 ) {
2881 return "\xe3\x85\x88";
2882 } elseif ( $code < 0xce74 ) {
2883 return "\xe3\x85\x8a";
2884 } elseif ( $code < 0xd0c0 ) {
2885 return "\xe3\x85\x8b";
2886 } elseif ( $code < 0xd30c ) {
2887 return "\xe3\x85\x8c";
2888 } elseif ( $code < 0xd558 ) {
2889 return "\xe3\x85\x8d";
2890 } else {
2891 return "\xe3\x85\x8e";
2893 } else {
2894 return '';
2898 function initEncoding() {
2899 # Some languages may have an alternate char encoding option
2900 # (Esperanto X-coding, Japanese furigana conversion, etc)
2901 # If this language is used as the primary content language,
2902 # an override to the defaults can be set here on startup.
2906 * @param string $s
2907 * @return string
2909 function recodeForEdit( $s ) {
2910 # For some languages we'll want to explicitly specify
2911 # which characters make it into the edit box raw
2912 # or are converted in some way or another.
2913 global $wgEditEncoding;
2914 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2915 return $s;
2916 } else {
2917 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2922 * @param string $s
2923 * @return string
2925 function recodeInput( $s ) {
2926 # Take the previous into account.
2927 global $wgEditEncoding;
2928 if ( $wgEditEncoding != '' ) {
2929 $enc = $wgEditEncoding;
2930 } else {
2931 $enc = 'UTF-8';
2933 if ( $enc == 'UTF-8' ) {
2934 return $s;
2935 } else {
2936 return $this->iconv( $enc, 'UTF-8', $s );
2941 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2942 * also cleans up certain backwards-compatible sequences, converting them
2943 * to the modern Unicode equivalent.
2945 * This is language-specific for performance reasons only.
2947 * @param string $s
2949 * @return string
2951 function normalize( $s ) {
2952 global $wgAllUnicodeFixes;
2953 $s = UtfNormal::cleanUp( $s );
2954 if ( $wgAllUnicodeFixes ) {
2955 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2956 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2959 return $s;
2963 * Transform a string using serialized data stored in the given file (which
2964 * must be in the serialized subdirectory of $IP). The file contains pairs
2965 * mapping source characters to destination characters.
2967 * The data is cached in process memory. This will go faster if you have the
2968 * FastStringSearch extension.
2970 * @param string $file
2971 * @param string $string
2973 * @throws MWException
2974 * @return string
2976 function transformUsingPairFile( $file, $string ) {
2977 if ( !isset( $this->transformData[$file] ) ) {
2978 $data = wfGetPrecompiledData( $file );
2979 if ( $data === false ) {
2980 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2982 $this->transformData[$file] = new ReplacementArray( $data );
2984 return $this->transformData[$file]->replace( $string );
2988 * For right-to-left language support
2990 * @return bool
2992 function isRTL() {
2993 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2997 * Return the correct HTML 'dir' attribute value for this language.
2998 * @return string
3000 function getDir() {
3001 return $this->isRTL() ? 'rtl' : 'ltr';
3005 * Return 'left' or 'right' as appropriate alignment for line-start
3006 * for this language's text direction.
3008 * Should be equivalent to CSS3 'start' text-align value....
3010 * @return string
3012 function alignStart() {
3013 return $this->isRTL() ? 'right' : 'left';
3017 * Return 'right' or 'left' as appropriate alignment for line-end
3018 * for this language's text direction.
3020 * Should be equivalent to CSS3 'end' text-align value....
3022 * @return string
3024 function alignEnd() {
3025 return $this->isRTL() ? 'left' : 'right';
3029 * A hidden direction mark (LRM or RLM), depending on the language direction.
3030 * Unlike getDirMark(), this function returns the character as an HTML entity.
3031 * This function should be used when the output is guaranteed to be HTML,
3032 * because it makes the output HTML source code more readable. When
3033 * the output is plain text or can be escaped, getDirMark() should be used.
3035 * @param bool $opposite Get the direction mark opposite to your language
3036 * @return string
3037 * @since 1.20
3039 function getDirMarkEntity( $opposite = false ) {
3040 if ( $opposite ) {
3041 return $this->isRTL() ? '&lrm;' : '&rlm;';
3043 return $this->isRTL() ? '&rlm;' : '&lrm;';
3047 * A hidden direction mark (LRM or RLM), depending on the language direction.
3048 * This function produces them as invisible Unicode characters and
3049 * the output may be hard to read and debug, so it should only be used
3050 * when the output is plain text or can be escaped. When the output is
3051 * HTML, use getDirMarkEntity() instead.
3053 * @param bool $opposite Get the direction mark opposite to your language
3054 * @return string
3056 function getDirMark( $opposite = false ) {
3057 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3058 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3059 if ( $opposite ) {
3060 return $this->isRTL() ? $lrm : $rlm;
3062 return $this->isRTL() ? $rlm : $lrm;
3066 * @return array
3068 function capitalizeAllNouns() {
3069 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3073 * An arrow, depending on the language direction.
3075 * @param string $direction The direction of the arrow: forwards (default),
3076 * backwards, left, right, up, down.
3077 * @return string
3079 function getArrow( $direction = 'forwards' ) {
3080 switch ( $direction ) {
3081 case 'forwards':
3082 return $this->isRTL() ? '←' : '→';
3083 case 'backwards':
3084 return $this->isRTL() ? '→' : '←';
3085 case 'left':
3086 return '←';
3087 case 'right':
3088 return '→';
3089 case 'up':
3090 return '↑';
3091 case 'down':
3092 return '↓';
3097 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3099 * @return bool
3101 function linkPrefixExtension() {
3102 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
3106 * Get all magic words from cache.
3107 * @return array
3109 function getMagicWords() {
3110 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
3114 * Run the LanguageGetMagic hook once.
3116 protected function doMagicHook() {
3117 if ( $this->mMagicHookDone ) {
3118 return;
3120 $this->mMagicHookDone = true;
3121 wfProfileIn( 'LanguageGetMagic' );
3122 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3123 wfProfileOut( 'LanguageGetMagic' );
3127 * Fill a MagicWord object with data from here
3129 * @param MagicWord $mw
3131 function getMagic( $mw ) {
3132 // Saves a function call
3133 if ( !$this->mMagicHookDone ) {
3134 $this->doMagicHook();
3137 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3138 $rawEntry = $this->mMagicExtensions[$mw->mId];
3139 } else {
3140 $rawEntry = self::$dataCache->getSubitem(
3141 $this->mCode, 'magicWords', $mw->mId );
3144 if ( !is_array( $rawEntry ) ) {
3145 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3146 } else {
3147 $mw->mCaseSensitive = $rawEntry[0];
3148 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3153 * Add magic words to the extension array
3155 * @param array $newWords
3157 function addMagicWordsByLang( $newWords ) {
3158 $fallbackChain = $this->getFallbackLanguages();
3159 $fallbackChain = array_reverse( $fallbackChain );
3160 foreach ( $fallbackChain as $code ) {
3161 if ( isset( $newWords[$code] ) ) {
3162 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3168 * Get special page names, as an associative array
3169 * case folded alias => real name
3170 * @return array
3172 function getSpecialPageAliases() {
3173 // Cache aliases because it may be slow to load them
3174 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3175 // Initialise array
3176 $this->mExtendedSpecialPageAliases =
3177 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3178 wfRunHooks( 'LanguageGetSpecialPageAliases',
3179 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3182 return $this->mExtendedSpecialPageAliases;
3186 * Italic is unsuitable for some languages
3188 * @param string $text The text to be emphasized.
3189 * @return string
3191 function emphasize( $text ) {
3192 return "<em>$text</em>";
3196 * Normally we output all numbers in plain en_US style, that is
3197 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3198 * point twohundredthirtyfive. However this is not suitable for all
3199 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3200 * Icelandic just want to use commas instead of dots, and dots instead
3201 * of commas like "293.291,235".
3203 * An example of this function being called:
3204 * <code>
3205 * wfMessage( 'message' )->numParams( $num )->text()
3206 * </code>
3208 * See $separatorTransformTable on MessageIs.php for
3209 * the , => . and . => , implementation.
3211 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3212 * @param int|float $number The string to be formatted, should be an integer
3213 * or a floating point number.
3214 * @param bool $nocommafy Set to true for special numbers like dates
3215 * @return string
3217 public function formatNum( $number, $nocommafy = false ) {
3218 global $wgTranslateNumerals;
3219 if ( !$nocommafy ) {
3220 $number = $this->commafy( $number );
3221 $s = $this->separatorTransformTable();
3222 if ( $s ) {
3223 $number = strtr( $number, $s );
3227 if ( $wgTranslateNumerals ) {
3228 $s = $this->digitTransformTable();
3229 if ( $s ) {
3230 $number = strtr( $number, $s );
3234 return $number;
3238 * Front-end for non-commafied formatNum
3240 * @param int|float $number The string to be formatted, should be an integer
3241 * or a floating point number.
3242 * @since 1.21
3243 * @return string
3245 public function formatNumNoSeparators( $number ) {
3246 return $this->formatNum( $number, true );
3250 * @param string $number
3251 * @return string
3253 public function parseFormattedNumber( $number ) {
3254 $s = $this->digitTransformTable();
3255 if ( $s ) {
3256 // eliminate empty array values such as ''. (bug 64347)
3257 $s = array_filter( $s );
3258 $number = strtr( $number, array_flip( $s ) );
3261 $s = $this->separatorTransformTable();
3262 if ( $s ) {
3263 // eliminate empty array values such as ''. (bug 64347)
3264 $s = array_filter( $s );
3265 $number = strtr( $number, array_flip( $s ) );
3268 $number = strtr( $number, array( ',' => '' ) );
3269 return $number;
3273 * Adds commas to a given number
3274 * @since 1.19
3275 * @param mixed $number
3276 * @return string
3278 function commafy( $number ) {
3279 $digitGroupingPattern = $this->digitGroupingPattern();
3280 if ( $number === null ) {
3281 return '';
3284 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3285 // default grouping is at thousands, use the same for ###,###,### pattern too.
3286 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3287 } else {
3288 // Ref: http://cldr.unicode.org/translation/number-patterns
3289 $sign = "";
3290 if ( intval( $number ) < 0 ) {
3291 // For negative numbers apply the algorithm like positive number and add sign.
3292 $sign = "-";
3293 $number = substr( $number, 1 );
3295 $integerPart = array();
3296 $decimalPart = array();
3297 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3298 preg_match( "/\d+/", $number, $integerPart );
3299 preg_match( "/\.\d*/", $number, $decimalPart );
3300 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3301 if ( $groupedNumber === $number ) {
3302 // the string does not have any number part. Eg: .12345
3303 return $sign . $groupedNumber;
3305 $start = $end = strlen( $integerPart[0] );
3306 while ( $start > 0 ) {
3307 $match = $matches[0][$numMatches - 1];
3308 $matchLen = strlen( $match );
3309 $start = $end - $matchLen;
3310 if ( $start < 0 ) {
3311 $start = 0;
3313 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3314 $end = $start;
3315 if ( $numMatches > 1 ) {
3316 // use the last pattern for the rest of the number
3317 $numMatches--;
3319 if ( $start > 0 ) {
3320 $groupedNumber = "," . $groupedNumber;
3323 return $sign . $groupedNumber;
3328 * @return string
3330 function digitGroupingPattern() {
3331 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3335 * @return array
3337 function digitTransformTable() {
3338 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3342 * @return array
3344 function separatorTransformTable() {
3345 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3349 * Take a list of strings and build a locale-friendly comma-separated
3350 * list, using the local comma-separator message.
3351 * The last two strings are chained with an "and".
3352 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3354 * @param string[] $l
3355 * @return string
3357 function listToText( array $l ) {
3358 $m = count( $l ) - 1;
3359 if ( $m < 0 ) {
3360 return '';
3362 if ( $m > 0 ) {
3363 $and = $this->getMessageFromDB( 'and' );
3364 $space = $this->getMessageFromDB( 'word-separator' );
3365 if ( $m > 1 ) {
3366 $comma = $this->getMessageFromDB( 'comma-separator' );
3369 $s = $l[$m];
3370 for ( $i = $m - 1; $i >= 0; $i-- ) {
3371 if ( $i == $m - 1 ) {
3372 $s = $l[$i] . $and . $space . $s;
3373 } else {
3374 $s = $l[$i] . $comma . $s;
3377 return $s;
3381 * Take a list of strings and build a locale-friendly comma-separated
3382 * list, using the local comma-separator message.
3383 * @param string[] $list Array of strings to put in a comma list
3384 * @return string
3386 function commaList( array $list ) {
3387 return implode(
3388 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3389 $list
3394 * Take a list of strings and build a locale-friendly semicolon-separated
3395 * list, using the local semicolon-separator message.
3396 * @param string[] $list Array of strings to put in a semicolon list
3397 * @return string
3399 function semicolonList( array $list ) {
3400 return implode(
3401 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3402 $list
3407 * Same as commaList, but separate it with the pipe instead.
3408 * @param string[] $list Array of strings to put in a pipe list
3409 * @return string
3411 function pipeList( array $list ) {
3412 return implode(
3413 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3414 $list
3419 * Truncate a string to a specified length in bytes, appending an optional
3420 * string (e.g. for ellipses)
3422 * The database offers limited byte lengths for some columns in the database;
3423 * multi-byte character sets mean we need to ensure that only whole characters
3424 * are included, otherwise broken characters can be passed to the user
3426 * If $length is negative, the string will be truncated from the beginning
3428 * @param string $string String to truncate
3429 * @param int $length Maximum length (including ellipses)
3430 * @param string $ellipsis String to append to the truncated text
3431 * @param bool $adjustLength Subtract length of ellipsis from $length.
3432 * $adjustLength was introduced in 1.18, before that behaved as if false.
3433 * @return string
3435 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3436 # Use the localized ellipsis character
3437 if ( $ellipsis == '...' ) {
3438 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3440 # Check if there is no need to truncate
3441 if ( $length == 0 ) {
3442 return $ellipsis; // convention
3443 } elseif ( strlen( $string ) <= abs( $length ) ) {
3444 return $string; // no need to truncate
3446 $stringOriginal = $string;
3447 # If ellipsis length is >= $length then we can't apply $adjustLength
3448 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3449 $string = $ellipsis; // this can be slightly unexpected
3450 # Otherwise, truncate and add ellipsis...
3451 } else {
3452 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3453 if ( $length > 0 ) {
3454 $length -= $eLength;
3455 $string = substr( $string, 0, $length ); // xyz...
3456 $string = $this->removeBadCharLast( $string );
3457 $string = rtrim( $string );
3458 $string = $string . $ellipsis;
3459 } else {
3460 $length += $eLength;
3461 $string = substr( $string, $length ); // ...xyz
3462 $string = $this->removeBadCharFirst( $string );
3463 $string = ltrim( $string );
3464 $string = $ellipsis . $string;
3467 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3468 # This check is *not* redundant if $adjustLength, due to the single case where
3469 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3470 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3471 return $string;
3472 } else {
3473 return $stringOriginal;
3478 * Remove bytes that represent an incomplete Unicode character
3479 * at the end of string (e.g. bytes of the char are missing)
3481 * @param string $string
3482 * @return string
3484 protected function removeBadCharLast( $string ) {
3485 if ( $string != '' ) {
3486 $char = ord( $string[strlen( $string ) - 1] );
3487 $m = array();
3488 if ( $char >= 0xc0 ) {
3489 # We got the first byte only of a multibyte char; remove it.
3490 $string = substr( $string, 0, -1 );
3491 } elseif ( $char >= 0x80 &&
3492 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3493 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3495 # We chopped in the middle of a character; remove it
3496 $string = $m[1];
3499 return $string;
3503 * Remove bytes that represent an incomplete Unicode character
3504 * at the start of string (e.g. bytes of the char are missing)
3506 * @param string $string
3507 * @return string
3509 protected function removeBadCharFirst( $string ) {
3510 if ( $string != '' ) {
3511 $char = ord( $string[0] );
3512 if ( $char >= 0x80 && $char < 0xc0 ) {
3513 # We chopped in the middle of a character; remove the whole thing
3514 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3517 return $string;
3521 * Truncate a string of valid HTML to a specified length in bytes,
3522 * appending an optional string (e.g. for ellipses), and return valid HTML
3524 * This is only intended for styled/linked text, such as HTML with
3525 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3526 * Also, this will not detect things like "display:none" CSS.
3528 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3530 * @param string $text HTML string to truncate
3531 * @param int $length (zero/positive) Maximum length (including ellipses)
3532 * @param string $ellipsis String to append to the truncated text
3533 * @return string
3535 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3536 # Use the localized ellipsis character
3537 if ( $ellipsis == '...' ) {
3538 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3540 # Check if there is clearly no need to truncate
3541 if ( $length <= 0 ) {
3542 return $ellipsis; // no text shown, nothing to format (convention)
3543 } elseif ( strlen( $text ) <= $length ) {
3544 return $text; // string short enough even *with* HTML (short-circuit)
3547 $dispLen = 0; // innerHTML legth so far
3548 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3549 $tagType = 0; // 0-open, 1-close
3550 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3551 $entityState = 0; // 0-not entity, 1-entity
3552 $tag = $ret = ''; // accumulated tag name, accumulated result string
3553 $openTags = array(); // open tag stack
3554 $maybeState = null; // possible truncation state
3556 $textLen = strlen( $text );
3557 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3558 for ( $pos = 0; true; ++$pos ) {
3559 # Consider truncation once the display length has reached the maximim.
3560 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3561 # Check that we're not in the middle of a bracket/entity...
3562 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3563 if ( !$testingEllipsis ) {
3564 $testingEllipsis = true;
3565 # Save where we are; we will truncate here unless there turn out to
3566 # be so few remaining characters that truncation is not necessary.
3567 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3568 $maybeState = array( $ret, $openTags ); // save state
3570 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3571 # String in fact does need truncation, the truncation point was OK.
3572 list( $ret, $openTags ) = $maybeState; // reload state
3573 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3574 $ret .= $ellipsis; // add ellipsis
3575 break;
3578 if ( $pos >= $textLen ) {
3579 break; // extra iteration just for above checks
3582 # Read the next char...
3583 $ch = $text[$pos];
3584 $lastCh = $pos ? $text[$pos - 1] : '';
3585 $ret .= $ch; // add to result string
3586 if ( $ch == '<' ) {
3587 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3588 $entityState = 0; // for bad HTML
3589 $bracketState = 1; // tag started (checking for backslash)
3590 } elseif ( $ch == '>' ) {
3591 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3592 $entityState = 0; // for bad HTML
3593 $bracketState = 0; // out of brackets
3594 } elseif ( $bracketState == 1 ) {
3595 if ( $ch == '/' ) {
3596 $tagType = 1; // close tag (e.g. "</span>")
3597 } else {
3598 $tagType = 0; // open tag (e.g. "<span>")
3599 $tag .= $ch;
3601 $bracketState = 2; // building tag name
3602 } elseif ( $bracketState == 2 ) {
3603 if ( $ch != ' ' ) {
3604 $tag .= $ch;
3605 } else {
3606 // Name found (e.g. "<a href=..."), add on tag attributes...
3607 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3609 } elseif ( $bracketState == 0 ) {
3610 if ( $entityState ) {
3611 if ( $ch == ';' ) {
3612 $entityState = 0;
3613 $dispLen++; // entity is one displayed char
3615 } else {
3616 if ( $neLength == 0 && !$maybeState ) {
3617 // Save state without $ch. We want to *hit* the first
3618 // display char (to get tags) but not *use* it if truncating.
3619 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3621 if ( $ch == '&' ) {
3622 $entityState = 1; // entity found, (e.g. "&#160;")
3623 } else {
3624 $dispLen++; // this char is displayed
3625 // Add the next $max display text chars after this in one swoop...
3626 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3627 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3628 $dispLen += $skipped;
3629 $pos += $skipped;
3634 // Close the last tag if left unclosed by bad HTML
3635 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3636 while ( count( $openTags ) > 0 ) {
3637 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3639 return $ret;
3643 * truncateHtml() helper function
3644 * like strcspn() but adds the skipped chars to $ret
3646 * @param string $ret
3647 * @param string $text
3648 * @param string $search
3649 * @param int $start
3650 * @param null|int $len
3651 * @return int
3653 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3654 if ( $len === null ) {
3655 $len = -1; // -1 means "no limit" for strcspn
3656 } elseif ( $len < 0 ) {
3657 $len = 0; // sanity
3659 $skipCount = 0;
3660 if ( $start < strlen( $text ) ) {
3661 $skipCount = strcspn( $text, $search, $start, $len );
3662 $ret .= substr( $text, $start, $skipCount );
3664 return $skipCount;
3668 * truncateHtml() helper function
3669 * (a) push or pop $tag from $openTags as needed
3670 * (b) clear $tag value
3671 * @param string &$tag Current HTML tag name we are looking at
3672 * @param int $tagType (0-open tag, 1-close tag)
3673 * @param string $lastCh Character before the '>' that ended this tag
3674 * @param array &$openTags Open tag stack (not accounting for $tag)
3676 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3677 $tag = ltrim( $tag );
3678 if ( $tag != '' ) {
3679 if ( $tagType == 0 && $lastCh != '/' ) {
3680 $openTags[] = $tag; // tag opened (didn't close itself)
3681 } elseif ( $tagType == 1 ) {
3682 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3683 array_pop( $openTags ); // tag closed
3686 $tag = '';
3691 * Grammatical transformations, needed for inflected languages
3692 * Invoked by putting {{grammar:case|word}} in a message
3694 * @param string $word
3695 * @param string $case
3696 * @return string
3698 function convertGrammar( $word, $case ) {
3699 global $wgGrammarForms;
3700 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3701 return $wgGrammarForms[$this->getCode()][$case][$word];
3704 return $word;
3707 * Get the grammar forms for the content language
3708 * @return array Array of grammar forms
3709 * @since 1.20
3711 function getGrammarForms() {
3712 global $wgGrammarForms;
3713 if ( isset( $wgGrammarForms[$this->getCode()] )
3714 && is_array( $wgGrammarForms[$this->getCode()] )
3716 return $wgGrammarForms[$this->getCode()];
3719 return array();
3722 * Provides an alternative text depending on specified gender.
3723 * Usage {{gender:username|masculine|feminine|unknown}}.
3724 * username is optional, in which case the gender of current user is used,
3725 * but only in (some) interface messages; otherwise default gender is used.
3727 * If no forms are given, an empty string is returned. If only one form is
3728 * given, it will be returned unconditionally. These details are implied by
3729 * the caller and cannot be overridden in subclasses.
3731 * If three forms are given, the default is to use the third (unknown) form.
3732 * If fewer than three forms are given, the default is to use the first (masculine) form.
3733 * These details can be overridden in subclasses.
3735 * @param string $gender
3736 * @param array $forms
3738 * @return string
3740 function gender( $gender, $forms ) {
3741 if ( !count( $forms ) ) {
3742 return '';
3744 $forms = $this->preConvertPlural( $forms, 2 );
3745 if ( $gender === 'male' ) {
3746 return $forms[0];
3748 if ( $gender === 'female' ) {
3749 return $forms[1];
3751 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3755 * Plural form transformations, needed for some languages.
3756 * For example, there are 3 form of plural in Russian and Polish,
3757 * depending on "count mod 10". See [[w:Plural]]
3758 * For English it is pretty simple.
3760 * Invoked by putting {{plural:count|wordform1|wordform2}}
3761 * or {{plural:count|wordform1|wordform2|wordform3}}
3763 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3765 * @param int $count Non-localized number
3766 * @param array $forms Different plural forms
3767 * @return string Correct form of plural for $count in this language
3769 function convertPlural( $count, $forms ) {
3770 // Handle explicit n=pluralform cases
3771 $forms = $this->handleExplicitPluralForms( $count, $forms );
3772 if ( is_string( $forms ) ) {
3773 return $forms;
3775 if ( !count( $forms ) ) {
3776 return '';
3779 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3780 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3781 return $forms[$pluralForm];
3785 * Handles explicit plural forms for Language::convertPlural()
3787 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3788 * If an explicitly defined plural form matches the $count, then
3789 * string value returned, otherwise array returned for further consideration
3790 * by CLDR rules or overridden convertPlural().
3792 * @since 1.23
3794 * @param int $count Non-localized number
3795 * @param array $forms Different plural forms
3797 * @return array|string
3799 protected function handleExplicitPluralForms( $count, array $forms ) {
3800 foreach ( $forms as $index => $form ) {
3801 if ( preg_match( '/\d+=/i', $form ) ) {
3802 $pos = strpos( $form, '=' );
3803 if ( substr( $form, 0, $pos ) === (string)$count ) {
3804 return substr( $form, $pos + 1 );
3806 unset( $forms[$index] );
3809 return array_values( $forms );
3813 * Checks that convertPlural was given an array and pads it to requested
3814 * amount of forms by copying the last one.
3816 * @param array $forms Array of forms given to convertPlural
3817 * @param int $count How many forms should there be at least
3818 * @return array Padded array of forms or an exception if not an array
3820 protected function preConvertPlural( /* Array */ $forms, $count ) {
3821 while ( count( $forms ) < $count ) {
3822 $forms[] = $forms[count( $forms ) - 1];
3824 return $forms;
3828 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3829 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3830 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3831 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3832 * match up with it.
3834 * @param string $str The validated block duration in English
3835 * @return string Somehow translated block duration
3836 * @see LanguageFi.php for example implementation
3838 function translateBlockExpiry( $str ) {
3839 $duration = SpecialBlock::getSuggestedDurations( $this );
3840 foreach ( $duration as $show => $value ) {
3841 if ( strcmp( $str, $value ) == 0 ) {
3842 return htmlspecialchars( trim( $show ) );
3846 // Since usually only infinite or indefinite is only on list, so try
3847 // equivalents if still here.
3848 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3849 if ( in_array( $str, $indefs ) ) {
3850 foreach ( $indefs as $val ) {
3851 $show = array_search( $val, $duration, true );
3852 if ( $show !== false ) {
3853 return htmlspecialchars( trim( $show ) );
3858 // If all else fails, return a standard duration or timestamp description.
3859 $time = strtotime( $str, 0 );
3860 if ( $time === false ) { // Unknown format. Return it as-is in case.
3861 return $str;
3862 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3863 // $time is relative to 0 so it's a duration length.
3864 return $this->formatDuration( $time );
3865 } else { // It's an absolute timestamp.
3866 if ( $time === 0 ) {
3867 // wfTimestamp() handles 0 as current time instead of epoch.
3868 return $this->timeanddate( '19700101000000' );
3869 } else {
3870 return $this->timeanddate( $time );
3876 * languages like Chinese need to be segmented in order for the diff
3877 * to be of any use
3879 * @param string $text
3880 * @return string
3882 public function segmentForDiff( $text ) {
3883 return $text;
3887 * and unsegment to show the result
3889 * @param string $text
3890 * @return string
3892 public function unsegmentForDiff( $text ) {
3893 return $text;
3897 * Return the LanguageConverter used in the Language
3899 * @since 1.19
3900 * @return LanguageConverter
3902 public function getConverter() {
3903 return $this->mConverter;
3907 * convert text to all supported variants
3909 * @param string $text
3910 * @return array
3912 public function autoConvertToAllVariants( $text ) {
3913 return $this->mConverter->autoConvertToAllVariants( $text );
3917 * convert text to different variants of a language.
3919 * @param string $text
3920 * @return string
3922 public function convert( $text ) {
3923 return $this->mConverter->convert( $text );
3927 * Convert a Title object to a string in the preferred variant
3929 * @param Title $title
3930 * @return string
3932 public function convertTitle( $title ) {
3933 return $this->mConverter->convertTitle( $title );
3937 * Convert a namespace index to a string in the preferred variant
3939 * @param int $ns
3940 * @return string
3942 public function convertNamespace( $ns ) {
3943 return $this->mConverter->convertNamespace( $ns );
3947 * Check if this is a language with variants
3949 * @return bool
3951 public function hasVariants() {
3952 return count( $this->getVariants() ) > 1;
3956 * Check if the language has the specific variant
3958 * @since 1.19
3959 * @param string $variant
3960 * @return bool
3962 public function hasVariant( $variant ) {
3963 return (bool)$this->mConverter->validateVariant( $variant );
3967 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3969 * @param string $text
3970 * @return string
3971 * @deprecated since 1.22 is no longer used
3973 public function armourMath( $text ) {
3974 return $this->mConverter->armourMath( $text );
3978 * Perform output conversion on a string, and encode for safe HTML output.
3979 * @param string $text Text to be converted
3980 * @param bool $isTitle Whether this conversion is for the article title
3981 * @return string
3982 * @todo this should get integrated somewhere sane
3984 public function convertHtml( $text, $isTitle = false ) {
3985 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3989 * @param string $key
3990 * @return string
3992 public function convertCategoryKey( $key ) {
3993 return $this->mConverter->convertCategoryKey( $key );
3997 * Get the list of variants supported by this language
3998 * see sample implementation in LanguageZh.php
4000 * @return array An array of language codes
4002 public function getVariants() {
4003 return $this->mConverter->getVariants();
4007 * @return string
4009 public function getPreferredVariant() {
4010 return $this->mConverter->getPreferredVariant();
4014 * @return string
4016 public function getDefaultVariant() {
4017 return $this->mConverter->getDefaultVariant();
4021 * @return string
4023 public function getURLVariant() {
4024 return $this->mConverter->getURLVariant();
4028 * If a language supports multiple variants, it is
4029 * possible that non-existing link in one variant
4030 * actually exists in another variant. this function
4031 * tries to find it. See e.g. LanguageZh.php
4032 * The input parameters may be modified upon return
4034 * @param string &$link The name of the link
4035 * @param Title &$nt The title object of the link
4036 * @param bool $ignoreOtherCond To disable other conditions when
4037 * we need to transclude a template or update a category's link
4039 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4040 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4044 * returns language specific options used by User::getPageRenderHash()
4045 * for example, the preferred language variant
4047 * @return string
4049 function getExtraHashOptions() {
4050 return $this->mConverter->getExtraHashOptions();
4054 * For languages that support multiple variants, the title of an
4055 * article may be displayed differently in different variants. this
4056 * function returns the apporiate title defined in the body of the article.
4058 * @return string
4060 public function getParsedTitle() {
4061 return $this->mConverter->getParsedTitle();
4065 * Prepare external link text for conversion. When the text is
4066 * a URL, it shouldn't be converted, and it'll be wrapped in
4067 * the "raw" tag (-{R| }-) to prevent conversion.
4069 * This function is called "markNoConversion" for historical
4070 * reasons.
4072 * @param string $text Text to be used for external link
4073 * @param bool $noParse Wrap it without confirming it's a real URL first
4074 * @return string The tagged text
4076 public function markNoConversion( $text, $noParse = false ) {
4077 // Excluding protocal-relative URLs may avoid many false positives.
4078 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4079 return $this->mConverter->markNoConversion( $text );
4080 } else {
4081 return $text;
4086 * A regular expression to match legal word-trailing characters
4087 * which should be merged onto a link of the form [[foo]]bar.
4089 * @return string
4091 public function linkTrail() {
4092 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
4096 * A regular expression character set to match legal word-prefixing
4097 * characters which should be merged onto a link of the form foo[[bar]].
4099 * @return string
4101 public function linkPrefixCharset() {
4102 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
4106 * @deprecated since 1.24, will be removed in 1.25
4107 * @return Language
4109 function getLangObj() {
4110 wfDeprecated( __METHOD__, '1.24' );
4111 return $this;
4115 * Get the "parent" language which has a converter to convert a "compatible" language
4116 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4118 * @return Language|null
4119 * @since 1.22
4121 public function getParentLanguage() {
4122 if ( $this->mParentLanguage !== false ) {
4123 return $this->mParentLanguage;
4126 $pieces = explode( '-', $this->getCode() );
4127 $code = $pieces[0];
4128 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4129 $this->mParentLanguage = null;
4130 return null;
4132 $lang = Language::factory( $code );
4133 if ( !$lang->hasVariant( $this->getCode() ) ) {
4134 $this->mParentLanguage = null;
4135 return null;
4138 $this->mParentLanguage = $lang;
4139 return $lang;
4143 * Get the RFC 3066 code for this language object
4145 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4146 * htmlspecialchars() or similar
4148 * @return string
4150 public function getCode() {
4151 return $this->mCode;
4155 * Get the code in Bcp47 format which we can use
4156 * inside of html lang="" tags.
4158 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4159 * htmlspecialchars() or similar.
4161 * @since 1.19
4162 * @return string
4164 public function getHtmlCode() {
4165 if ( is_null( $this->mHtmlCode ) ) {
4166 $this->mHtmlCode = wfBCP47( $this->getCode() );
4168 return $this->mHtmlCode;
4172 * @param string $code
4174 public function setCode( $code ) {
4175 $this->mCode = $code;
4176 // Ensure we don't leave incorrect cached data lying around
4177 $this->mHtmlCode = null;
4178 $this->mParentLanguage = false;
4182 * Get the name of a file for a certain language code
4183 * @param string $prefix Prepend this to the filename
4184 * @param string $code Language code
4185 * @param string $suffix Append this to the filename
4186 * @throws MWException
4187 * @return string $prefix . $mangledCode . $suffix
4189 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4190 if ( !self::isValidBuiltInCode( $code ) ) {
4191 throw new MWException( "Invalid language code \"$code\"" );
4194 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4198 * Get the language code from a file name. Inverse of getFileName()
4199 * @param string $filename $prefix . $languageCode . $suffix
4200 * @param string $prefix Prefix before the language code
4201 * @param string $suffix Suffix after the language code
4202 * @return string Language code, or false if $prefix or $suffix isn't found
4204 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4205 $m = null;
4206 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4207 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4208 if ( !count( $m ) ) {
4209 return false;
4211 return str_replace( '_', '-', strtolower( $m[1] ) );
4215 * @param string $code
4216 * @return string
4218 public static function getMessagesFileName( $code ) {
4219 global $IP;
4220 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4221 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4222 return $file;
4226 * @param string $code
4227 * @return string
4228 * @since 1.23
4230 public static function getJsonMessagesFileName( $code ) {
4231 global $IP;
4233 if ( !self::isValidBuiltInCode( $code ) ) {
4234 throw new MWException( "Invalid language code \"$code\"" );
4237 return "$IP/languages/i18n/$code.json";
4241 * @param string $code
4242 * @return string
4244 public static function getClassFileName( $code ) {
4245 global $IP;
4246 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4250 * Get the first fallback for a given language.
4252 * @param string $code
4254 * @return bool|string
4256 public static function getFallbackFor( $code ) {
4257 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4258 return false;
4259 } else {
4260 $fallbacks = self::getFallbacksFor( $code );
4261 $first = array_shift( $fallbacks );
4262 return $first;
4267 * Get the ordered list of fallback languages.
4269 * @since 1.19
4270 * @param string $code Language code
4271 * @return array
4273 public static function getFallbacksFor( $code ) {
4274 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4275 return array();
4276 } else {
4277 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4278 $v = array_map( 'trim', explode( ',', $v ) );
4279 if ( $v[count( $v ) - 1] !== 'en' ) {
4280 $v[] = 'en';
4282 return $v;
4287 * Get the ordered list of fallback languages, ending with the fallback
4288 * language chain for the site language.
4290 * @since 1.22
4291 * @param string $code Language code
4292 * @return array Array( fallbacks, site fallbacks )
4294 public static function getFallbacksIncludingSiteLanguage( $code ) {
4295 global $wgLanguageCode;
4297 // Usually, we will only store a tiny number of fallback chains, so we
4298 // keep them in static memory.
4299 $cacheKey = "{$code}-{$wgLanguageCode}";
4301 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4302 $fallbacks = self::getFallbacksFor( $code );
4304 // Append the site's fallback chain, including the site language itself
4305 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4306 array_unshift( $siteFallbacks, $wgLanguageCode );
4308 // Eliminate any languages already included in the chain
4309 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4311 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4313 return self::$fallbackLanguageCache[$cacheKey];
4317 * Get all messages for a given language
4318 * WARNING: this may take a long time. If you just need all message *keys*
4319 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4321 * @param string $code
4323 * @return array
4325 public static function getMessagesFor( $code ) {
4326 return self::getLocalisationCache()->getItem( $code, 'messages' );
4330 * Get a message for a given language
4332 * @param string $key
4333 * @param string $code
4335 * @return string
4337 public static function getMessageFor( $key, $code ) {
4338 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4342 * Get all message keys for a given language. This is a faster alternative to
4343 * array_keys( Language::getMessagesFor( $code ) )
4345 * @since 1.19
4346 * @param string $code Language code
4347 * @return array Array of message keys (strings)
4349 public static function getMessageKeysFor( $code ) {
4350 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4354 * @param string $talk
4355 * @return mixed
4357 function fixVariableInNamespace( $talk ) {
4358 if ( strpos( $talk, '$1' ) === false ) {
4359 return $talk;
4362 global $wgMetaNamespace;
4363 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4365 # Allow grammar transformations
4366 # Allowing full message-style parsing would make simple requests
4367 # such as action=raw much more expensive than they need to be.
4368 # This will hopefully cover most cases.
4369 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4370 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4371 return str_replace( ' ', '_', $talk );
4375 * @param string $m
4376 * @return string
4378 function replaceGrammarInNamespace( $m ) {
4379 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4383 * @throws MWException
4384 * @return array
4386 static function getCaseMaps() {
4387 static $wikiUpperChars, $wikiLowerChars;
4388 if ( isset( $wikiUpperChars ) ) {
4389 return array( $wikiUpperChars, $wikiLowerChars );
4392 wfProfileIn( __METHOD__ );
4393 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4394 if ( $arr === false ) {
4395 throw new MWException(
4396 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4398 $wikiUpperChars = $arr['wikiUpperChars'];
4399 $wikiLowerChars = $arr['wikiLowerChars'];
4400 wfProfileOut( __METHOD__ );
4401 return array( $wikiUpperChars, $wikiLowerChars );
4405 * Decode an expiry (block, protection, etc) which has come from the DB
4407 * @todo FIXME: why are we returnings DBMS-dependent strings???
4409 * @param string $expiry Database expiry String
4410 * @param bool|int $format True to process using language functions, or TS_ constant
4411 * to return the expiry in a given timestamp
4412 * @return string
4413 * @since 1.18
4415 public function formatExpiry( $expiry, $format = true ) {
4416 static $infinity;
4417 if ( $infinity === null ) {
4418 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4421 if ( $expiry == '' || $expiry == $infinity ) {
4422 return $format === true
4423 ? $this->getMessageFromDB( 'infiniteblock' )
4424 : $infinity;
4425 } else {
4426 return $format === true
4427 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4428 : wfTimestamp( $format, $expiry );
4433 * @todo Document
4434 * @param int|float $seconds
4435 * @param array $format Optional
4436 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4437 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4438 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4439 * and friends.
4440 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4441 * or 'avoidminutes'.
4442 * @return string
4444 function formatTimePeriod( $seconds, $format = array() ) {
4445 if ( !is_array( $format ) ) {
4446 $format = array( 'avoid' => $format ); // For backwards compatibility
4448 if ( !isset( $format['avoid'] ) ) {
4449 $format['avoid'] = false;
4451 if ( !isset( $format['noabbrevs'] ) ) {
4452 $format['noabbrevs'] = false;
4454 $secondsMsg = wfMessage(
4455 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4456 $minutesMsg = wfMessage(
4457 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4458 $hoursMsg = wfMessage(
4459 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4460 $daysMsg = wfMessage(
4461 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4463 if ( round( $seconds * 10 ) < 100 ) {
4464 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4465 $s = $secondsMsg->params( $s )->text();
4466 } elseif ( round( $seconds ) < 60 ) {
4467 $s = $this->formatNum( round( $seconds ) );
4468 $s = $secondsMsg->params( $s )->text();
4469 } elseif ( round( $seconds ) < 3600 ) {
4470 $minutes = floor( $seconds / 60 );
4471 $secondsPart = round( fmod( $seconds, 60 ) );
4472 if ( $secondsPart == 60 ) {
4473 $secondsPart = 0;
4474 $minutes++;
4476 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4477 $s .= ' ';
4478 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4479 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4480 $hours = floor( $seconds / 3600 );
4481 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4482 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4483 if ( $secondsPart == 60 ) {
4484 $secondsPart = 0;
4485 $minutes++;
4487 if ( $minutes == 60 ) {
4488 $minutes = 0;
4489 $hours++;
4491 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4492 $s .= ' ';
4493 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4494 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4495 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4497 } else {
4498 $days = floor( $seconds / 86400 );
4499 if ( $format['avoid'] === 'avoidminutes' ) {
4500 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4501 if ( $hours == 24 ) {
4502 $hours = 0;
4503 $days++;
4505 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4506 $s .= ' ';
4507 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4508 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4509 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4510 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4511 if ( $minutes == 60 ) {
4512 $minutes = 0;
4513 $hours++;
4515 if ( $hours == 24 ) {
4516 $hours = 0;
4517 $days++;
4519 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4520 $s .= ' ';
4521 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4522 $s .= ' ';
4523 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4524 } else {
4525 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4526 $s .= ' ';
4527 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4530 return $s;
4534 * Format a bitrate for output, using an appropriate
4535 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4536 * the magnitude in question.
4538 * This use base 1000. For base 1024 use formatSize(), for another base
4539 * see formatComputingNumbers().
4541 * @param int $bps
4542 * @return string
4544 function formatBitrate( $bps ) {
4545 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4549 * @param int $size Size of the unit
4550 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4551 * @param string $messageKey Message key to be uesd
4552 * @return string
4554 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4555 if ( $size <= 0 ) {
4556 return str_replace( '$1', $this->formatNum( $size ),
4557 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4560 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4561 $index = 0;
4563 $maxIndex = count( $sizes ) - 1;
4564 while ( $size >= $boundary && $index < $maxIndex ) {
4565 $index++;
4566 $size /= $boundary;
4569 // For small sizes no decimal places necessary
4570 $round = 0;
4571 if ( $index > 1 ) {
4572 // For MB and bigger two decimal places are smarter
4573 $round = 2;
4575 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4577 $size = round( $size, $round );
4578 $text = $this->getMessageFromDB( $msg );
4579 return str_replace( '$1', $this->formatNum( $size ), $text );
4583 * Format a size in bytes for output, using an appropriate
4584 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4586 * This method use base 1024. For base 1000 use formatBitrate(), for
4587 * another base see formatComputingNumbers()
4589 * @param int $size Size to format
4590 * @return string Plain text (not HTML)
4592 function formatSize( $size ) {
4593 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4597 * Make a list item, used by various special pages
4599 * @param string $page Page link
4600 * @param string $details Text between brackets
4601 * @param bool $oppositedm Add the direction mark opposite to your
4602 * language, to display text properly
4603 * @return string
4605 function specialList( $page, $details, $oppositedm = true ) {
4606 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4607 $this->getDirMark();
4608 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4609 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4610 return $page . $details;
4614 * Generate (prev x| next x) (20|50|100...) type links for paging
4616 * @param Title $title Title object to link
4617 * @param int $offset
4618 * @param int $limit
4619 * @param array $query Optional URL query parameter string
4620 * @param bool $atend Optional param for specified if this is the last page
4621 * @return string
4623 public function viewPrevNext( Title $title, $offset, $limit,
4624 array $query = array(), $atend = false
4626 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4628 # Make 'previous' link
4629 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4630 if ( $offset > 0 ) {
4631 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4632 $query, $prev, 'prevn-title', 'mw-prevlink' );
4633 } else {
4634 $plink = htmlspecialchars( $prev );
4637 # Make 'next' link
4638 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4639 if ( $atend ) {
4640 $nlink = htmlspecialchars( $next );
4641 } else {
4642 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4643 $query, $next, 'nextn-title', 'mw-nextlink' );
4646 # Make links to set number of items per page
4647 $numLinks = array();
4648 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4649 $numLinks[] = $this->numLink( $title, $offset, $num,
4650 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4653 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4654 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4658 * Helper function for viewPrevNext() that generates links
4660 * @param Title $title Title object to link
4661 * @param int $offset
4662 * @param int $limit
4663 * @param array $query Extra query parameters
4664 * @param string $link Text to use for the link; will be escaped
4665 * @param string $tooltipMsg Name of the message to use as tooltip
4666 * @param string $class Value of the "class" attribute of the link
4667 * @return string HTML fragment
4669 private function numLink( Title $title, $offset, $limit, array $query, $link,
4670 $tooltipMsg, $class
4672 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4673 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4674 ->numParams( $limit )->text();
4676 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4677 'title' => $tooltip, 'class' => $class ), $link );
4681 * Get the conversion rule title, if any.
4683 * @return string
4685 public function getConvRuleTitle() {
4686 return $this->mConverter->getConvRuleTitle();
4690 * Get the compiled plural rules for the language
4691 * @since 1.20
4692 * @return array Associative array with plural form, and plural rule as key-value pairs
4694 public function getCompiledPluralRules() {
4695 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4696 $fallbacks = Language::getFallbacksFor( $this->mCode );
4697 if ( !$pluralRules ) {
4698 foreach ( $fallbacks as $fallbackCode ) {
4699 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4700 if ( $pluralRules ) {
4701 break;
4705 return $pluralRules;
4709 * Get the plural rules for the language
4710 * @since 1.20
4711 * @return array Associative array with plural form number and plural rule as key-value pairs
4713 public function getPluralRules() {
4714 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4715 $fallbacks = Language::getFallbacksFor( $this->mCode );
4716 if ( !$pluralRules ) {
4717 foreach ( $fallbacks as $fallbackCode ) {
4718 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4719 if ( $pluralRules ) {
4720 break;
4724 return $pluralRules;
4728 * Get the plural rule types for the language
4729 * @since 1.22
4730 * @return array Associative array with plural form number and plural rule type as key-value pairs
4732 public function getPluralRuleTypes() {
4733 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4734 $fallbacks = Language::getFallbacksFor( $this->mCode );
4735 if ( !$pluralRuleTypes ) {
4736 foreach ( $fallbacks as $fallbackCode ) {
4737 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4738 if ( $pluralRuleTypes ) {
4739 break;
4743 return $pluralRuleTypes;
4747 * Find the index number of the plural rule appropriate for the given number
4748 * @param int $number
4749 * @return int The index number of the plural rule
4751 public function getPluralRuleIndexNumber( $number ) {
4752 $pluralRules = $this->getCompiledPluralRules();
4753 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4754 return $form;
4758 * Find the plural rule type appropriate for the given number
4759 * For example, if the language is set to Arabic, getPluralType(5) should
4760 * return 'few'.
4761 * @since 1.22
4762 * @param int $number
4763 * @return string The name of the plural rule type, e.g. one, two, few, many
4765 public function getPluralRuleType( $number ) {
4766 $index = $this->getPluralRuleIndexNumber( $number );
4767 $pluralRuleTypes = $this->getPluralRuleTypes();
4768 if ( isset( $pluralRuleTypes[$index] ) ) {
4769 return $pluralRuleTypes[$index];
4770 } else {
4771 return 'other';