Remove messages.inc, rebuildLanguage.php, writeMessagesArray.inc
[mediawiki.git] / languages / Language.php
blob38d3af5c8521ec5f9ea2578f14658d095c6794f9
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,}$/i', $code );
346 * Returns true if a language code is an IETF tag known to MediaWiki.
348 * @param string $code
350 * @since 1.21
351 * @return bool
353 public static function isKnownLanguageTag( $tag ) {
354 static $coreLanguageNames;
356 // Quick escape for invalid input to avoid exceptions down the line
357 // when code tries to process tags which are not valid at all.
358 if ( !self::isValidBuiltInCode( $tag ) ) {
359 return false;
362 if ( $coreLanguageNames === null ) {
363 global $IP;
364 include "$IP/languages/Names.php";
367 if ( isset( $coreLanguageNames[$tag] )
368 || self::fetchLanguageName( $tag, $tag ) !== ''
370 return true;
373 return false;
377 * @param string $code
378 * @return string Name of the language class
380 public static function classFromCode( $code ) {
381 if ( $code == 'en' ) {
382 return 'Language';
383 } else {
384 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
389 * Includes language class files
391 * @param string $class Name of the language class
393 public static function preloadLanguageClass( $class ) {
394 global $IP;
396 if ( $class === 'Language' ) {
397 return;
400 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
401 include_once "$IP/languages/classes/$class.php";
406 * Get the LocalisationCache instance
408 * @return LocalisationCache
410 public static function getLocalisationCache() {
411 if ( is_null( self::$dataCache ) ) {
412 global $wgLocalisationCacheConf;
413 $class = $wgLocalisationCacheConf['class'];
414 self::$dataCache = new $class( $wgLocalisationCacheConf );
416 return self::$dataCache;
419 function __construct() {
420 $this->mConverter = new FakeConverter( $this );
421 // Set the code to the name of the descendant
422 if ( get_class( $this ) == 'Language' ) {
423 $this->mCode = 'en';
424 } else {
425 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
427 self::getLocalisationCache();
431 * Reduce memory usage
433 function __destruct() {
434 foreach ( $this as $name => $value ) {
435 unset( $this->$name );
440 * Hook which will be called if this is the content language.
441 * Descendants can use this to register hook functions or modify globals
443 function initContLang() {
447 * Same as getFallbacksFor for current language.
448 * @return array|bool
449 * @deprecated since 1.19
451 function getFallbackLanguageCode() {
452 wfDeprecated( __METHOD__, '1.19' );
454 return self::getFallbackFor( $this->mCode );
458 * @return array
459 * @since 1.19
461 function getFallbackLanguages() {
462 return self::getFallbacksFor( $this->mCode );
466 * Exports $wgBookstoreListEn
467 * @return array
469 function getBookstoreList() {
470 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
474 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
475 * available in localised form, it will be included in English.
477 * @return array
479 public function getNamespaces() {
480 if ( is_null( $this->namespaceNames ) ) {
481 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
483 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
484 $validNamespaces = MWNamespace::getCanonicalNamespaces();
486 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
488 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
489 if ( $wgMetaNamespaceTalk ) {
490 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
491 } else {
492 $talk = $this->namespaceNames[NS_PROJECT_TALK];
493 $this->namespaceNames[NS_PROJECT_TALK] =
494 $this->fixVariableInNamespace( $talk );
497 # Sometimes a language will be localised but not actually exist on this wiki.
498 foreach ( $this->namespaceNames as $key => $text ) {
499 if ( !isset( $validNamespaces[$key] ) ) {
500 unset( $this->namespaceNames[$key] );
504 # The above mixing may leave namespaces out of canonical order.
505 # Re-order by namespace ID number...
506 ksort( $this->namespaceNames );
508 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
511 return $this->namespaceNames;
515 * Arbitrarily set all of the namespace names at once. Mainly used for testing
516 * @param array $namespaces Array of namespaces (id => name)
518 public function setNamespaces( array $namespaces ) {
519 $this->namespaceNames = $namespaces;
520 $this->mNamespaceIds = null;
524 * Resets all of the namespace caches. Mainly used for testing
526 public function resetNamespaces() {
527 $this->namespaceNames = null;
528 $this->mNamespaceIds = null;
529 $this->namespaceAliases = null;
533 * A convenience function that returns the same thing as
534 * getNamespaces() except with the array values changed to ' '
535 * where it found '_', useful for producing output to be displayed
536 * e.g. in <select> forms.
538 * @return array
540 function getFormattedNamespaces() {
541 $ns = $this->getNamespaces();
542 foreach ( $ns as $k => $v ) {
543 $ns[$k] = strtr( $v, '_', ' ' );
545 return $ns;
549 * Get a namespace value by key
550 * <code>
551 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
552 * echo $mw_ns; // prints 'MediaWiki'
553 * </code>
555 * @param int $index The array key of the namespace to return
556 * @return string|bool String if the namespace value exists, otherwise false
558 function getNsText( $index ) {
559 $ns = $this->getNamespaces();
561 return isset( $ns[$index] ) ? $ns[$index] : false;
565 * A convenience function that returns the same thing as
566 * getNsText() except with '_' changed to ' ', useful for
567 * producing output.
569 * <code>
570 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
571 * echo $mw_ns; // prints 'MediaWiki talk'
572 * </code>
574 * @param int $index The array key of the namespace to return
575 * @return string Namespace name without underscores (empty string if namespace does not exist)
577 function getFormattedNsText( $index ) {
578 $ns = $this->getNsText( $index );
580 return strtr( $ns, '_', ' ' );
584 * Returns gender-dependent namespace alias if available.
585 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
586 * @param int $index Namespace index
587 * @param string $gender Gender key (male, female... )
588 * @return string
589 * @since 1.18
591 function getGenderNsText( $index, $gender ) {
592 global $wgExtraGenderNamespaces;
594 $ns = $wgExtraGenderNamespaces +
595 self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
597 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
601 * Whether this language uses gender-dependent namespace aliases.
602 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
603 * @return bool
604 * @since 1.18
606 function needsGenderDistinction() {
607 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
608 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
609 // $wgExtraGenderNamespaces overrides everything
610 return true;
611 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
612 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
613 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
614 return false;
615 } else {
616 // Check what is in i18n files
617 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
618 return count( $aliases ) > 0;
623 * Get a namespace key by value, case insensitive.
624 * Only matches namespace names for the current language, not the
625 * canonical ones defined in Namespace.php.
627 * @param string $text
628 * @return int|bool An integer if $text is a valid value otherwise false
630 function getLocalNsIndex( $text ) {
631 $lctext = $this->lc( $text );
632 $ids = $this->getNamespaceIds();
633 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
637 * @return array
639 function getNamespaceAliases() {
640 if ( is_null( $this->namespaceAliases ) ) {
641 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
642 if ( !$aliases ) {
643 $aliases = array();
644 } else {
645 foreach ( $aliases as $name => $index ) {
646 if ( $index === NS_PROJECT_TALK ) {
647 unset( $aliases[$name] );
648 $name = $this->fixVariableInNamespace( $name );
649 $aliases[$name] = $index;
654 global $wgExtraGenderNamespaces;
655 $genders = $wgExtraGenderNamespaces +
656 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
657 foreach ( $genders as $index => $forms ) {
658 foreach ( $forms as $alias ) {
659 $aliases[$alias] = $index;
663 # Also add converted namespace names as aliases, to avoid confusion.
664 $convertedNames = array();
665 foreach ( $this->getVariants() as $variant ) {
666 if ( $variant === $this->mCode ) {
667 continue;
669 foreach ( $this->getNamespaces() as $ns => $_ ) {
670 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
674 $this->namespaceAliases = $aliases + $convertedNames;
677 return $this->namespaceAliases;
681 * @return array
683 function getNamespaceIds() {
684 if ( is_null( $this->mNamespaceIds ) ) {
685 global $wgNamespaceAliases;
686 # Put namespace names and aliases into a hashtable.
687 # If this is too slow, then we should arrange it so that it is done
688 # before caching. The catch is that at pre-cache time, the above
689 # class-specific fixup hasn't been done.
690 $this->mNamespaceIds = array();
691 foreach ( $this->getNamespaces() as $index => $name ) {
692 $this->mNamespaceIds[$this->lc( $name )] = $index;
694 foreach ( $this->getNamespaceAliases() as $name => $index ) {
695 $this->mNamespaceIds[$this->lc( $name )] = $index;
697 if ( $wgNamespaceAliases ) {
698 foreach ( $wgNamespaceAliases as $name => $index ) {
699 $this->mNamespaceIds[$this->lc( $name )] = $index;
703 return $this->mNamespaceIds;
707 * Get a namespace key by value, case insensitive. Canonical namespace
708 * names override custom ones defined for the current language.
710 * @param string $text
711 * @return int|bool An integer if $text is a valid value otherwise false
713 function getNsIndex( $text ) {
714 $lctext = $this->lc( $text );
715 $ns = MWNamespace::getCanonicalIndex( $lctext );
716 if ( $ns !== null ) {
717 return $ns;
719 $ids = $this->getNamespaceIds();
720 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
724 * short names for language variants used for language conversion links.
726 * @param string $code
727 * @param bool $usemsg Use the "variantname-xyz" message if it exists
728 * @return string
730 function getVariantname( $code, $usemsg = true ) {
731 $msg = "variantname-$code";
732 if ( $usemsg && wfMessage( $msg )->exists() ) {
733 return $this->getMessageFromDB( $msg );
735 $name = self::fetchLanguageName( $code );
736 if ( $name ) {
737 return $name; # if it's defined as a language name, show that
738 } else {
739 # otherwise, output the language code
740 return $code;
745 * @param string $name
746 * @return string
748 function specialPage( $name ) {
749 $aliases = $this->getSpecialPageAliases();
750 if ( isset( $aliases[$name][0] ) ) {
751 $name = $aliases[$name][0];
753 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
757 * @return array
759 function getDatePreferences() {
760 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
764 * @return array
766 function getDateFormats() {
767 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
771 * @return array|string
773 function getDefaultDateFormat() {
774 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
775 if ( $df === 'dmy or mdy' ) {
776 global $wgAmericanDates;
777 return $wgAmericanDates ? 'mdy' : 'dmy';
778 } else {
779 return $df;
784 * @return array
786 function getDatePreferenceMigrationMap() {
787 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
791 * @param string $image
792 * @return array|null
794 function getImageFile( $image ) {
795 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
799 * @return array
801 function getExtraUserToggles() {
802 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
806 * @param string $tog
807 * @return string
809 function getUserToggle( $tog ) {
810 return $this->getMessageFromDB( "tog-$tog" );
814 * Get native language names, indexed by code.
815 * Only those defined in MediaWiki, no other data like CLDR.
816 * If $customisedOnly is true, only returns codes with a messages file
818 * @param bool $customisedOnly
820 * @return array
821 * @deprecated since 1.20, use fetchLanguageNames()
823 public static function getLanguageNames( $customisedOnly = false ) {
824 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
828 * Get translated language names. This is done on best effort and
829 * by default this is exactly the same as Language::getLanguageNames.
830 * The CLDR extension provides translated names.
831 * @param string $code Language code.
832 * @return array Language code => language name
833 * @since 1.18.0
834 * @deprecated since 1.20, use fetchLanguageNames()
836 public static function getTranslatedLanguageNames( $code ) {
837 return self::fetchLanguageNames( $code, 'all' );
841 * Get an array of language names, indexed by code.
842 * @param null|string $inLanguage Code of language in which to return the names
843 * Use null for autonyms (native names)
844 * @param string $include One of:
845 * 'all' all available languages
846 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
847 * 'mwfile' only if the language is in 'mw' *and* has a message file
848 * @return array Language code => language name
849 * @since 1.20
851 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
852 global $wgExtraLanguageNames;
853 static $coreLanguageNames;
855 if ( $coreLanguageNames === null ) {
856 global $IP;
857 include "$IP/languages/Names.php";
860 $names = array();
862 if ( $inLanguage ) {
863 # TODO: also include when $inLanguage is null, when this code is more efficient
864 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
867 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
868 foreach ( $mwNames as $mwCode => $mwName ) {
869 # - Prefer own MediaWiki native name when not using the hook
870 # - For other names just add if not added through the hook
871 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
872 $names[$mwCode] = $mwName;
876 if ( $include === 'all' ) {
877 return $names;
880 $returnMw = array();
881 $coreCodes = array_keys( $mwNames );
882 foreach ( $coreCodes as $coreCode ) {
883 $returnMw[$coreCode] = $names[$coreCode];
886 if ( $include === 'mwfile' ) {
887 $namesMwFile = array();
888 # We do this using a foreach over the codes instead of a directory
889 # loop so that messages files in extensions will work correctly.
890 foreach ( $returnMw as $code => $value ) {
891 if ( is_readable( self::getMessagesFileName( $code ) )
892 || is_readable( self::getJsonMessagesFileName( $code ) )
894 $namesMwFile[$code] = $names[$code];
898 return $namesMwFile;
901 # 'mw' option; default if it's not one of the other two options (all/mwfile)
902 return $returnMw;
906 * @param string $code The code of the language for which to get the name
907 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
908 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
909 * @return string Language name or empty
910 * @since 1.20
912 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
913 $code = strtolower( $code );
914 $array = self::fetchLanguageNames( $inLanguage, $include );
915 return !array_key_exists( $code, $array ) ? '' : $array[$code];
919 * Get a message from the MediaWiki namespace.
921 * @param string $msg Message name
922 * @return string
924 function getMessageFromDB( $msg ) {
925 return wfMessage( $msg )->inLanguage( $this )->text();
929 * Get the native language name of $code.
930 * Only if defined in MediaWiki, no other data like CLDR.
931 * @param string $code
932 * @return string
933 * @deprecated since 1.20, use fetchLanguageName()
935 function getLanguageName( $code ) {
936 return self::fetchLanguageName( $code );
940 * @param string $key
941 * @return string
943 function getMonthName( $key ) {
944 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
948 * @return array
950 function getMonthNamesArray() {
951 $monthNames = array( '' );
952 for ( $i = 1; $i < 13; $i++ ) {
953 $monthNames[] = $this->getMonthName( $i );
955 return $monthNames;
959 * @param string $key
960 * @return string
962 function getMonthNameGen( $key ) {
963 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
967 * @param string $key
968 * @return string
970 function getMonthAbbreviation( $key ) {
971 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
975 * @return array
977 function getMonthAbbreviationsArray() {
978 $monthNames = array( '' );
979 for ( $i = 1; $i < 13; $i++ ) {
980 $monthNames[] = $this->getMonthAbbreviation( $i );
982 return $monthNames;
986 * @param string $key
987 * @return string
989 function getWeekdayName( $key ) {
990 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
994 * @param string $key
995 * @return string
997 function getWeekdayAbbreviation( $key ) {
998 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
1002 * @param string $key
1003 * @return string
1005 function getIranianCalendarMonthName( $key ) {
1006 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1010 * @param string $key
1011 * @return string
1013 function getHebrewCalendarMonthName( $key ) {
1014 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1018 * @param string $key
1019 * @return string
1021 function getHebrewCalendarMonthNameGen( $key ) {
1022 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1026 * @param string $key
1027 * @return string
1029 function getHijriCalendarMonthName( $key ) {
1030 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1034 * This is a workalike of PHP's date() function, but with better
1035 * internationalisation, a reduced set of format characters, and a better
1036 * escaping format.
1038 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1039 * the PHP manual for definitions. There are a number of extensions, which
1040 * start with "x":
1042 * xn Do not translate digits of the next numeric format character
1043 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1044 * xr Use roman numerals for the next numeric format character
1045 * xh Use hebrew numerals for the next numeric format character
1046 * xx Literal x
1047 * xg Genitive month name
1049 * xij j (day number) in Iranian calendar
1050 * xiF F (month name) in Iranian calendar
1051 * xin n (month number) in Iranian calendar
1052 * xiy y (two digit year) in Iranian calendar
1053 * xiY Y (full year) in Iranian calendar
1055 * xjj j (day number) in Hebrew calendar
1056 * xjF F (month name) in Hebrew calendar
1057 * xjt t (days in month) in Hebrew calendar
1058 * xjx xg (genitive month name) in Hebrew calendar
1059 * xjn n (month number) in Hebrew calendar
1060 * xjY Y (full year) in Hebrew calendar
1062 * xmj j (day number) in Hijri calendar
1063 * xmF F (month name) in Hijri calendar
1064 * xmn n (month number) in Hijri calendar
1065 * xmY Y (full year) in Hijri calendar
1067 * xkY Y (full year) in Thai solar calendar. Months and days are
1068 * identical to the Gregorian calendar
1069 * xoY Y (full year) in Minguo calendar or Juche year.
1070 * Months and days are identical to the
1071 * Gregorian calendar
1072 * xtY Y (full year) in Japanese nengo. Months and days are
1073 * identical to the Gregorian calendar
1075 * Characters enclosed in double quotes will be considered literal (with
1076 * the quotes themselves removed). Unmatched quotes will be considered
1077 * literal quotes. Example:
1079 * "The month is" F => The month is January
1080 * i's" => 20'11"
1082 * Backslash escaping is also supported.
1084 * Input timestamp is assumed to be pre-normalized to the desired local
1085 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1086 * $ts is UTC if $zone is not given.
1088 * @param string $format
1089 * @param string $ts 14-character timestamp
1090 * YYYYMMDDHHMMSS
1091 * 01234567890123
1092 * @param DateTimeZone $zone Timezone of $ts
1093 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1095 * @throws MWException
1096 * @return string
1098 function sprintfDate( $format, $ts, DateTimeZone $zone = null ) {
1099 $s = '';
1100 $raw = false;
1101 $roman = false;
1102 $hebrewNum = false;
1103 $dateTimeObj = false;
1104 $rawToggle = false;
1105 $iranian = false;
1106 $hebrew = false;
1107 $hijri = false;
1108 $thai = false;
1109 $minguo = false;
1110 $tenno = false;
1112 if ( strlen( $ts ) !== 14 ) {
1113 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1116 if ( !ctype_digit( $ts ) ) {
1117 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1120 $formatLength = strlen( $format );
1121 for ( $p = 0; $p < $formatLength; $p++ ) {
1122 $num = false;
1123 $code = $format[$p];
1124 if ( $code == 'x' && $p < $formatLength - 1 ) {
1125 $code .= $format[++$p];
1128 if ( ( $code === 'xi'
1129 || $code === 'xj'
1130 || $code === 'xk'
1131 || $code === 'xm'
1132 || $code === 'xo'
1133 || $code === 'xt' )
1134 && $p < $formatLength - 1 ) {
1135 $code .= $format[++$p];
1138 switch ( $code ) {
1139 case 'xx':
1140 $s .= 'x';
1141 break;
1142 case 'xn':
1143 $raw = true;
1144 break;
1145 case 'xN':
1146 $rawToggle = !$rawToggle;
1147 break;
1148 case 'xr':
1149 $roman = true;
1150 break;
1151 case 'xh':
1152 $hebrewNum = true;
1153 break;
1154 case 'xg':
1155 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1156 break;
1157 case 'xjx':
1158 if ( !$hebrew ) {
1159 $hebrew = self::tsToHebrew( $ts );
1161 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1162 break;
1163 case 'd':
1164 $num = substr( $ts, 6, 2 );
1165 break;
1166 case 'D':
1167 if ( !$dateTimeObj ) {
1168 $dateTimeObj = DateTime::createFromFormat(
1169 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1172 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) + 1 );
1173 break;
1174 case 'j':
1175 $num = intval( substr( $ts, 6, 2 ) );
1176 break;
1177 case 'xij':
1178 if ( !$iranian ) {
1179 $iranian = self::tsToIranian( $ts );
1181 $num = $iranian[2];
1182 break;
1183 case 'xmj':
1184 if ( !$hijri ) {
1185 $hijri = self::tsToHijri( $ts );
1187 $num = $hijri[2];
1188 break;
1189 case 'xjj':
1190 if ( !$hebrew ) {
1191 $hebrew = self::tsToHebrew( $ts );
1193 $num = $hebrew[2];
1194 break;
1195 case 'l':
1196 if ( !$dateTimeObj ) {
1197 $dateTimeObj = DateTime::createFromFormat(
1198 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1201 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) + 1 );
1202 break;
1203 case 'F':
1204 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1205 break;
1206 case 'xiF':
1207 if ( !$iranian ) {
1208 $iranian = self::tsToIranian( $ts );
1210 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1211 break;
1212 case 'xmF':
1213 if ( !$hijri ) {
1214 $hijri = self::tsToHijri( $ts );
1216 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1217 break;
1218 case 'xjF':
1219 if ( !$hebrew ) {
1220 $hebrew = self::tsToHebrew( $ts );
1222 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1223 break;
1224 case 'm':
1225 $num = substr( $ts, 4, 2 );
1226 break;
1227 case 'M':
1228 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1229 break;
1230 case 'n':
1231 $num = intval( substr( $ts, 4, 2 ) );
1232 break;
1233 case 'xin':
1234 if ( !$iranian ) {
1235 $iranian = self::tsToIranian( $ts );
1237 $num = $iranian[1];
1238 break;
1239 case 'xmn':
1240 if ( !$hijri ) {
1241 $hijri = self::tsToHijri ( $ts );
1243 $num = $hijri[1];
1244 break;
1245 case 'xjn':
1246 if ( !$hebrew ) {
1247 $hebrew = self::tsToHebrew( $ts );
1249 $num = $hebrew[1];
1250 break;
1251 case 'xjt':
1252 if ( !$hebrew ) {
1253 $hebrew = self::tsToHebrew( $ts );
1255 $num = $hebrew[3];
1256 break;
1257 case 'Y':
1258 $num = substr( $ts, 0, 4 );
1259 break;
1260 case 'xiY':
1261 if ( !$iranian ) {
1262 $iranian = self::tsToIranian( $ts );
1264 $num = $iranian[0];
1265 break;
1266 case 'xmY':
1267 if ( !$hijri ) {
1268 $hijri = self::tsToHijri( $ts );
1270 $num = $hijri[0];
1271 break;
1272 case 'xjY':
1273 if ( !$hebrew ) {
1274 $hebrew = self::tsToHebrew( $ts );
1276 $num = $hebrew[0];
1277 break;
1278 case 'xkY':
1279 if ( !$thai ) {
1280 $thai = self::tsToYear( $ts, 'thai' );
1282 $num = $thai[0];
1283 break;
1284 case 'xoY':
1285 if ( !$minguo ) {
1286 $minguo = self::tsToYear( $ts, 'minguo' );
1288 $num = $minguo[0];
1289 break;
1290 case 'xtY':
1291 if ( !$tenno ) {
1292 $tenno = self::tsToYear( $ts, 'tenno' );
1294 $num = $tenno[0];
1295 break;
1296 case 'y':
1297 $num = substr( $ts, 2, 2 );
1298 break;
1299 case 'xiy':
1300 if ( !$iranian ) {
1301 $iranian = self::tsToIranian( $ts );
1303 $num = substr( $iranian[0], -2 );
1304 break;
1305 case 'a':
1306 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1307 break;
1308 case 'A':
1309 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1310 break;
1311 case 'g':
1312 $h = substr( $ts, 8, 2 );
1313 $num = $h % 12 ? $h % 12 : 12;
1314 break;
1315 case 'G':
1316 $num = intval( substr( $ts, 8, 2 ) );
1317 break;
1318 case 'h':
1319 $h = substr( $ts, 8, 2 );
1320 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1321 break;
1322 case 'H':
1323 $num = substr( $ts, 8, 2 );
1324 break;
1325 case 'i':
1326 $num = substr( $ts, 10, 2 );
1327 break;
1328 case 's':
1329 $num = substr( $ts, 12, 2 );
1330 break;
1331 case 'c':
1332 case 'r':
1333 case 'e':
1334 case 'O':
1335 case 'P':
1336 case 'T':
1337 // Pass through string from $dateTimeObj->format()
1338 if ( !$dateTimeObj ) {
1339 $dateTimeObj = DateTime::createFromFormat(
1340 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1343 $s .= $dateTimeObj->format( $code );
1344 break;
1345 case 'w':
1346 case 'N':
1347 case 'z':
1348 case 'W':
1349 case 't':
1350 case 'L':
1351 case 'o':
1352 case 'U':
1353 case 'I':
1354 case 'Z':
1355 // Pass through number from $dateTimeObj->format()
1356 if ( !$dateTimeObj ) {
1357 $dateTimeObj = DateTime::createFromFormat(
1358 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1361 $num = $dateTimeObj->format( $code );
1362 break;
1363 case '\\':
1364 # Backslash escaping
1365 if ( $p < $formatLength - 1 ) {
1366 $s .= $format[++$p];
1367 } else {
1368 $s .= '\\';
1370 break;
1371 case '"':
1372 # Quoted literal
1373 if ( $p < $formatLength - 1 ) {
1374 $endQuote = strpos( $format, '"', $p + 1 );
1375 if ( $endQuote === false ) {
1376 # No terminating quote, assume literal "
1377 $s .= '"';
1378 } else {
1379 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1380 $p = $endQuote;
1382 } else {
1383 # Quote at end of string, assume literal "
1384 $s .= '"';
1386 break;
1387 default:
1388 $s .= $format[$p];
1390 if ( $num !== false ) {
1391 if ( $rawToggle || $raw ) {
1392 $s .= $num;
1393 $raw = false;
1394 } elseif ( $roman ) {
1395 $s .= Language::romanNumeral( $num );
1396 $roman = false;
1397 } elseif ( $hebrewNum ) {
1398 $s .= self::hebrewNumeral( $num );
1399 $hebrewNum = false;
1400 } else {
1401 $s .= $this->formatNum( $num, true );
1406 return $s;
1409 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1410 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1413 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1414 * Gregorian dates to Iranian dates. Originally written in C, it
1415 * is released under the terms of GNU Lesser General Public
1416 * License. Conversion to PHP was performed by Niklas Laxström.
1418 * Link: http://www.farsiweb.info/jalali/jalali.c
1420 * @param string $ts
1422 * @return string
1424 private static function tsToIranian( $ts ) {
1425 $gy = substr( $ts, 0, 4 ) -1600;
1426 $gm = substr( $ts, 4, 2 ) -1;
1427 $gd = substr( $ts, 6, 2 ) -1;
1429 # Days passed from the beginning (including leap years)
1430 $gDayNo = 365 * $gy
1431 + floor( ( $gy + 3 ) / 4 )
1432 - floor( ( $gy + 99 ) / 100 )
1433 + floor( ( $gy + 399 ) / 400 );
1435 // Add days of the past months of this year
1436 for ( $i = 0; $i < $gm; $i++ ) {
1437 $gDayNo += self::$GREG_DAYS[$i];
1440 // Leap years
1441 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1442 $gDayNo++;
1445 // Days passed in current month
1446 $gDayNo += (int)$gd;
1448 $jDayNo = $gDayNo - 79;
1450 $jNp = floor( $jDayNo / 12053 );
1451 $jDayNo %= 12053;
1453 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1454 $jDayNo %= 1461;
1456 if ( $jDayNo >= 366 ) {
1457 $jy += floor( ( $jDayNo - 1 ) / 365 );
1458 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1461 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1462 $jDayNo -= self::$IRANIAN_DAYS[$i];
1465 $jm = $i + 1;
1466 $jd = $jDayNo + 1;
1468 return array( $jy, $jm, $jd );
1472 * Converting Gregorian dates to Hijri dates.
1474 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1476 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1478 * @param string $ts
1480 * @return string
1482 private static function tsToHijri( $ts ) {
1483 $year = substr( $ts, 0, 4 );
1484 $month = substr( $ts, 4, 2 );
1485 $day = substr( $ts, 6, 2 );
1487 $zyr = $year;
1488 $zd = $day;
1489 $zm = $month;
1490 $zy = $zyr;
1492 if (
1493 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1494 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1496 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1497 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1498 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1499 $zd - 32075;
1500 } else {
1501 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1502 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1505 $zl = $zjd -1948440 + 10632;
1506 $zn = (int)( ( $zl - 1 ) / 10631 );
1507 $zl = $zl - 10631 * $zn + 354;
1508 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1509 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1510 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1511 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1512 $zm = (int)( ( 24 * $zl ) / 709 );
1513 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1514 $zy = 30 * $zn + $zj - 30;
1516 return array( $zy, $zm, $zd );
1520 * Converting Gregorian dates to Hebrew dates.
1522 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1523 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1524 * to translate the relevant functions into PHP and release them under
1525 * GNU GPL.
1527 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1528 * and Adar II is 14. In a non-leap year, Adar is 6.
1530 * @param string $ts
1532 * @return string
1534 private static function tsToHebrew( $ts ) {
1535 # Parse date
1536 $year = substr( $ts, 0, 4 );
1537 $month = substr( $ts, 4, 2 );
1538 $day = substr( $ts, 6, 2 );
1540 # Calculate Hebrew year
1541 $hebrewYear = $year + 3760;
1543 # Month number when September = 1, August = 12
1544 $month += 4;
1545 if ( $month > 12 ) {
1546 # Next year
1547 $month -= 12;
1548 $year++;
1549 $hebrewYear++;
1552 # Calculate day of year from 1 September
1553 $dayOfYear = $day;
1554 for ( $i = 1; $i < $month; $i++ ) {
1555 if ( $i == 6 ) {
1556 # February
1557 $dayOfYear += 28;
1558 # Check if the year is leap
1559 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1560 $dayOfYear++;
1562 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1563 $dayOfYear += 30;
1564 } else {
1565 $dayOfYear += 31;
1569 # Calculate the start of the Hebrew year
1570 $start = self::hebrewYearStart( $hebrewYear );
1572 # Calculate next year's start
1573 if ( $dayOfYear <= $start ) {
1574 # Day is before the start of the year - it is the previous year
1575 # Next year's start
1576 $nextStart = $start;
1577 # Previous year
1578 $year--;
1579 $hebrewYear--;
1580 # Add days since previous year's 1 September
1581 $dayOfYear += 365;
1582 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1583 # Leap year
1584 $dayOfYear++;
1586 # Start of the new (previous) year
1587 $start = self::hebrewYearStart( $hebrewYear );
1588 } else {
1589 # Next year's start
1590 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1593 # Calculate Hebrew day of year
1594 $hebrewDayOfYear = $dayOfYear - $start;
1596 # Difference between year's days
1597 $diff = $nextStart - $start;
1598 # Add 12 (or 13 for leap years) days to ignore the difference between
1599 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1600 # difference is only about the year type
1601 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1602 $diff += 13;
1603 } else {
1604 $diff += 12;
1607 # Check the year pattern, and is leap year
1608 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1609 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1610 # and non-leap years
1611 $yearPattern = $diff % 30;
1612 # Check if leap year
1613 $isLeap = $diff >= 30;
1615 # Calculate day in the month from number of day in the Hebrew year
1616 # Don't check Adar - if the day is not in Adar, we will stop before;
1617 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1618 $hebrewDay = $hebrewDayOfYear;
1619 $hebrewMonth = 1;
1620 $days = 0;
1621 while ( $hebrewMonth <= 12 ) {
1622 # Calculate days in this month
1623 if ( $isLeap && $hebrewMonth == 6 ) {
1624 # Adar in a leap year
1625 if ( $isLeap ) {
1626 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1627 $days = 30;
1628 if ( $hebrewDay <= $days ) {
1629 # Day in Adar I
1630 $hebrewMonth = 13;
1631 } else {
1632 # Subtract the days of Adar I
1633 $hebrewDay -= $days;
1634 # Try Adar II
1635 $days = 29;
1636 if ( $hebrewDay <= $days ) {
1637 # Day in Adar II
1638 $hebrewMonth = 14;
1642 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1643 # Cheshvan in a complete year (otherwise as the rule below)
1644 $days = 30;
1645 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1646 # Kislev in an incomplete year (otherwise as the rule below)
1647 $days = 29;
1648 } else {
1649 # Odd months have 30 days, even have 29
1650 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1652 if ( $hebrewDay <= $days ) {
1653 # In the current month
1654 break;
1655 } else {
1656 # Subtract the days of the current month
1657 $hebrewDay -= $days;
1658 # Try in the next month
1659 $hebrewMonth++;
1663 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1667 * This calculates the Hebrew year start, as days since 1 September.
1668 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1669 * Used for Hebrew date.
1671 * @param int $year
1673 * @return string
1675 private static function hebrewYearStart( $year ) {
1676 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1677 $b = intval( ( $year - 1 ) % 4 );
1678 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1679 if ( $m < 0 ) {
1680 $m--;
1682 $Mar = intval( $m );
1683 if ( $m < 0 ) {
1684 $m++;
1686 $m -= $Mar;
1688 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1689 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1690 $Mar++;
1691 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1692 $Mar += 2;
1693 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1694 $Mar++;
1697 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1698 return $Mar;
1702 * Algorithm to convert Gregorian dates to Thai solar dates,
1703 * Minguo dates or Minguo dates.
1705 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1706 * http://en.wikipedia.org/wiki/Minguo_calendar
1707 * http://en.wikipedia.org/wiki/Japanese_era_name
1709 * @param string $ts 14-character timestamp
1710 * @param string $cName Calender name
1711 * @return array Converted year, month, day
1713 private static function tsToYear( $ts, $cName ) {
1714 $gy = substr( $ts, 0, 4 );
1715 $gm = substr( $ts, 4, 2 );
1716 $gd = substr( $ts, 6, 2 );
1718 if ( !strcmp( $cName, 'thai' ) ) {
1719 # Thai solar dates
1720 # Add 543 years to the Gregorian calendar
1721 # Months and days are identical
1722 $gy_offset = $gy + 543;
1723 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1724 # Minguo dates
1725 # Deduct 1911 years from the Gregorian calendar
1726 # Months and days are identical
1727 $gy_offset = $gy - 1911;
1728 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1729 # Nengō dates up to Meiji period
1730 # Deduct years from the Gregorian calendar
1731 # depending on the nengo periods
1732 # Months and days are identical
1733 if ( ( $gy < 1912 )
1734 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1735 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1737 # Meiji period
1738 $gy_gannen = $gy - 1868 + 1;
1739 $gy_offset = $gy_gannen;
1740 if ( $gy_gannen == 1 ) {
1741 $gy_offset = '元';
1743 $gy_offset = '明治' . $gy_offset;
1744 } elseif (
1745 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1746 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1747 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1748 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1749 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1751 # Taishō period
1752 $gy_gannen = $gy - 1912 + 1;
1753 $gy_offset = $gy_gannen;
1754 if ( $gy_gannen == 1 ) {
1755 $gy_offset = '元';
1757 $gy_offset = '大正' . $gy_offset;
1758 } elseif (
1759 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1760 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1761 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1763 # Shōwa period
1764 $gy_gannen = $gy - 1926 + 1;
1765 $gy_offset = $gy_gannen;
1766 if ( $gy_gannen == 1 ) {
1767 $gy_offset = '元';
1769 $gy_offset = '昭和' . $gy_offset;
1770 } else {
1771 # Heisei period
1772 $gy_gannen = $gy - 1989 + 1;
1773 $gy_offset = $gy_gannen;
1774 if ( $gy_gannen == 1 ) {
1775 $gy_offset = '元';
1777 $gy_offset = '平成' . $gy_offset;
1779 } else {
1780 $gy_offset = $gy;
1783 return array( $gy_offset, $gm, $gd );
1787 * Roman number formatting up to 10000
1789 * @param int $num
1791 * @return string
1793 static function romanNumeral( $num ) {
1794 static $table = array(
1795 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1796 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1797 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1798 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1799 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1802 $num = intval( $num );
1803 if ( $num > 10000 || $num <= 0 ) {
1804 return $num;
1807 $s = '';
1808 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1809 if ( $num >= $pow10 ) {
1810 $s .= $table[$i][(int)floor( $num / $pow10 )];
1812 $num = $num % $pow10;
1814 return $s;
1818 * Hebrew Gematria number formatting up to 9999
1820 * @param int $num
1822 * @return string
1824 static function hebrewNumeral( $num ) {
1825 static $table = array(
1826 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1827 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1828 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1829 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1832 $num = intval( $num );
1833 if ( $num > 9999 || $num <= 0 ) {
1834 return $num;
1837 $s = '';
1838 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1839 if ( $num >= $pow10 ) {
1840 if ( $num == 15 || $num == 16 ) {
1841 $s .= $table[0][9] . $table[0][$num - 9];
1842 $num = 0;
1843 } else {
1844 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1845 if ( $pow10 == 1000 ) {
1846 $s .= "'";
1850 $num = $num % $pow10;
1852 if ( strlen( $s ) == 2 ) {
1853 $str = $s . "'";
1854 } else {
1855 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1856 $str .= substr( $s, strlen( $s ) - 2, 2 );
1858 $start = substr( $str, 0, strlen( $str ) - 2 );
1859 $end = substr( $str, strlen( $str ) - 2 );
1860 switch ( $end ) {
1861 case 'כ':
1862 $str = $start . 'ך';
1863 break;
1864 case 'מ':
1865 $str = $start . 'ם';
1866 break;
1867 case 'נ':
1868 $str = $start . 'ן';
1869 break;
1870 case 'פ':
1871 $str = $start . 'ף';
1872 break;
1873 case 'צ':
1874 $str = $start . 'ץ';
1875 break;
1877 return $str;
1881 * Used by date() and time() to adjust the time output.
1883 * @param int $ts The time in date('YmdHis') format
1884 * @param mixed $tz Adjust the time by this amount (default false, mean we
1885 * get user timecorrection setting)
1886 * @return int
1888 function userAdjust( $ts, $tz = false ) {
1889 global $wgUser, $wgLocalTZoffset;
1891 if ( $tz === false ) {
1892 $tz = $wgUser->getOption( 'timecorrection' );
1895 $data = explode( '|', $tz, 3 );
1897 if ( $data[0] == 'ZoneInfo' ) {
1898 wfSuppressWarnings();
1899 $userTZ = timezone_open( $data[2] );
1900 wfRestoreWarnings();
1901 if ( $userTZ !== false ) {
1902 $date = date_create( $ts, timezone_open( 'UTC' ) );
1903 date_timezone_set( $date, $userTZ );
1904 $date = date_format( $date, 'YmdHis' );
1905 return $date;
1907 # Unrecognized timezone, default to 'Offset' with the stored offset.
1908 $data[0] = 'Offset';
1911 if ( $data[0] == 'System' || $tz == '' ) {
1912 # Global offset in minutes.
1913 $minDiff = $wgLocalTZoffset;
1914 } elseif ( $data[0] == 'Offset' ) {
1915 $minDiff = intval( $data[1] );
1916 } else {
1917 $data = explode( ':', $tz );
1918 if ( count( $data ) == 2 ) {
1919 $data[0] = intval( $data[0] );
1920 $data[1] = intval( $data[1] );
1921 $minDiff = abs( $data[0] ) * 60 + $data[1];
1922 if ( $data[0] < 0 ) {
1923 $minDiff = -$minDiff;
1925 } else {
1926 $minDiff = intval( $data[0] ) * 60;
1930 # No difference ? Return time unchanged
1931 if ( 0 == $minDiff ) {
1932 return $ts;
1935 wfSuppressWarnings(); // E_STRICT system time bitching
1936 # Generate an adjusted date; take advantage of the fact that mktime
1937 # will normalize out-of-range values so we don't have to split $minDiff
1938 # into hours and minutes.
1939 $t = mktime( (
1940 (int)substr( $ts, 8, 2 ) ), # Hours
1941 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1942 (int)substr( $ts, 12, 2 ), # Seconds
1943 (int)substr( $ts, 4, 2 ), # Month
1944 (int)substr( $ts, 6, 2 ), # Day
1945 (int)substr( $ts, 0, 4 ) ); # Year
1947 $date = date( 'YmdHis', $t );
1948 wfRestoreWarnings();
1950 return $date;
1954 * This is meant to be used by time(), date(), and timeanddate() to get
1955 * the date preference they're supposed to use, it should be used in
1956 * all children.
1958 *<code>
1959 * function timeanddate([...], $format = true) {
1960 * $datePreference = $this->dateFormat($format);
1961 * [...]
1963 *</code>
1965 * @param int|string|bool $usePrefs If true, the user's preference is used
1966 * if false, the site/language default is used
1967 * if int/string, assumed to be a format.
1968 * @return string
1970 function dateFormat( $usePrefs = true ) {
1971 global $wgUser;
1973 if ( is_bool( $usePrefs ) ) {
1974 if ( $usePrefs ) {
1975 $datePreference = $wgUser->getDatePreference();
1976 } else {
1977 $datePreference = (string)User::getDefaultOption( 'date' );
1979 } else {
1980 $datePreference = (string)$usePrefs;
1983 // return int
1984 if ( $datePreference == '' ) {
1985 return 'default';
1988 return $datePreference;
1992 * Get a format string for a given type and preference
1993 * @param string $type May be date, time or both
1994 * @param string $pref The format name as it appears in Messages*.php
1996 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1998 * @return string
2000 function getDateFormatString( $type, $pref ) {
2001 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2002 if ( $pref == 'default' ) {
2003 $pref = $this->getDefaultDateFormat();
2004 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2005 } else {
2006 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2008 if ( $type === 'pretty' && $df === null ) {
2009 $df = $this->getDateFormatString( 'date', $pref );
2012 if ( $df === null ) {
2013 $pref = $this->getDefaultDateFormat();
2014 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2017 $this->dateFormatStrings[$type][$pref] = $df;
2019 return $this->dateFormatStrings[$type][$pref];
2023 * @param mixed $ts The time format which needs to be turned into a
2024 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2025 * @param bool $adj Whether to adjust the time output according to the
2026 * user configured offset ($timecorrection)
2027 * @param mixed $format True to use user's date format preference
2028 * @param string|bool $timecorrection The time offset as returned by
2029 * validateTimeZone() in Special:Preferences
2030 * @return string
2032 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2033 $ts = wfTimestamp( TS_MW, $ts );
2034 if ( $adj ) {
2035 $ts = $this->userAdjust( $ts, $timecorrection );
2037 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2038 return $this->sprintfDate( $df, $ts );
2042 * @param mixed $ts The time format which needs to be turned into a
2043 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2044 * @param bool $adj Whether to adjust the time output according to the
2045 * user configured offset ($timecorrection)
2046 * @param mixed $format True to use user's date format preference
2047 * @param string|bool $timecorrection The time offset as returned by
2048 * validateTimeZone() in Special:Preferences
2049 * @return string
2051 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2052 $ts = wfTimestamp( TS_MW, $ts );
2053 if ( $adj ) {
2054 $ts = $this->userAdjust( $ts, $timecorrection );
2056 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2057 return $this->sprintfDate( $df, $ts );
2061 * @param mixed $ts The time format which needs to be turned into a
2062 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2063 * @param bool $adj Whether to adjust the time output according to the
2064 * user configured offset ($timecorrection)
2065 * @param mixed $format What format to return, if it's false output the
2066 * default one (default true)
2067 * @param string|bool $timecorrection The time offset as returned by
2068 * validateTimeZone() in Special:Preferences
2069 * @return string
2071 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2072 $ts = wfTimestamp( TS_MW, $ts );
2073 if ( $adj ) {
2074 $ts = $this->userAdjust( $ts, $timecorrection );
2076 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2077 return $this->sprintfDate( $df, $ts );
2081 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2083 * @since 1.20
2085 * @param int $seconds The amount of seconds.
2086 * @param array $chosenIntervals The intervals to enable.
2088 * @return string
2090 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2091 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2093 $segments = array();
2095 foreach ( $intervals as $intervalName => $intervalValue ) {
2096 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2097 // duration-years, duration-decades, duration-centuries, duration-millennia
2098 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2099 $segments[] = $message->inLanguage( $this )->escaped();
2102 return $this->listToText( $segments );
2106 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2107 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2109 * @since 1.20
2111 * @param int $seconds The amount of seconds.
2112 * @param array $chosenIntervals The intervals to enable.
2114 * @return array
2116 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2117 if ( empty( $chosenIntervals ) ) {
2118 $chosenIntervals = array(
2119 'millennia',
2120 'centuries',
2121 'decades',
2122 'years',
2123 'days',
2124 'hours',
2125 'minutes',
2126 'seconds'
2130 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2131 $sortedNames = array_keys( $intervals );
2132 $smallestInterval = array_pop( $sortedNames );
2134 $segments = array();
2136 foreach ( $intervals as $name => $length ) {
2137 $value = floor( $seconds / $length );
2139 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2140 $seconds -= $value * $length;
2141 $segments[$name] = $value;
2145 return $segments;
2149 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2151 * @param string $type Can be 'date', 'time' or 'both'
2152 * @param mixed $ts The time format which needs to be turned into a
2153 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2154 * @param User $user User object used to get preferences for timezone and format
2155 * @param array $options Array, can contain the following keys:
2156 * - 'timecorrection': time correction, can have the following values:
2157 * - true: use user's preference
2158 * - false: don't use time correction
2159 * - int: value of time correction in minutes
2160 * - 'format': format to use, can have the following values:
2161 * - true: use user's preference
2162 * - false: use default preference
2163 * - string: format to use
2164 * @since 1.19
2165 * @return string
2167 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2168 $ts = wfTimestamp( TS_MW, $ts );
2169 $options += array( 'timecorrection' => true, 'format' => true );
2170 if ( $options['timecorrection'] !== false ) {
2171 if ( $options['timecorrection'] === true ) {
2172 $offset = $user->getOption( 'timecorrection' );
2173 } else {
2174 $offset = $options['timecorrection'];
2176 $ts = $this->userAdjust( $ts, $offset );
2178 if ( $options['format'] === true ) {
2179 $format = $user->getDatePreference();
2180 } else {
2181 $format = $options['format'];
2183 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2184 return $this->sprintfDate( $df, $ts );
2188 * Get the formatted date for the given timestamp and formatted for
2189 * the given user.
2191 * @param mixed $ts Mixed: the time format which needs to be turned into a
2192 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2193 * @param User $user User object used to get preferences for timezone and format
2194 * @param array $options Array, can contain the following keys:
2195 * - 'timecorrection': time correction, can have the following values:
2196 * - true: use user's preference
2197 * - false: don't use time correction
2198 * - int: value of time correction in minutes
2199 * - 'format': format to use, can have the following values:
2200 * - true: use user's preference
2201 * - false: use default preference
2202 * - string: format to use
2203 * @since 1.19
2204 * @return string
2206 public function userDate( $ts, User $user, array $options = array() ) {
2207 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2211 * Get the formatted time for the given timestamp and formatted for
2212 * the given user.
2214 * @param mixed $ts The time format which needs to be turned into a
2215 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2216 * @param User $user User object used to get preferences for timezone and format
2217 * @param array $options Array, can contain the following keys:
2218 * - 'timecorrection': time correction, can have the following values:
2219 * - true: use user's preference
2220 * - false: don't use time correction
2221 * - int: value of time correction in minutes
2222 * - 'format': format to use, can have the following values:
2223 * - true: use user's preference
2224 * - false: use default preference
2225 * - string: format to use
2226 * @since 1.19
2227 * @return string
2229 public function userTime( $ts, User $user, array $options = array() ) {
2230 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2234 * Get the formatted date and time for the given timestamp and formatted for
2235 * the given user.
2237 * @param mixed $ts the time format which needs to be turned into a
2238 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2239 * @param User $user User object used to get preferences for timezone and format
2240 * @param array $options Array, can contain the following keys:
2241 * - 'timecorrection': time correction, can have the following values:
2242 * - true: use user's preference
2243 * - false: don't use time correction
2244 * - int: value of time correction in minutes
2245 * - 'format': format to use, can have the following values:
2246 * - true: use user's preference
2247 * - false: use default preference
2248 * - string: format to use
2249 * @since 1.19
2250 * @return string
2252 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2253 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2257 * Convert an MWTimestamp into a pretty human-readable timestamp using
2258 * the given user preferences and relative base time.
2260 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2261 * on your timestamp object, which will then call this function. Calling
2262 * this function directly will cause hooks to be skipped over.
2264 * @see MWTimestamp::getHumanTimestamp
2265 * @param MWTimestamp $ts Timestamp to prettify
2266 * @param MWTimestamp $relativeTo Base timestamp
2267 * @param User $user User preferences to use
2268 * @return string Human timestamp
2269 * @since 1.22
2271 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2272 $diff = $ts->diff( $relativeTo );
2273 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2274 (int)$relativeTo->timestamp->format( 'w' ) );
2275 $days = $diff->days ?: (int)$diffDay;
2276 if ( $diff->invert || $days > 5
2277 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2279 // Timestamps are in different years: use full timestamp
2280 // Also do full timestamp for future dates
2282 * @FIXME Add better handling of future timestamps.
2284 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2285 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2286 } elseif ( $days > 5 ) {
2287 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2288 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2289 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2290 } elseif ( $days > 1 ) {
2291 // Timestamp within the past week: show the day of the week and time
2292 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2293 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2294 // Messages:
2295 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2296 $ts = wfMessage( "$weekday-at" )
2297 ->inLanguage( $this )
2298 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2299 ->text();
2300 } elseif ( $days == 1 ) {
2301 // Timestamp was yesterday: say 'yesterday' and the time.
2302 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2303 $ts = wfMessage( 'yesterday-at' )
2304 ->inLanguage( $this )
2305 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2306 ->text();
2307 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2308 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2309 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2310 $ts = wfMessage( 'today-at' )
2311 ->inLanguage( $this )
2312 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2313 ->text();
2315 // From here on in, the timestamp was soon enough ago so that we can simply say
2316 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2317 } elseif ( $diff->h == 1 ) {
2318 // Less than 90 minutes, but more than an hour ago.
2319 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2320 } elseif ( $diff->i >= 1 ) {
2321 // A few minutes ago.
2322 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2323 } elseif ( $diff->s >= 30 ) {
2324 // Less than a minute, but more than 30 sec ago.
2325 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2326 } else {
2327 // Less than 30 seconds ago.
2328 $ts = wfMessage( 'just-now' )->text();
2331 return $ts;
2335 * @param string $key
2336 * @return array|null
2338 function getMessage( $key ) {
2339 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2343 * @return array
2345 function getAllMessages() {
2346 return self::$dataCache->getItem( $this->mCode, 'messages' );
2350 * @param string $in
2351 * @param string $out
2352 * @param string $string
2353 * @return string
2355 function iconv( $in, $out, $string ) {
2356 # This is a wrapper for iconv in all languages except esperanto,
2357 # which does some nasty x-conversions beforehand
2359 # Even with //IGNORE iconv can whine about illegal characters in
2360 # *input* string. We just ignore those too.
2361 # REF: http://bugs.php.net/bug.php?id=37166
2362 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2363 wfSuppressWarnings();
2364 $text = iconv( $in, $out . '//IGNORE', $string );
2365 wfRestoreWarnings();
2366 return $text;
2369 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2372 * @param array $matches
2373 * @return mixed|string
2375 function ucwordbreaksCallbackAscii( $matches ) {
2376 return $this->ucfirst( $matches[1] );
2380 * @param array $matches
2381 * @return string
2383 function ucwordbreaksCallbackMB( $matches ) {
2384 return mb_strtoupper( $matches[0] );
2388 * @param array $matches
2389 * @return string
2391 function ucCallback( $matches ) {
2392 list( $wikiUpperChars ) = self::getCaseMaps();
2393 return strtr( $matches[1], $wikiUpperChars );
2397 * @param array $matches
2398 * @return string
2400 function lcCallback( $matches ) {
2401 list( , $wikiLowerChars ) = self::getCaseMaps();
2402 return strtr( $matches[1], $wikiLowerChars );
2406 * @param array $matches
2407 * @return string
2409 function ucwordsCallbackMB( $matches ) {
2410 return mb_strtoupper( $matches[0] );
2414 * @param array $matches
2415 * @return string
2417 function ucwordsCallbackWiki( $matches ) {
2418 list( $wikiUpperChars ) = self::getCaseMaps();
2419 return strtr( $matches[0], $wikiUpperChars );
2423 * Make a string's first character uppercase
2425 * @param string $str
2427 * @return string
2429 function ucfirst( $str ) {
2430 $o = ord( $str );
2431 if ( $o < 96 ) { // if already uppercase...
2432 return $str;
2433 } elseif ( $o < 128 ) {
2434 return ucfirst( $str ); // use PHP's ucfirst()
2435 } else {
2436 // fall back to more complex logic in case of multibyte strings
2437 return $this->uc( $str, true );
2442 * Convert a string to uppercase
2444 * @param string $str
2445 * @param bool $first
2447 * @return string
2449 function uc( $str, $first = false ) {
2450 if ( function_exists( 'mb_strtoupper' ) ) {
2451 if ( $first ) {
2452 if ( $this->isMultibyte( $str ) ) {
2453 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2454 } else {
2455 return ucfirst( $str );
2457 } else {
2458 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2460 } else {
2461 if ( $this->isMultibyte( $str ) ) {
2462 $x = $first ? '^' : '';
2463 return preg_replace_callback(
2464 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2465 array( $this, 'ucCallback' ),
2466 $str
2468 } else {
2469 return $first ? ucfirst( $str ) : strtoupper( $str );
2475 * @param string $str
2476 * @return mixed|string
2478 function lcfirst( $str ) {
2479 $o = ord( $str );
2480 if ( !$o ) {
2481 return strval( $str );
2482 } elseif ( $o >= 128 ) {
2483 return $this->lc( $str, true );
2484 } elseif ( $o > 96 ) {
2485 return $str;
2486 } else {
2487 $str[0] = strtolower( $str[0] );
2488 return $str;
2493 * @param string $str
2494 * @param bool $first
2495 * @return mixed|string
2497 function lc( $str, $first = false ) {
2498 if ( function_exists( 'mb_strtolower' ) ) {
2499 if ( $first ) {
2500 if ( $this->isMultibyte( $str ) ) {
2501 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2502 } else {
2503 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2505 } else {
2506 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2508 } else {
2509 if ( $this->isMultibyte( $str ) ) {
2510 $x = $first ? '^' : '';
2511 return preg_replace_callback(
2512 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2513 array( $this, 'lcCallback' ),
2514 $str
2516 } else {
2517 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2523 * @param string $str
2524 * @return bool
2526 function isMultibyte( $str ) {
2527 return (bool)preg_match( '/[\x80-\xff]/', $str );
2531 * @param string $str
2532 * @return mixed|string
2534 function ucwords( $str ) {
2535 if ( $this->isMultibyte( $str ) ) {
2536 $str = $this->lc( $str );
2538 // regexp to find first letter in each word (i.e. after each space)
2539 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2541 // function to use to capitalize a single char
2542 if ( function_exists( 'mb_strtoupper' ) ) {
2543 return preg_replace_callback(
2544 $replaceRegexp,
2545 array( $this, 'ucwordsCallbackMB' ),
2546 $str
2548 } else {
2549 return preg_replace_callback(
2550 $replaceRegexp,
2551 array( $this, 'ucwordsCallbackWiki' ),
2552 $str
2555 } else {
2556 return ucwords( strtolower( $str ) );
2561 * capitalize words at word breaks
2563 * @param string $str
2564 * @return mixed
2566 function ucwordbreaks( $str ) {
2567 if ( $this->isMultibyte( $str ) ) {
2568 $str = $this->lc( $str );
2570 // since \b doesn't work for UTF-8, we explicitely define word break chars
2571 $breaks = "[ \-\(\)\}\{\.,\?!]";
2573 // find first letter after word break
2574 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2575 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2577 if ( function_exists( 'mb_strtoupper' ) ) {
2578 return preg_replace_callback(
2579 $replaceRegexp,
2580 array( $this, 'ucwordbreaksCallbackMB' ),
2581 $str
2583 } else {
2584 return preg_replace_callback(
2585 $replaceRegexp,
2586 array( $this, 'ucwordsCallbackWiki' ),
2587 $str
2590 } else {
2591 return preg_replace_callback(
2592 '/\b([\w\x80-\xff]+)\b/',
2593 array( $this, 'ucwordbreaksCallbackAscii' ),
2594 $str
2600 * Return a case-folded representation of $s
2602 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2603 * and $s2 are the same except for the case of their characters. It is not
2604 * necessary for the value returned to make sense when displayed.
2606 * Do *not* perform any other normalisation in this function. If a caller
2607 * uses this function when it should be using a more general normalisation
2608 * function, then fix the caller.
2610 * @param string $s
2612 * @return string
2614 function caseFold( $s ) {
2615 return $this->uc( $s );
2619 * @param string $s
2620 * @return string
2622 function checkTitleEncoding( $s ) {
2623 if ( is_array( $s ) ) {
2624 throw new MWException( 'Given array to checkTitleEncoding.' );
2626 if ( StringUtils::isUtf8( $s ) ) {
2627 return $s;
2630 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2634 * @return array
2636 function fallback8bitEncoding() {
2637 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2641 * Most writing systems use whitespace to break up words.
2642 * Some languages such as Chinese don't conventionally do this,
2643 * which requires special handling when breaking up words for
2644 * searching etc.
2646 * @return bool
2648 function hasWordBreaks() {
2649 return true;
2653 * Some languages such as Chinese require word segmentation,
2654 * Specify such segmentation when overridden in derived class.
2656 * @param string $string
2657 * @return string
2659 function segmentByWord( $string ) {
2660 return $string;
2664 * Some languages have special punctuation need to be normalized.
2665 * Make such changes here.
2667 * @param string $string
2668 * @return string
2670 function normalizeForSearch( $string ) {
2671 return self::convertDoubleWidth( $string );
2675 * convert double-width roman characters to single-width.
2676 * range: ff00-ff5f ~= 0020-007f
2678 * @param string $string
2680 * @return string
2682 protected static function convertDoubleWidth( $string ) {
2683 static $full = null;
2684 static $half = null;
2686 if ( $full === null ) {
2687 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2688 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2689 $full = str_split( $fullWidth, 3 );
2690 $half = str_split( $halfWidth );
2693 $string = str_replace( $full, $half, $string );
2694 return $string;
2698 * @param string $string
2699 * @param string $pattern
2700 * @return string
2702 protected static function insertSpace( $string, $pattern ) {
2703 $string = preg_replace( $pattern, " $1 ", $string );
2704 $string = preg_replace( '/ +/', ' ', $string );
2705 return $string;
2709 * @param array $termsArray
2710 * @return array
2712 function convertForSearchResult( $termsArray ) {
2713 # some languages, e.g. Chinese, need to do a conversion
2714 # in order for search results to be displayed correctly
2715 return $termsArray;
2719 * Get the first character of a string.
2721 * @param string $s
2722 * @return string
2724 function firstChar( $s ) {
2725 $matches = array();
2726 preg_match(
2727 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2728 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2730 $matches
2733 if ( isset( $matches[1] ) ) {
2734 if ( strlen( $matches[1] ) != 3 ) {
2735 return $matches[1];
2738 // Break down Hangul syllables to grab the first jamo
2739 $code = utf8ToCodepoint( $matches[1] );
2740 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2741 return $matches[1];
2742 } elseif ( $code < 0xb098 ) {
2743 return "\xe3\x84\xb1";
2744 } elseif ( $code < 0xb2e4 ) {
2745 return "\xe3\x84\xb4";
2746 } elseif ( $code < 0xb77c ) {
2747 return "\xe3\x84\xb7";
2748 } elseif ( $code < 0xb9c8 ) {
2749 return "\xe3\x84\xb9";
2750 } elseif ( $code < 0xbc14 ) {
2751 return "\xe3\x85\x81";
2752 } elseif ( $code < 0xc0ac ) {
2753 return "\xe3\x85\x82";
2754 } elseif ( $code < 0xc544 ) {
2755 return "\xe3\x85\x85";
2756 } elseif ( $code < 0xc790 ) {
2757 return "\xe3\x85\x87";
2758 } elseif ( $code < 0xcc28 ) {
2759 return "\xe3\x85\x88";
2760 } elseif ( $code < 0xce74 ) {
2761 return "\xe3\x85\x8a";
2762 } elseif ( $code < 0xd0c0 ) {
2763 return "\xe3\x85\x8b";
2764 } elseif ( $code < 0xd30c ) {
2765 return "\xe3\x85\x8c";
2766 } elseif ( $code < 0xd558 ) {
2767 return "\xe3\x85\x8d";
2768 } else {
2769 return "\xe3\x85\x8e";
2771 } else {
2772 return '';
2776 function initEncoding() {
2777 # Some languages may have an alternate char encoding option
2778 # (Esperanto X-coding, Japanese furigana conversion, etc)
2779 # If this language is used as the primary content language,
2780 # an override to the defaults can be set here on startup.
2784 * @param string $s
2785 * @return string
2787 function recodeForEdit( $s ) {
2788 # For some languages we'll want to explicitly specify
2789 # which characters make it into the edit box raw
2790 # or are converted in some way or another.
2791 global $wgEditEncoding;
2792 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2793 return $s;
2794 } else {
2795 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2800 * @param string $s
2801 * @return string
2803 function recodeInput( $s ) {
2804 # Take the previous into account.
2805 global $wgEditEncoding;
2806 if ( $wgEditEncoding != '' ) {
2807 $enc = $wgEditEncoding;
2808 } else {
2809 $enc = 'UTF-8';
2811 if ( $enc == 'UTF-8' ) {
2812 return $s;
2813 } else {
2814 return $this->iconv( $enc, 'UTF-8', $s );
2819 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2820 * also cleans up certain backwards-compatible sequences, converting them
2821 * to the modern Unicode equivalent.
2823 * This is language-specific for performance reasons only.
2825 * @param string $s
2827 * @return string
2829 function normalize( $s ) {
2830 global $wgAllUnicodeFixes;
2831 $s = UtfNormal::cleanUp( $s );
2832 if ( $wgAllUnicodeFixes ) {
2833 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2834 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2837 return $s;
2841 * Transform a string using serialized data stored in the given file (which
2842 * must be in the serialized subdirectory of $IP). The file contains pairs
2843 * mapping source characters to destination characters.
2845 * The data is cached in process memory. This will go faster if you have the
2846 * FastStringSearch extension.
2848 * @param string $file
2849 * @param string $string
2851 * @throws MWException
2852 * @return string
2854 function transformUsingPairFile( $file, $string ) {
2855 if ( !isset( $this->transformData[$file] ) ) {
2856 $data = wfGetPrecompiledData( $file );
2857 if ( $data === false ) {
2858 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2860 $this->transformData[$file] = new ReplacementArray( $data );
2862 return $this->transformData[$file]->replace( $string );
2866 * For right-to-left language support
2868 * @return bool
2870 function isRTL() {
2871 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2875 * Return the correct HTML 'dir' attribute value for this language.
2876 * @return string
2878 function getDir() {
2879 return $this->isRTL() ? 'rtl' : 'ltr';
2883 * Return 'left' or 'right' as appropriate alignment for line-start
2884 * for this language's text direction.
2886 * Should be equivalent to CSS3 'start' text-align value....
2888 * @return string
2890 function alignStart() {
2891 return $this->isRTL() ? 'right' : 'left';
2895 * Return 'right' or 'left' as appropriate alignment for line-end
2896 * for this language's text direction.
2898 * Should be equivalent to CSS3 'end' text-align value....
2900 * @return string
2902 function alignEnd() {
2903 return $this->isRTL() ? 'left' : 'right';
2907 * A hidden direction mark (LRM or RLM), depending on the language direction.
2908 * Unlike getDirMark(), this function returns the character as an HTML entity.
2909 * This function should be used when the output is guaranteed to be HTML,
2910 * because it makes the output HTML source code more readable. When
2911 * the output is plain text or can be escaped, getDirMark() should be used.
2913 * @param bool $opposite Get the direction mark opposite to your language
2914 * @return string
2915 * @since 1.20
2917 function getDirMarkEntity( $opposite = false ) {
2918 if ( $opposite ) {
2919 return $this->isRTL() ? '&lrm;' : '&rlm;';
2921 return $this->isRTL() ? '&rlm;' : '&lrm;';
2925 * A hidden direction mark (LRM or RLM), depending on the language direction.
2926 * This function produces them as invisible Unicode characters and
2927 * the output may be hard to read and debug, so it should only be used
2928 * when the output is plain text or can be escaped. When the output is
2929 * HTML, use getDirMarkEntity() instead.
2931 * @param bool $opposite Get the direction mark opposite to your language
2932 * @return string
2934 function getDirMark( $opposite = false ) {
2935 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2936 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2937 if ( $opposite ) {
2938 return $this->isRTL() ? $lrm : $rlm;
2940 return $this->isRTL() ? $rlm : $lrm;
2944 * @return array
2946 function capitalizeAllNouns() {
2947 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2951 * An arrow, depending on the language direction.
2953 * @param string $direction The direction of the arrow: forwards (default),
2954 * backwards, left, right, up, down.
2955 * @return string
2957 function getArrow( $direction = 'forwards' ) {
2958 switch ( $direction ) {
2959 case 'forwards':
2960 return $this->isRTL() ? '←' : '→';
2961 case 'backwards':
2962 return $this->isRTL() ? '→' : '←';
2963 case 'left':
2964 return '←';
2965 case 'right':
2966 return '→';
2967 case 'up':
2968 return '↑';
2969 case 'down':
2970 return '↓';
2975 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2977 * @return bool
2979 function linkPrefixExtension() {
2980 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2984 * Get all magic words from cache.
2985 * @return array
2987 function getMagicWords() {
2988 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2992 * Run the LanguageGetMagic hook once.
2994 protected function doMagicHook() {
2995 if ( $this->mMagicHookDone ) {
2996 return;
2998 $this->mMagicHookDone = true;
2999 wfProfileIn( 'LanguageGetMagic' );
3000 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3001 wfProfileOut( 'LanguageGetMagic' );
3005 * Fill a MagicWord object with data from here
3007 * @param MagicWord $mw
3009 function getMagic( $mw ) {
3010 // Saves a function call
3011 if ( ! $this->mMagicHookDone ) {
3012 $this->doMagicHook();
3015 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3016 $rawEntry = $this->mMagicExtensions[$mw->mId];
3017 } else {
3018 $rawEntry = self::$dataCache->getSubitem(
3019 $this->mCode, 'magicWords', $mw->mId );
3022 if ( !is_array( $rawEntry ) ) {
3023 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3024 } else {
3025 $mw->mCaseSensitive = $rawEntry[0];
3026 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3031 * Add magic words to the extension array
3033 * @param array $newWords
3035 function addMagicWordsByLang( $newWords ) {
3036 $fallbackChain = $this->getFallbackLanguages();
3037 $fallbackChain = array_reverse( $fallbackChain );
3038 foreach ( $fallbackChain as $code ) {
3039 if ( isset( $newWords[$code] ) ) {
3040 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3046 * Get special page names, as an associative array
3047 * case folded alias => real name
3048 * @return array
3050 function getSpecialPageAliases() {
3051 // Cache aliases because it may be slow to load them
3052 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3053 // Initialise array
3054 $this->mExtendedSpecialPageAliases =
3055 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3056 wfRunHooks( 'LanguageGetSpecialPageAliases',
3057 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3060 return $this->mExtendedSpecialPageAliases;
3064 * Italic is unsuitable for some languages
3066 * @param string $text The text to be emphasized.
3067 * @return string
3069 function emphasize( $text ) {
3070 return "<em>$text</em>";
3074 * Normally we output all numbers in plain en_US style, that is
3075 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3076 * point twohundredthirtyfive. However this is not suitable for all
3077 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3078 * Icelandic just want to use commas instead of dots, and dots instead
3079 * of commas like "293.291,235".
3081 * An example of this function being called:
3082 * <code>
3083 * wfMessage( 'message' )->numParams( $num )->text()
3084 * </code>
3086 * See $separatorTransformTable on MessageIs.php for
3087 * the , => . and . => , implementation.
3089 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3090 * @param int|float $number The string to be formatted, should be an integer
3091 * or a floating point number.
3092 * @param bool $nocommafy Set to true for special numbers like dates
3093 * @return string
3095 public function formatNum( $number, $nocommafy = false ) {
3096 global $wgTranslateNumerals;
3097 if ( !$nocommafy ) {
3098 $number = $this->commafy( $number );
3099 $s = $this->separatorTransformTable();
3100 if ( $s ) {
3101 $number = strtr( $number, $s );
3105 if ( $wgTranslateNumerals ) {
3106 $s = $this->digitTransformTable();
3107 if ( $s ) {
3108 $number = strtr( $number, $s );
3112 return $number;
3116 * Front-end for non-commafied formatNum
3118 * @param int|float $number The string to be formatted, should be an integer
3119 * or a floating point number.
3120 * @since 1.21
3121 * @return string
3123 public function formatNumNoSeparators( $number ) {
3124 return $this->formatNum( $number, true );
3128 * @param string $number
3129 * @return string
3131 public function parseFormattedNumber( $number ) {
3132 $s = $this->digitTransformTable();
3133 if ( $s ) {
3134 // eliminate empty array values such as ''. (bug 64347)
3135 $s = array_filter( $s );
3136 $number = strtr( $number, array_flip( $s ) );
3139 $s = $this->separatorTransformTable();
3140 if ( $s ) {
3141 // eliminate empty array values such as ''. (bug 64347)
3142 $s = array_filter( $s );
3143 $number = strtr( $number, array_flip( $s ) );
3146 $number = strtr( $number, array( ',' => '' ) );
3147 return $number;
3151 * Adds commas to a given number
3152 * @since 1.19
3153 * @param mixed $number
3154 * @return string
3156 function commafy( $number ) {
3157 $digitGroupingPattern = $this->digitGroupingPattern();
3158 if ( $number === null ) {
3159 return '';
3162 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3163 // default grouping is at thousands, use the same for ###,###,### pattern too.
3164 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3165 } else {
3166 // Ref: http://cldr.unicode.org/translation/number-patterns
3167 $sign = "";
3168 if ( intval( $number ) < 0 ) {
3169 // For negative numbers apply the algorithm like positive number and add sign.
3170 $sign = "-";
3171 $number = substr( $number, 1 );
3173 $integerPart = array();
3174 $decimalPart = array();
3175 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3176 preg_match( "/\d+/", $number, $integerPart );
3177 preg_match( "/\.\d*/", $number, $decimalPart );
3178 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3179 if ( $groupedNumber === $number ) {
3180 // the string does not have any number part. Eg: .12345
3181 return $sign . $groupedNumber;
3183 $start = $end = strlen( $integerPart[0] );
3184 while ( $start > 0 ) {
3185 $match = $matches[0][$numMatches - 1];
3186 $matchLen = strlen( $match );
3187 $start = $end - $matchLen;
3188 if ( $start < 0 ) {
3189 $start = 0;
3191 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3192 $end = $start;
3193 if ( $numMatches > 1 ) {
3194 // use the last pattern for the rest of the number
3195 $numMatches--;
3197 if ( $start > 0 ) {
3198 $groupedNumber = "," . $groupedNumber;
3201 return $sign . $groupedNumber;
3206 * @return string
3208 function digitGroupingPattern() {
3209 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3213 * @return array
3215 function digitTransformTable() {
3216 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3220 * @return array
3222 function separatorTransformTable() {
3223 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3227 * Take a list of strings and build a locale-friendly comma-separated
3228 * list, using the local comma-separator message.
3229 * The last two strings are chained with an "and".
3230 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3232 * @param string[] $l
3233 * @return string
3235 function listToText( array $l ) {
3236 $m = count( $l ) - 1;
3237 if ( $m < 0 ) {
3238 return '';
3240 if ( $m > 0 ) {
3241 $and = $this->getMessageFromDB( 'and' );
3242 $space = $this->getMessageFromDB( 'word-separator' );
3243 if ( $m > 1 ) {
3244 $comma = $this->getMessageFromDB( 'comma-separator' );
3247 $s = $l[$m];
3248 for ( $i = $m - 1; $i >= 0; $i-- ) {
3249 if ( $i == $m - 1 ) {
3250 $s = $l[$i] . $and . $space . $s;
3251 } else {
3252 $s = $l[$i] . $comma . $s;
3255 return $s;
3259 * Take a list of strings and build a locale-friendly comma-separated
3260 * list, using the local comma-separator message.
3261 * @param string[] $list Array of strings to put in a comma list
3262 * @return string
3264 function commaList( array $list ) {
3265 return implode(
3266 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3267 $list
3272 * Take a list of strings and build a locale-friendly semicolon-separated
3273 * list, using the local semicolon-separator message.
3274 * @param string[] $list Array of strings to put in a semicolon list
3275 * @return string
3277 function semicolonList( array $list ) {
3278 return implode(
3279 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3280 $list
3285 * Same as commaList, but separate it with the pipe instead.
3286 * @param string[] $list Array of strings to put in a pipe list
3287 * @return string
3289 function pipeList( array $list ) {
3290 return implode(
3291 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3292 $list
3297 * Truncate a string to a specified length in bytes, appending an optional
3298 * string (e.g. for ellipses)
3300 * The database offers limited byte lengths for some columns in the database;
3301 * multi-byte character sets mean we need to ensure that only whole characters
3302 * are included, otherwise broken characters can be passed to the user
3304 * If $length is negative, the string will be truncated from the beginning
3306 * @param string $string String to truncate
3307 * @param int $length Maximum length (including ellipses)
3308 * @param string $ellipsis String to append to the truncated text
3309 * @param bool $adjustLength Subtract length of ellipsis from $length.
3310 * $adjustLength was introduced in 1.18, before that behaved as if false.
3311 * @return string
3313 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3314 # Use the localized ellipsis character
3315 if ( $ellipsis == '...' ) {
3316 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3318 # Check if there is no need to truncate
3319 if ( $length == 0 ) {
3320 return $ellipsis; // convention
3321 } elseif ( strlen( $string ) <= abs( $length ) ) {
3322 return $string; // no need to truncate
3324 $stringOriginal = $string;
3325 # If ellipsis length is >= $length then we can't apply $adjustLength
3326 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3327 $string = $ellipsis; // this can be slightly unexpected
3328 # Otherwise, truncate and add ellipsis...
3329 } else {
3330 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3331 if ( $length > 0 ) {
3332 $length -= $eLength;
3333 $string = substr( $string, 0, $length ); // xyz...
3334 $string = $this->removeBadCharLast( $string );
3335 $string = rtrim( $string );
3336 $string = $string . $ellipsis;
3337 } else {
3338 $length += $eLength;
3339 $string = substr( $string, $length ); // ...xyz
3340 $string = $this->removeBadCharFirst( $string );
3341 $string = ltrim( $string );
3342 $string = $ellipsis . $string;
3345 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3346 # This check is *not* redundant if $adjustLength, due to the single case where
3347 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3348 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3349 return $string;
3350 } else {
3351 return $stringOriginal;
3356 * Remove bytes that represent an incomplete Unicode character
3357 * at the end of string (e.g. bytes of the char are missing)
3359 * @param string $string
3360 * @return string
3362 protected function removeBadCharLast( $string ) {
3363 if ( $string != '' ) {
3364 $char = ord( $string[strlen( $string ) - 1] );
3365 $m = array();
3366 if ( $char >= 0xc0 ) {
3367 # We got the first byte only of a multibyte char; remove it.
3368 $string = substr( $string, 0, -1 );
3369 } elseif ( $char >= 0x80 &&
3370 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3371 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3373 # We chopped in the middle of a character; remove it
3374 $string = $m[1];
3377 return $string;
3381 * Remove bytes that represent an incomplete Unicode character
3382 * at the start of string (e.g. bytes of the char are missing)
3384 * @param string $string
3385 * @return string
3387 protected function removeBadCharFirst( $string ) {
3388 if ( $string != '' ) {
3389 $char = ord( $string[0] );
3390 if ( $char >= 0x80 && $char < 0xc0 ) {
3391 # We chopped in the middle of a character; remove the whole thing
3392 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3395 return $string;
3399 * Truncate a string of valid HTML to a specified length in bytes,
3400 * appending an optional string (e.g. for ellipses), and return valid HTML
3402 * This is only intended for styled/linked text, such as HTML with
3403 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3404 * Also, this will not detect things like "display:none" CSS.
3406 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3408 * @param string $text HTML string to truncate
3409 * @param int $length (zero/positive) Maximum length (including ellipses)
3410 * @param string $ellipsis String to append to the truncated text
3411 * @return string
3413 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3414 # Use the localized ellipsis character
3415 if ( $ellipsis == '...' ) {
3416 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3418 # Check if there is clearly no need to truncate
3419 if ( $length <= 0 ) {
3420 return $ellipsis; // no text shown, nothing to format (convention)
3421 } elseif ( strlen( $text ) <= $length ) {
3422 return $text; // string short enough even *with* HTML (short-circuit)
3425 $dispLen = 0; // innerHTML legth so far
3426 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3427 $tagType = 0; // 0-open, 1-close
3428 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3429 $entityState = 0; // 0-not entity, 1-entity
3430 $tag = $ret = ''; // accumulated tag name, accumulated result string
3431 $openTags = array(); // open tag stack
3432 $maybeState = null; // possible truncation state
3434 $textLen = strlen( $text );
3435 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3436 for ( $pos = 0; true; ++$pos ) {
3437 # Consider truncation once the display length has reached the maximim.
3438 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3439 # Check that we're not in the middle of a bracket/entity...
3440 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3441 if ( !$testingEllipsis ) {
3442 $testingEllipsis = true;
3443 # Save where we are; we will truncate here unless there turn out to
3444 # be so few remaining characters that truncation is not necessary.
3445 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3446 $maybeState = array( $ret, $openTags ); // save state
3448 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3449 # String in fact does need truncation, the truncation point was OK.
3450 list( $ret, $openTags ) = $maybeState; // reload state
3451 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3452 $ret .= $ellipsis; // add ellipsis
3453 break;
3456 if ( $pos >= $textLen ) {
3457 break; // extra iteration just for above checks
3460 # Read the next char...
3461 $ch = $text[$pos];
3462 $lastCh = $pos ? $text[$pos - 1] : '';
3463 $ret .= $ch; // add to result string
3464 if ( $ch == '<' ) {
3465 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3466 $entityState = 0; // for bad HTML
3467 $bracketState = 1; // tag started (checking for backslash)
3468 } elseif ( $ch == '>' ) {
3469 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3470 $entityState = 0; // for bad HTML
3471 $bracketState = 0; // out of brackets
3472 } elseif ( $bracketState == 1 ) {
3473 if ( $ch == '/' ) {
3474 $tagType = 1; // close tag (e.g. "</span>")
3475 } else {
3476 $tagType = 0; // open tag (e.g. "<span>")
3477 $tag .= $ch;
3479 $bracketState = 2; // building tag name
3480 } elseif ( $bracketState == 2 ) {
3481 if ( $ch != ' ' ) {
3482 $tag .= $ch;
3483 } else {
3484 // Name found (e.g. "<a href=..."), add on tag attributes...
3485 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3487 } elseif ( $bracketState == 0 ) {
3488 if ( $entityState ) {
3489 if ( $ch == ';' ) {
3490 $entityState = 0;
3491 $dispLen++; // entity is one displayed char
3493 } else {
3494 if ( $neLength == 0 && !$maybeState ) {
3495 // Save state without $ch. We want to *hit* the first
3496 // display char (to get tags) but not *use* it if truncating.
3497 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3499 if ( $ch == '&' ) {
3500 $entityState = 1; // entity found, (e.g. "&#160;")
3501 } else {
3502 $dispLen++; // this char is displayed
3503 // Add the next $max display text chars after this in one swoop...
3504 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3505 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3506 $dispLen += $skipped;
3507 $pos += $skipped;
3512 // Close the last tag if left unclosed by bad HTML
3513 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3514 while ( count( $openTags ) > 0 ) {
3515 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3517 return $ret;
3521 * truncateHtml() helper function
3522 * like strcspn() but adds the skipped chars to $ret
3524 * @param string $ret
3525 * @param string $text
3526 * @param string $search
3527 * @param int $start
3528 * @param null|int $len
3529 * @return int
3531 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3532 if ( $len === null ) {
3533 $len = -1; // -1 means "no limit" for strcspn
3534 } elseif ( $len < 0 ) {
3535 $len = 0; // sanity
3537 $skipCount = 0;
3538 if ( $start < strlen( $text ) ) {
3539 $skipCount = strcspn( $text, $search, $start, $len );
3540 $ret .= substr( $text, $start, $skipCount );
3542 return $skipCount;
3546 * truncateHtml() helper function
3547 * (a) push or pop $tag from $openTags as needed
3548 * (b) clear $tag value
3549 * @param string &$tag Current HTML tag name we are looking at
3550 * @param int $tagType (0-open tag, 1-close tag)
3551 * @param string $lastCh Character before the '>' that ended this tag
3552 * @param array &$openTags Open tag stack (not accounting for $tag)
3554 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3555 $tag = ltrim( $tag );
3556 if ( $tag != '' ) {
3557 if ( $tagType == 0 && $lastCh != '/' ) {
3558 $openTags[] = $tag; // tag opened (didn't close itself)
3559 } elseif ( $tagType == 1 ) {
3560 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3561 array_pop( $openTags ); // tag closed
3564 $tag = '';
3569 * Grammatical transformations, needed for inflected languages
3570 * Invoked by putting {{grammar:case|word}} in a message
3572 * @param string $word
3573 * @param string $case
3574 * @return string
3576 function convertGrammar( $word, $case ) {
3577 global $wgGrammarForms;
3578 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3579 return $wgGrammarForms[$this->getCode()][$case][$word];
3582 return $word;
3585 * Get the grammar forms for the content language
3586 * @return array Array of grammar forms
3587 * @since 1.20
3589 function getGrammarForms() {
3590 global $wgGrammarForms;
3591 if ( isset( $wgGrammarForms[$this->getCode()] )
3592 && is_array( $wgGrammarForms[$this->getCode()] )
3594 return $wgGrammarForms[$this->getCode()];
3597 return array();
3600 * Provides an alternative text depending on specified gender.
3601 * Usage {{gender:username|masculine|feminine|unknown}}.
3602 * username is optional, in which case the gender of current user is used,
3603 * but only in (some) interface messages; otherwise default gender is used.
3605 * If no forms are given, an empty string is returned. If only one form is
3606 * given, it will be returned unconditionally. These details are implied by
3607 * the caller and cannot be overridden in subclasses.
3609 * If three forms are given, the default is to use the third (unknown) form.
3610 * If fewer than three forms are given, the default is to use the first (masculine) form.
3611 * These details can be overridden in subclasses.
3613 * @param string $gender
3614 * @param array $forms
3616 * @return string
3618 function gender( $gender, $forms ) {
3619 if ( !count( $forms ) ) {
3620 return '';
3622 $forms = $this->preConvertPlural( $forms, 2 );
3623 if ( $gender === 'male' ) {
3624 return $forms[0];
3626 if ( $gender === 'female' ) {
3627 return $forms[1];
3629 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3633 * Plural form transformations, needed for some languages.
3634 * For example, there are 3 form of plural in Russian and Polish,
3635 * depending on "count mod 10". See [[w:Plural]]
3636 * For English it is pretty simple.
3638 * Invoked by putting {{plural:count|wordform1|wordform2}}
3639 * or {{plural:count|wordform1|wordform2|wordform3}}
3641 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3643 * @param int $count Non-localized number
3644 * @param array $forms Different plural forms
3645 * @return string Correct form of plural for $count in this language
3647 function convertPlural( $count, $forms ) {
3648 // Handle explicit n=pluralform cases
3649 $forms = $this->handleExplicitPluralForms( $count, $forms );
3650 if ( is_string( $forms ) ) {
3651 return $forms;
3653 if ( !count( $forms ) ) {
3654 return '';
3657 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3658 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3659 return $forms[$pluralForm];
3663 * Handles explicit plural forms for Language::convertPlural()
3665 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3666 * If an explicitly defined plural form matches the $count, then
3667 * string value returned, otherwise array returned for further consideration
3668 * by CLDR rules or overridden convertPlural().
3670 * @since 1.23
3672 * @param int $count non-localized number
3673 * @param array $forms different plural forms
3675 * @return array|string
3677 protected function handleExplicitPluralForms( $count, array $forms ) {
3678 foreach ( $forms as $index => $form ) {
3679 if ( preg_match( '/\d+=/i', $form ) ) {
3680 $pos = strpos( $form, '=' );
3681 if ( substr( $form, 0, $pos ) === (string) $count ) {
3682 return substr( $form, $pos + 1 );
3684 unset( $forms[$index] );
3687 return array_values( $forms );
3691 * Checks that convertPlural was given an array and pads it to requested
3692 * amount of forms by copying the last one.
3694 * @param int $count How many forms should there be at least
3695 * @param array $forms Array of forms given to convertPlural
3696 * @return array Padded array of forms or an exception if not an array
3698 protected function preConvertPlural( /* Array */ $forms, $count ) {
3699 while ( count( $forms ) < $count ) {
3700 $forms[] = $forms[count( $forms ) - 1];
3702 return $forms;
3706 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3707 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3708 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3709 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3710 * match up with it.
3712 * @param string $str The validated block duration in English
3713 * @return string Somehow translated block duration
3714 * @see LanguageFi.php for example implementation
3716 function translateBlockExpiry( $str ) {
3717 $duration = SpecialBlock::getSuggestedDurations( $this );
3718 foreach ( $duration as $show => $value ) {
3719 if ( strcmp( $str, $value ) == 0 ) {
3720 return htmlspecialchars( trim( $show ) );
3724 // Since usually only infinite or indefinite is only on list, so try
3725 // equivalents if still here.
3726 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3727 if ( in_array( $str, $indefs ) ) {
3728 foreach ( $indefs as $val ) {
3729 $show = array_search( $val, $duration, true );
3730 if ( $show !== false ) {
3731 return htmlspecialchars( trim( $show ) );
3736 // If all else fails, return a standard duration or timestamp description.
3737 $time = strtotime( $str, 0 );
3738 if ( $time === false ) { // Unknown format. Return it as-is in case.
3739 return $str;
3740 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3741 // $time is relative to 0 so it's a duration length.
3742 return $this->formatDuration( $time );
3743 } else { // It's an absolute timestamp.
3744 if ( $time === 0 ) {
3745 // wfTimestamp() handles 0 as current time instead of epoch.
3746 return $this->timeanddate( '19700101000000' );
3747 } else {
3748 return $this->timeanddate( $time );
3754 * languages like Chinese need to be segmented in order for the diff
3755 * to be of any use
3757 * @param string $text
3758 * @return string
3760 public function segmentForDiff( $text ) {
3761 return $text;
3765 * and unsegment to show the result
3767 * @param string $text
3768 * @return string
3770 public function unsegmentForDiff( $text ) {
3771 return $text;
3775 * Return the LanguageConverter used in the Language
3777 * @since 1.19
3778 * @return LanguageConverter
3780 public function getConverter() {
3781 return $this->mConverter;
3785 * convert text to all supported variants
3787 * @param string $text
3788 * @return array
3790 public function autoConvertToAllVariants( $text ) {
3791 return $this->mConverter->autoConvertToAllVariants( $text );
3795 * convert text to different variants of a language.
3797 * @param string $text
3798 * @return string
3800 public function convert( $text ) {
3801 return $this->mConverter->convert( $text );
3805 * Convert a Title object to a string in the preferred variant
3807 * @param Title $title
3808 * @return string
3810 public function convertTitle( $title ) {
3811 return $this->mConverter->convertTitle( $title );
3815 * Convert a namespace index to a string in the preferred variant
3817 * @param int $ns
3818 * @return string
3820 public function convertNamespace( $ns ) {
3821 return $this->mConverter->convertNamespace( $ns );
3825 * Check if this is a language with variants
3827 * @return bool
3829 public function hasVariants() {
3830 return count( $this->getVariants() ) > 1;
3834 * Check if the language has the specific variant
3836 * @since 1.19
3837 * @param string $variant
3838 * @return bool
3840 public function hasVariant( $variant ) {
3841 return (bool)$this->mConverter->validateVariant( $variant );
3845 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3847 * @param string $text
3848 * @return string
3849 * @deprecated since 1.22 is no longer used
3851 public function armourMath( $text ) {
3852 return $this->mConverter->armourMath( $text );
3856 * Perform output conversion on a string, and encode for safe HTML output.
3857 * @param string $text Text to be converted
3858 * @param bool $isTitle Whether this conversion is for the article title
3859 * @return string
3860 * @todo this should get integrated somewhere sane
3862 public function convertHtml( $text, $isTitle = false ) {
3863 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3867 * @param string $key
3868 * @return string
3870 public function convertCategoryKey( $key ) {
3871 return $this->mConverter->convertCategoryKey( $key );
3875 * Get the list of variants supported by this language
3876 * see sample implementation in LanguageZh.php
3878 * @return array an array of language codes
3880 public function getVariants() {
3881 return $this->mConverter->getVariants();
3885 * @return string
3887 public function getPreferredVariant() {
3888 return $this->mConverter->getPreferredVariant();
3892 * @return string
3894 public function getDefaultVariant() {
3895 return $this->mConverter->getDefaultVariant();
3899 * @return string
3901 public function getURLVariant() {
3902 return $this->mConverter->getURLVariant();
3906 * If a language supports multiple variants, it is
3907 * possible that non-existing link in one variant
3908 * actually exists in another variant. this function
3909 * tries to find it. See e.g. LanguageZh.php
3911 * @param string $link The name of the link
3912 * @param Title $nt The title object of the link
3913 * @param bool $ignoreOtherCond To disable other conditions when
3914 * we need to transclude a template or update a category's link
3915 * @return null the input parameters may be modified upon return
3917 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3918 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3922 * returns language specific options used by User::getPageRenderHash()
3923 * for example, the preferred language variant
3925 * @return string
3927 function getExtraHashOptions() {
3928 return $this->mConverter->getExtraHashOptions();
3932 * For languages that support multiple variants, the title of an
3933 * article may be displayed differently in different variants. this
3934 * function returns the apporiate title defined in the body of the article.
3936 * @return string
3938 public function getParsedTitle() {
3939 return $this->mConverter->getParsedTitle();
3943 * Prepare external link text for conversion. When the text is
3944 * a URL, it shouldn't be converted, and it'll be wrapped in
3945 * the "raw" tag (-{R| }-) to prevent conversion.
3947 * This function is called "markNoConversion" for historical
3948 * reasons.
3950 * @param string $text Text to be used for external link
3951 * @param bool $noParse Wrap it without confirming it's a real URL first
3952 * @return string The tagged text
3954 public function markNoConversion( $text, $noParse = false ) {
3955 // Excluding protocal-relative URLs may avoid many false positives.
3956 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3957 return $this->mConverter->markNoConversion( $text );
3958 } else {
3959 return $text;
3964 * A regular expression to match legal word-trailing characters
3965 * which should be merged onto a link of the form [[foo]]bar.
3967 * @return string
3969 public function linkTrail() {
3970 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3974 * A regular expression character set to match legal word-prefixing
3975 * characters which should be merged onto a link of the form foo[[bar]].
3977 * @return string
3979 public function linkPrefixCharset() {
3980 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
3984 * @return Language
3986 function getLangObj() {
3987 return $this;
3991 * Get the "parent" language which has a converter to convert a "compatible" language
3992 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
3994 * @return Language|null
3995 * @since 1.22
3997 public function getParentLanguage() {
3998 if ( $this->mParentLanguage !== false ) {
3999 return $this->mParentLanguage;
4002 $pieces = explode( '-', $this->getCode() );
4003 $code = $pieces[0];
4004 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4005 $this->mParentLanguage = null;
4006 return null;
4008 $lang = Language::factory( $code );
4009 if ( !$lang->hasVariant( $this->getCode() ) ) {
4010 $this->mParentLanguage = null;
4011 return null;
4014 $this->mParentLanguage = $lang;
4015 return $lang;
4019 * Get the RFC 3066 code for this language object
4021 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4022 * htmlspecialchars() or similar
4024 * @return string
4026 public function getCode() {
4027 return $this->mCode;
4031 * Get the code in Bcp47 format which we can use
4032 * inside of html lang="" tags.
4034 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4035 * htmlspecialchars() or similar.
4037 * @since 1.19
4038 * @return string
4040 public function getHtmlCode() {
4041 if ( is_null( $this->mHtmlCode ) ) {
4042 $this->mHtmlCode = wfBCP47( $this->getCode() );
4044 return $this->mHtmlCode;
4048 * @param string $code
4050 public function setCode( $code ) {
4051 $this->mCode = $code;
4052 // Ensure we don't leave incorrect cached data lying around
4053 $this->mHtmlCode = null;
4054 $this->mParentLanguage = false;
4058 * Get the name of a file for a certain language code
4059 * @param string $prefix Prepend this to the filename
4060 * @param string $code Language code
4061 * @param string $suffix Append this to the filename
4062 * @throws MWException
4063 * @return string $prefix . $mangledCode . $suffix
4065 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4066 if ( !self::isValidBuiltInCode( $code ) ) {
4067 throw new MWException( "Invalid language code \"$code\"" );
4070 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4074 * Get the language code from a file name. Inverse of getFileName()
4075 * @param string $filename $prefix . $languageCode . $suffix
4076 * @param string $prefix Prefix before the language code
4077 * @param string $suffix Suffix after the language code
4078 * @return string Language code, or false if $prefix or $suffix isn't found
4080 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4081 $m = null;
4082 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4083 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4084 if ( !count( $m ) ) {
4085 return false;
4087 return str_replace( '_', '-', strtolower( $m[1] ) );
4091 * @param string $code
4092 * @return string
4094 public static function getMessagesFileName( $code ) {
4095 global $IP;
4096 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4097 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4098 return $file;
4102 * @param string $code
4103 * @return string
4104 * @since 1.23
4106 public static function getJsonMessagesFileName( $code ) {
4107 global $IP;
4109 if ( !self::isValidBuiltInCode( $code ) ) {
4110 throw new MWException( "Invalid language code \"$code\"" );
4113 return "$IP/languages/i18n/$code.json";
4117 * @param string $code
4118 * @return string
4120 public static function getClassFileName( $code ) {
4121 global $IP;
4122 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4126 * Get the first fallback for a given language.
4128 * @param string $code
4130 * @return bool|string
4132 public static function getFallbackFor( $code ) {
4133 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4134 return false;
4135 } else {
4136 $fallbacks = self::getFallbacksFor( $code );
4137 $first = array_shift( $fallbacks );
4138 return $first;
4143 * Get the ordered list of fallback languages.
4145 * @since 1.19
4146 * @param string $code Language code
4147 * @return array
4149 public static function getFallbacksFor( $code ) {
4150 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4151 return array();
4152 } else {
4153 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4154 $v = array_map( 'trim', explode( ',', $v ) );
4155 if ( $v[count( $v ) - 1] !== 'en' ) {
4156 $v[] = 'en';
4158 return $v;
4163 * Get the ordered list of fallback languages, ending with the fallback
4164 * language chain for the site language.
4166 * @since 1.22
4167 * @param string $code Language code
4168 * @return array array( fallbacks, site fallbacks )
4170 public static function getFallbacksIncludingSiteLanguage( $code ) {
4171 global $wgLanguageCode;
4173 // Usually, we will only store a tiny number of fallback chains, so we
4174 // keep them in static memory.
4175 $cacheKey = "{$code}-{$wgLanguageCode}";
4177 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4178 $fallbacks = self::getFallbacksFor( $code );
4180 // Append the site's fallback chain, including the site language itself
4181 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4182 array_unshift( $siteFallbacks, $wgLanguageCode );
4184 // Eliminate any languages already included in the chain
4185 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4187 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4189 return self::$fallbackLanguageCache[$cacheKey];
4193 * Get all messages for a given language
4194 * WARNING: this may take a long time. If you just need all message *keys*
4195 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4197 * @param string $code
4199 * @return array
4201 public static function getMessagesFor( $code ) {
4202 return self::getLocalisationCache()->getItem( $code, 'messages' );
4206 * Get a message for a given language
4208 * @param string $key
4209 * @param string $code
4211 * @return string
4213 public static function getMessageFor( $key, $code ) {
4214 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4218 * Get all message keys for a given language. This is a faster alternative to
4219 * array_keys( Language::getMessagesFor( $code ) )
4221 * @since 1.19
4222 * @param string $code Language code
4223 * @return array of message keys (strings)
4225 public static function getMessageKeysFor( $code ) {
4226 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4230 * @param string $talk
4231 * @return mixed
4233 function fixVariableInNamespace( $talk ) {
4234 if ( strpos( $talk, '$1' ) === false ) {
4235 return $talk;
4238 global $wgMetaNamespace;
4239 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4241 # Allow grammar transformations
4242 # Allowing full message-style parsing would make simple requests
4243 # such as action=raw much more expensive than they need to be.
4244 # This will hopefully cover most cases.
4245 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4246 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4247 return str_replace( ' ', '_', $talk );
4251 * @param string $m
4252 * @return string
4254 function replaceGrammarInNamespace( $m ) {
4255 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4259 * @throws MWException
4260 * @return array
4262 static function getCaseMaps() {
4263 static $wikiUpperChars, $wikiLowerChars;
4264 if ( isset( $wikiUpperChars ) ) {
4265 return array( $wikiUpperChars, $wikiLowerChars );
4268 wfProfileIn( __METHOD__ );
4269 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4270 if ( $arr === false ) {
4271 throw new MWException(
4272 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4274 $wikiUpperChars = $arr['wikiUpperChars'];
4275 $wikiLowerChars = $arr['wikiLowerChars'];
4276 wfProfileOut( __METHOD__ );
4277 return array( $wikiUpperChars, $wikiLowerChars );
4281 * Decode an expiry (block, protection, etc) which has come from the DB
4283 * @todo FIXME: why are we returnings DBMS-dependent strings???
4285 * @param string $expiry Database expiry String
4286 * @param bool|int $format True to process using language functions, or TS_ constant
4287 * to return the expiry in a given timestamp
4288 * @return string
4289 * @since 1.18
4291 public function formatExpiry( $expiry, $format = true ) {
4292 static $infinity;
4293 if ( $infinity === null ) {
4294 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4297 if ( $expiry == '' || $expiry == $infinity ) {
4298 return $format === true
4299 ? $this->getMessageFromDB( 'infiniteblock' )
4300 : $infinity;
4301 } else {
4302 return $format === true
4303 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4304 : wfTimestamp( $format, $expiry );
4309 * @todo Document
4310 * @param int|float $seconds
4311 * @param array $format Optional
4312 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4313 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4314 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4315 * and friends.
4316 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4317 * or 'avoidminutes'.
4318 * @return string
4320 function formatTimePeriod( $seconds, $format = array() ) {
4321 if ( !is_array( $format ) ) {
4322 $format = array( 'avoid' => $format ); // For backwards compatibility
4324 if ( !isset( $format['avoid'] ) ) {
4325 $format['avoid'] = false;
4327 if ( !isset( $format['noabbrevs' ] ) ) {
4328 $format['noabbrevs'] = false;
4330 $secondsMsg = wfMessage(
4331 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4332 $minutesMsg = wfMessage(
4333 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4334 $hoursMsg = wfMessage(
4335 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4336 $daysMsg = wfMessage(
4337 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4339 if ( round( $seconds * 10 ) < 100 ) {
4340 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4341 $s = $secondsMsg->params( $s )->text();
4342 } elseif ( round( $seconds ) < 60 ) {
4343 $s = $this->formatNum( round( $seconds ) );
4344 $s = $secondsMsg->params( $s )->text();
4345 } elseif ( round( $seconds ) < 3600 ) {
4346 $minutes = floor( $seconds / 60 );
4347 $secondsPart = round( fmod( $seconds, 60 ) );
4348 if ( $secondsPart == 60 ) {
4349 $secondsPart = 0;
4350 $minutes++;
4352 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4353 $s .= ' ';
4354 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4355 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4356 $hours = floor( $seconds / 3600 );
4357 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4358 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4359 if ( $secondsPart == 60 ) {
4360 $secondsPart = 0;
4361 $minutes++;
4363 if ( $minutes == 60 ) {
4364 $minutes = 0;
4365 $hours++;
4367 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4368 $s .= ' ';
4369 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4370 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4371 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4373 } else {
4374 $days = floor( $seconds / 86400 );
4375 if ( $format['avoid'] === 'avoidminutes' ) {
4376 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4377 if ( $hours == 24 ) {
4378 $hours = 0;
4379 $days++;
4381 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4382 $s .= ' ';
4383 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4384 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4385 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4386 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4387 if ( $minutes == 60 ) {
4388 $minutes = 0;
4389 $hours++;
4391 if ( $hours == 24 ) {
4392 $hours = 0;
4393 $days++;
4395 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4396 $s .= ' ';
4397 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4398 $s .= ' ';
4399 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4400 } else {
4401 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4402 $s .= ' ';
4403 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4406 return $s;
4410 * Format a bitrate for output, using an appropriate
4411 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4412 * the magnitude in question.
4414 * This use base 1000. For base 1024 use formatSize(), for another base
4415 * see formatComputingNumbers().
4417 * @param int $bps
4418 * @return string
4420 function formatBitrate( $bps ) {
4421 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4425 * @param int $size Size of the unit
4426 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4427 * @param string $messageKey Message key to be uesd
4428 * @return string
4430 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4431 if ( $size <= 0 ) {
4432 return str_replace( '$1', $this->formatNum( $size ),
4433 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4436 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4437 $index = 0;
4439 $maxIndex = count( $sizes ) - 1;
4440 while ( $size >= $boundary && $index < $maxIndex ) {
4441 $index++;
4442 $size /= $boundary;
4445 // For small sizes no decimal places necessary
4446 $round = 0;
4447 if ( $index > 1 ) {
4448 // For MB and bigger two decimal places are smarter
4449 $round = 2;
4451 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4453 $size = round( $size, $round );
4454 $text = $this->getMessageFromDB( $msg );
4455 return str_replace( '$1', $this->formatNum( $size ), $text );
4459 * Format a size in bytes for output, using an appropriate
4460 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4462 * This method use base 1024. For base 1000 use formatBitrate(), for
4463 * another base see formatComputingNumbers()
4465 * @param int $size Size to format
4466 * @return string Plain text (not HTML)
4468 function formatSize( $size ) {
4469 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4473 * Make a list item, used by various special pages
4475 * @param string $page Page link
4476 * @param string $details Text between brackets
4477 * @param bool $oppositedm Add the direction mark opposite to your
4478 * language, to display text properly
4479 * @return string
4481 function specialList( $page, $details, $oppositedm = true ) {
4482 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4483 $this->getDirMark();
4484 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4485 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4486 return $page . $details;
4490 * Generate (prev x| next x) (20|50|100...) type links for paging
4492 * @param Title $title Title object to link
4493 * @param int $offset
4494 * @param int $limit
4495 * @param array|string $query Optional URL query parameter string
4496 * @param bool $atend Optional param for specified if this is the last page
4497 * @return string
4499 public function viewPrevNext( Title $title, $offset, $limit,
4500 array $query = array(), $atend = false
4502 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4504 # Make 'previous' link
4505 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4506 if ( $offset > 0 ) {
4507 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4508 $query, $prev, 'prevn-title', 'mw-prevlink' );
4509 } else {
4510 $plink = htmlspecialchars( $prev );
4513 # Make 'next' link
4514 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4515 if ( $atend ) {
4516 $nlink = htmlspecialchars( $next );
4517 } else {
4518 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4519 $query, $next, 'nextn-title', 'mw-nextlink' );
4522 # Make links to set number of items per page
4523 $numLinks = array();
4524 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4525 $numLinks[] = $this->numLink( $title, $offset, $num,
4526 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4529 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4530 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4534 * Helper function for viewPrevNext() that generates links
4536 * @param Title $title Title object to link
4537 * @param int $offset
4538 * @param int $limit
4539 * @param array $query Extra query parameters
4540 * @param string $link Text to use for the link; will be escaped
4541 * @param string $tooltipMsg Name of the message to use as tooltip
4542 * @param string $class Value of the "class" attribute of the link
4543 * @return string HTML fragment
4545 private function numLink( Title $title, $offset, $limit, array $query, $link,
4546 $tooltipMsg, $class
4548 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4549 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4550 ->numParams( $limit )->text();
4552 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4553 'title' => $tooltip, 'class' => $class ), $link );
4557 * Get the conversion rule title, if any.
4559 * @return string
4561 public function getConvRuleTitle() {
4562 return $this->mConverter->getConvRuleTitle();
4566 * Get the compiled plural rules for the language
4567 * @since 1.20
4568 * @return array Associative array with plural form, and plural rule as key-value pairs
4570 public function getCompiledPluralRules() {
4571 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4572 $fallbacks = Language::getFallbacksFor( $this->mCode );
4573 if ( !$pluralRules ) {
4574 foreach ( $fallbacks as $fallbackCode ) {
4575 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4576 if ( $pluralRules ) {
4577 break;
4581 return $pluralRules;
4585 * Get the plural rules for the language
4586 * @since 1.20
4587 * @return array Associative array with plural form number and plural rule as key-value pairs
4589 public function getPluralRules() {
4590 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4591 $fallbacks = Language::getFallbacksFor( $this->mCode );
4592 if ( !$pluralRules ) {
4593 foreach ( $fallbacks as $fallbackCode ) {
4594 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4595 if ( $pluralRules ) {
4596 break;
4600 return $pluralRules;
4604 * Get the plural rule types for the language
4605 * @since 1.22
4606 * @return array Associative array with plural form number and plural rule type as key-value pairs
4608 public function getPluralRuleTypes() {
4609 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4610 $fallbacks = Language::getFallbacksFor( $this->mCode );
4611 if ( !$pluralRuleTypes ) {
4612 foreach ( $fallbacks as $fallbackCode ) {
4613 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4614 if ( $pluralRuleTypes ) {
4615 break;
4619 return $pluralRuleTypes;
4623 * Find the index number of the plural rule appropriate for the given number
4624 * @return int The index number of the plural rule
4626 public function getPluralRuleIndexNumber( $number ) {
4627 $pluralRules = $this->getCompiledPluralRules();
4628 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4629 return $form;
4633 * Find the plural rule type appropriate for the given number
4634 * For example, if the language is set to Arabic, getPluralType(5) should
4635 * return 'few'.
4636 * @since 1.22
4637 * @return string The name of the plural rule type, e.g. one, two, few, many
4639 public function getPluralRuleType( $number ) {
4640 $index = $this->getPluralRuleIndexNumber( $number );
4641 $pluralRuleTypes = $this->getPluralRuleTypes();
4642 if ( isset( $pluralRuleTypes[$index] ) ) {
4643 return $pluralRuleTypes[$index];
4644 } else {
4645 return 'other';