Pass phpcs-strict on some test files (10/11)
[mediawiki.git] / languages / Language.php
blobc635ebbfd17cccde09e1e37ac2cd5b6ff8772f0d
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 $minDiff = 0;
1912 if ( $data[0] == 'System' || $tz == '' ) {
1913 #  Global offset in minutes.
1914 if ( isset( $wgLocalTZoffset ) ) {
1915 $minDiff = $wgLocalTZoffset;
1917 } elseif ( $data[0] == 'Offset' ) {
1918 $minDiff = intval( $data[1] );
1919 } else {
1920 $data = explode( ':', $tz );
1921 if ( count( $data ) == 2 ) {
1922 $data[0] = intval( $data[0] );
1923 $data[1] = intval( $data[1] );
1924 $minDiff = abs( $data[0] ) * 60 + $data[1];
1925 if ( $data[0] < 0 ) {
1926 $minDiff = -$minDiff;
1928 } else {
1929 $minDiff = intval( $data[0] ) * 60;
1933 # No difference ? Return time unchanged
1934 if ( 0 == $minDiff ) {
1935 return $ts;
1938 wfSuppressWarnings(); // E_STRICT system time bitching
1939 # Generate an adjusted date; take advantage of the fact that mktime
1940 # will normalize out-of-range values so we don't have to split $minDiff
1941 # into hours and minutes.
1942 $t = mktime( (
1943 (int)substr( $ts, 8, 2 ) ), # Hours
1944 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1945 (int)substr( $ts, 12, 2 ), # Seconds
1946 (int)substr( $ts, 4, 2 ), # Month
1947 (int)substr( $ts, 6, 2 ), # Day
1948 (int)substr( $ts, 0, 4 ) ); # Year
1950 $date = date( 'YmdHis', $t );
1951 wfRestoreWarnings();
1953 return $date;
1957 * This is meant to be used by time(), date(), and timeanddate() to get
1958 * the date preference they're supposed to use, it should be used in
1959 * all children.
1961 *<code>
1962 * function timeanddate([...], $format = true) {
1963 * $datePreference = $this->dateFormat($format);
1964 * [...]
1966 *</code>
1968 * @param int|string|bool $usePrefs If true, the user's preference is used
1969 * if false, the site/language default is used
1970 * if int/string, assumed to be a format.
1971 * @return string
1973 function dateFormat( $usePrefs = true ) {
1974 global $wgUser;
1976 if ( is_bool( $usePrefs ) ) {
1977 if ( $usePrefs ) {
1978 $datePreference = $wgUser->getDatePreference();
1979 } else {
1980 $datePreference = (string)User::getDefaultOption( 'date' );
1982 } else {
1983 $datePreference = (string)$usePrefs;
1986 // return int
1987 if ( $datePreference == '' ) {
1988 return 'default';
1991 return $datePreference;
1995 * Get a format string for a given type and preference
1996 * @param string $type May be date, time or both
1997 * @param string $pref The format name as it appears in Messages*.php
1999 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2001 * @return string
2003 function getDateFormatString( $type, $pref ) {
2004 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2005 if ( $pref == 'default' ) {
2006 $pref = $this->getDefaultDateFormat();
2007 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2008 } else {
2009 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2011 if ( $type === 'pretty' && $df === null ) {
2012 $df = $this->getDateFormatString( 'date', $pref );
2015 if ( $df === null ) {
2016 $pref = $this->getDefaultDateFormat();
2017 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2020 $this->dateFormatStrings[$type][$pref] = $df;
2022 return $this->dateFormatStrings[$type][$pref];
2026 * @param mixed $ts The time format which needs to be turned into a
2027 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2028 * @param bool $adj Whether to adjust the time output according to the
2029 * user configured offset ($timecorrection)
2030 * @param mixed $format True to use user's date format preference
2031 * @param string|bool $timecorrection The time offset as returned by
2032 * validateTimeZone() in Special:Preferences
2033 * @return string
2035 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2036 $ts = wfTimestamp( TS_MW, $ts );
2037 if ( $adj ) {
2038 $ts = $this->userAdjust( $ts, $timecorrection );
2040 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2041 return $this->sprintfDate( $df, $ts );
2045 * @param mixed $ts The time format which needs to be turned into a
2046 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2047 * @param bool $adj Whether to adjust the time output according to the
2048 * user configured offset ($timecorrection)
2049 * @param mixed $format True to use user's date format preference
2050 * @param string|bool $timecorrection The time offset as returned by
2051 * validateTimeZone() in Special:Preferences
2052 * @return string
2054 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2055 $ts = wfTimestamp( TS_MW, $ts );
2056 if ( $adj ) {
2057 $ts = $this->userAdjust( $ts, $timecorrection );
2059 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2060 return $this->sprintfDate( $df, $ts );
2064 * @param mixed $ts The time format which needs to be turned into a
2065 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2066 * @param bool $adj Whether to adjust the time output according to the
2067 * user configured offset ($timecorrection)
2068 * @param mixed $format What format to return, if it's false output the
2069 * default one (default true)
2070 * @param string|bool $timecorrection The time offset as returned by
2071 * validateTimeZone() in Special:Preferences
2072 * @return string
2074 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2075 $ts = wfTimestamp( TS_MW, $ts );
2076 if ( $adj ) {
2077 $ts = $this->userAdjust( $ts, $timecorrection );
2079 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2080 return $this->sprintfDate( $df, $ts );
2084 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2086 * @since 1.20
2088 * @param int $seconds The amount of seconds.
2089 * @param array $chosenIntervals The intervals to enable.
2091 * @return string
2093 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2094 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2096 $segments = array();
2098 foreach ( $intervals as $intervalName => $intervalValue ) {
2099 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2100 // duration-years, duration-decades, duration-centuries, duration-millennia
2101 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2102 $segments[] = $message->inLanguage( $this )->escaped();
2105 return $this->listToText( $segments );
2109 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2110 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2112 * @since 1.20
2114 * @param int $seconds The amount of seconds.
2115 * @param array $chosenIntervals The intervals to enable.
2117 * @return array
2119 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2120 if ( empty( $chosenIntervals ) ) {
2121 $chosenIntervals = array(
2122 'millennia',
2123 'centuries',
2124 'decades',
2125 'years',
2126 'days',
2127 'hours',
2128 'minutes',
2129 'seconds'
2133 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2134 $sortedNames = array_keys( $intervals );
2135 $smallestInterval = array_pop( $sortedNames );
2137 $segments = array();
2139 foreach ( $intervals as $name => $length ) {
2140 $value = floor( $seconds / $length );
2142 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2143 $seconds -= $value * $length;
2144 $segments[$name] = $value;
2148 return $segments;
2152 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2154 * @param string $type Can be 'date', 'time' or 'both'
2155 * @param mixed $ts The time format which needs to be turned into a
2156 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2157 * @param User $user User object used to get preferences for timezone and format
2158 * @param array $options Array, can contain the following keys:
2159 * - 'timecorrection': time correction, can have the following values:
2160 * - true: use user's preference
2161 * - false: don't use time correction
2162 * - int: value of time correction in minutes
2163 * - 'format': format to use, can have the following values:
2164 * - true: use user's preference
2165 * - false: use default preference
2166 * - string: format to use
2167 * @since 1.19
2168 * @return string
2170 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2171 $ts = wfTimestamp( TS_MW, $ts );
2172 $options += array( 'timecorrection' => true, 'format' => true );
2173 if ( $options['timecorrection'] !== false ) {
2174 if ( $options['timecorrection'] === true ) {
2175 $offset = $user->getOption( 'timecorrection' );
2176 } else {
2177 $offset = $options['timecorrection'];
2179 $ts = $this->userAdjust( $ts, $offset );
2181 if ( $options['format'] === true ) {
2182 $format = $user->getDatePreference();
2183 } else {
2184 $format = $options['format'];
2186 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2187 return $this->sprintfDate( $df, $ts );
2191 * Get the formatted date for the given timestamp and formatted for
2192 * the given user.
2194 * @param mixed $ts Mixed: the time format which needs to be turned into a
2195 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2196 * @param User $user User object used to get preferences for timezone and format
2197 * @param array $options Array, can contain the following keys:
2198 * - 'timecorrection': time correction, can have the following values:
2199 * - true: use user's preference
2200 * - false: don't use time correction
2201 * - int: value of time correction in minutes
2202 * - 'format': format to use, can have the following values:
2203 * - true: use user's preference
2204 * - false: use default preference
2205 * - string: format to use
2206 * @since 1.19
2207 * @return string
2209 public function userDate( $ts, User $user, array $options = array() ) {
2210 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2214 * Get the formatted time for the given timestamp and formatted for
2215 * the given user.
2217 * @param mixed $ts The time format which needs to be turned into a
2218 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2219 * @param User $user User object used to get preferences for timezone and format
2220 * @param array $options Array, can contain the following keys:
2221 * - 'timecorrection': time correction, can have the following values:
2222 * - true: use user's preference
2223 * - false: don't use time correction
2224 * - int: value of time correction in minutes
2225 * - 'format': format to use, can have the following values:
2226 * - true: use user's preference
2227 * - false: use default preference
2228 * - string: format to use
2229 * @since 1.19
2230 * @return string
2232 public function userTime( $ts, User $user, array $options = array() ) {
2233 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2237 * Get the formatted date and time for the given timestamp and formatted for
2238 * the given user.
2240 * @param mixed $ts the time format which needs to be turned into a
2241 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2242 * @param User $user User object used to get preferences for timezone and format
2243 * @param array $options Array, can contain the following keys:
2244 * - 'timecorrection': time correction, can have the following values:
2245 * - true: use user's preference
2246 * - false: don't use time correction
2247 * - int: value of time correction in minutes
2248 * - 'format': format to use, can have the following values:
2249 * - true: use user's preference
2250 * - false: use default preference
2251 * - string: format to use
2252 * @since 1.19
2253 * @return string
2255 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2256 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2260 * Convert an MWTimestamp into a pretty human-readable timestamp using
2261 * the given user preferences and relative base time.
2263 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2264 * on your timestamp object, which will then call this function. Calling
2265 * this function directly will cause hooks to be skipped over.
2267 * @see MWTimestamp::getHumanTimestamp
2268 * @param MWTimestamp $ts Timestamp to prettify
2269 * @param MWTimestamp $relativeTo Base timestamp
2270 * @param User $user User preferences to use
2271 * @return string Human timestamp
2272 * @since 1.22
2274 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2275 $diff = $ts->diff( $relativeTo );
2276 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2277 (int)$relativeTo->timestamp->format( 'w' ) );
2278 $days = $diff->days ?: (int)$diffDay;
2279 if ( $diff->invert || $days > 5
2280 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2282 // Timestamps are in different years: use full timestamp
2283 // Also do full timestamp for future dates
2285 * @FIXME Add better handling of future timestamps.
2287 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2288 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2289 } elseif ( $days > 5 ) {
2290 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2291 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2292 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2293 } elseif ( $days > 1 ) {
2294 // Timestamp within the past week: show the day of the week and time
2295 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2296 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2297 // Messages:
2298 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2299 $ts = wfMessage( "$weekday-at" )
2300 ->inLanguage( $this )
2301 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2302 ->text();
2303 } elseif ( $days == 1 ) {
2304 // Timestamp was yesterday: say 'yesterday' and the time.
2305 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2306 $ts = wfMessage( 'yesterday-at' )
2307 ->inLanguage( $this )
2308 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2309 ->text();
2310 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2311 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2312 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2313 $ts = wfMessage( 'today-at' )
2314 ->inLanguage( $this )
2315 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2316 ->text();
2318 // From here on in, the timestamp was soon enough ago so that we can simply say
2319 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2320 } elseif ( $diff->h == 1 ) {
2321 // Less than 90 minutes, but more than an hour ago.
2322 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2323 } elseif ( $diff->i >= 1 ) {
2324 // A few minutes ago.
2325 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2326 } elseif ( $diff->s >= 30 ) {
2327 // Less than a minute, but more than 30 sec ago.
2328 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2329 } else {
2330 // Less than 30 seconds ago.
2331 $ts = wfMessage( 'just-now' )->text();
2334 return $ts;
2338 * @param string $key
2339 * @return array|null
2341 function getMessage( $key ) {
2342 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2346 * @return array
2348 function getAllMessages() {
2349 return self::$dataCache->getItem( $this->mCode, 'messages' );
2353 * @param string $in
2354 * @param string $out
2355 * @param string $string
2356 * @return string
2358 function iconv( $in, $out, $string ) {
2359 # This is a wrapper for iconv in all languages except esperanto,
2360 # which does some nasty x-conversions beforehand
2362 # Even with //IGNORE iconv can whine about illegal characters in
2363 # *input* string. We just ignore those too.
2364 # REF: http://bugs.php.net/bug.php?id=37166
2365 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2366 wfSuppressWarnings();
2367 $text = iconv( $in, $out . '//IGNORE', $string );
2368 wfRestoreWarnings();
2369 return $text;
2372 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2375 * @param array $matches
2376 * @return mixed|string
2378 function ucwordbreaksCallbackAscii( $matches ) {
2379 return $this->ucfirst( $matches[1] );
2383 * @param array $matches
2384 * @return string
2386 function ucwordbreaksCallbackMB( $matches ) {
2387 return mb_strtoupper( $matches[0] );
2391 * @param array $matches
2392 * @return string
2394 function ucCallback( $matches ) {
2395 list( $wikiUpperChars ) = self::getCaseMaps();
2396 return strtr( $matches[1], $wikiUpperChars );
2400 * @param array $matches
2401 * @return string
2403 function lcCallback( $matches ) {
2404 list( , $wikiLowerChars ) = self::getCaseMaps();
2405 return strtr( $matches[1], $wikiLowerChars );
2409 * @param array $matches
2410 * @return string
2412 function ucwordsCallbackMB( $matches ) {
2413 return mb_strtoupper( $matches[0] );
2417 * @param array $matches
2418 * @return string
2420 function ucwordsCallbackWiki( $matches ) {
2421 list( $wikiUpperChars ) = self::getCaseMaps();
2422 return strtr( $matches[0], $wikiUpperChars );
2426 * Make a string's first character uppercase
2428 * @param string $str
2430 * @return string
2432 function ucfirst( $str ) {
2433 $o = ord( $str );
2434 if ( $o < 96 ) { // if already uppercase...
2435 return $str;
2436 } elseif ( $o < 128 ) {
2437 return ucfirst( $str ); // use PHP's ucfirst()
2438 } else {
2439 // fall back to more complex logic in case of multibyte strings
2440 return $this->uc( $str, true );
2445 * Convert a string to uppercase
2447 * @param string $str
2448 * @param bool $first
2450 * @return string
2452 function uc( $str, $first = false ) {
2453 if ( function_exists( 'mb_strtoupper' ) ) {
2454 if ( $first ) {
2455 if ( $this->isMultibyte( $str ) ) {
2456 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2457 } else {
2458 return ucfirst( $str );
2460 } else {
2461 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2463 } else {
2464 if ( $this->isMultibyte( $str ) ) {
2465 $x = $first ? '^' : '';
2466 return preg_replace_callback(
2467 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2468 array( $this, 'ucCallback' ),
2469 $str
2471 } else {
2472 return $first ? ucfirst( $str ) : strtoupper( $str );
2478 * @param string $str
2479 * @return mixed|string
2481 function lcfirst( $str ) {
2482 $o = ord( $str );
2483 if ( !$o ) {
2484 return strval( $str );
2485 } elseif ( $o >= 128 ) {
2486 return $this->lc( $str, true );
2487 } elseif ( $o > 96 ) {
2488 return $str;
2489 } else {
2490 $str[0] = strtolower( $str[0] );
2491 return $str;
2496 * @param string $str
2497 * @param bool $first
2498 * @return mixed|string
2500 function lc( $str, $first = false ) {
2501 if ( function_exists( 'mb_strtolower' ) ) {
2502 if ( $first ) {
2503 if ( $this->isMultibyte( $str ) ) {
2504 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2505 } else {
2506 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2508 } else {
2509 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2511 } else {
2512 if ( $this->isMultibyte( $str ) ) {
2513 $x = $first ? '^' : '';
2514 return preg_replace_callback(
2515 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2516 array( $this, 'lcCallback' ),
2517 $str
2519 } else {
2520 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2526 * @param string $str
2527 * @return bool
2529 function isMultibyte( $str ) {
2530 return (bool)preg_match( '/[\x80-\xff]/', $str );
2534 * @param string $str
2535 * @return mixed|string
2537 function ucwords( $str ) {
2538 if ( $this->isMultibyte( $str ) ) {
2539 $str = $this->lc( $str );
2541 // regexp to find first letter in each word (i.e. after each space)
2542 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2544 // function to use to capitalize a single char
2545 if ( function_exists( 'mb_strtoupper' ) ) {
2546 return preg_replace_callback(
2547 $replaceRegexp,
2548 array( $this, 'ucwordsCallbackMB' ),
2549 $str
2551 } else {
2552 return preg_replace_callback(
2553 $replaceRegexp,
2554 array( $this, 'ucwordsCallbackWiki' ),
2555 $str
2558 } else {
2559 return ucwords( strtolower( $str ) );
2564 * capitalize words at word breaks
2566 * @param string $str
2567 * @return mixed
2569 function ucwordbreaks( $str ) {
2570 if ( $this->isMultibyte( $str ) ) {
2571 $str = $this->lc( $str );
2573 // since \b doesn't work for UTF-8, we explicitely define word break chars
2574 $breaks = "[ \-\(\)\}\{\.,\?!]";
2576 // find first letter after word break
2577 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2578 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2580 if ( function_exists( 'mb_strtoupper' ) ) {
2581 return preg_replace_callback(
2582 $replaceRegexp,
2583 array( $this, 'ucwordbreaksCallbackMB' ),
2584 $str
2586 } else {
2587 return preg_replace_callback(
2588 $replaceRegexp,
2589 array( $this, 'ucwordsCallbackWiki' ),
2590 $str
2593 } else {
2594 return preg_replace_callback(
2595 '/\b([\w\x80-\xff]+)\b/',
2596 array( $this, 'ucwordbreaksCallbackAscii' ),
2597 $str
2603 * Return a case-folded representation of $s
2605 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2606 * and $s2 are the same except for the case of their characters. It is not
2607 * necessary for the value returned to make sense when displayed.
2609 * Do *not* perform any other normalisation in this function. If a caller
2610 * uses this function when it should be using a more general normalisation
2611 * function, then fix the caller.
2613 * @param string $s
2615 * @return string
2617 function caseFold( $s ) {
2618 return $this->uc( $s );
2622 * @param string $s
2623 * @return string
2625 function checkTitleEncoding( $s ) {
2626 if ( is_array( $s ) ) {
2627 throw new MWException( 'Given array to checkTitleEncoding.' );
2629 if ( StringUtils::isUtf8( $s ) ) {
2630 return $s;
2633 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2637 * @return array
2639 function fallback8bitEncoding() {
2640 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2644 * Most writing systems use whitespace to break up words.
2645 * Some languages such as Chinese don't conventionally do this,
2646 * which requires special handling when breaking up words for
2647 * searching etc.
2649 * @return bool
2651 function hasWordBreaks() {
2652 return true;
2656 * Some languages such as Chinese require word segmentation,
2657 * Specify such segmentation when overridden in derived class.
2659 * @param string $string
2660 * @return string
2662 function segmentByWord( $string ) {
2663 return $string;
2667 * Some languages have special punctuation need to be normalized.
2668 * Make such changes here.
2670 * @param string $string
2671 * @return string
2673 function normalizeForSearch( $string ) {
2674 return self::convertDoubleWidth( $string );
2678 * convert double-width roman characters to single-width.
2679 * range: ff00-ff5f ~= 0020-007f
2681 * @param string $string
2683 * @return string
2685 protected static function convertDoubleWidth( $string ) {
2686 static $full = null;
2687 static $half = null;
2689 if ( $full === null ) {
2690 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2691 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2692 $full = str_split( $fullWidth, 3 );
2693 $half = str_split( $halfWidth );
2696 $string = str_replace( $full, $half, $string );
2697 return $string;
2701 * @param string $string
2702 * @param string $pattern
2703 * @return string
2705 protected static function insertSpace( $string, $pattern ) {
2706 $string = preg_replace( $pattern, " $1 ", $string );
2707 $string = preg_replace( '/ +/', ' ', $string );
2708 return $string;
2712 * @param array $termsArray
2713 * @return array
2715 function convertForSearchResult( $termsArray ) {
2716 # some languages, e.g. Chinese, need to do a conversion
2717 # in order for search results to be displayed correctly
2718 return $termsArray;
2722 * Get the first character of a string.
2724 * @param string $s
2725 * @return string
2727 function firstChar( $s ) {
2728 $matches = array();
2729 preg_match(
2730 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2731 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2733 $matches
2736 if ( isset( $matches[1] ) ) {
2737 if ( strlen( $matches[1] ) != 3 ) {
2738 return $matches[1];
2741 // Break down Hangul syllables to grab the first jamo
2742 $code = utf8ToCodepoint( $matches[1] );
2743 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2744 return $matches[1];
2745 } elseif ( $code < 0xb098 ) {
2746 return "\xe3\x84\xb1";
2747 } elseif ( $code < 0xb2e4 ) {
2748 return "\xe3\x84\xb4";
2749 } elseif ( $code < 0xb77c ) {
2750 return "\xe3\x84\xb7";
2751 } elseif ( $code < 0xb9c8 ) {
2752 return "\xe3\x84\xb9";
2753 } elseif ( $code < 0xbc14 ) {
2754 return "\xe3\x85\x81";
2755 } elseif ( $code < 0xc0ac ) {
2756 return "\xe3\x85\x82";
2757 } elseif ( $code < 0xc544 ) {
2758 return "\xe3\x85\x85";
2759 } elseif ( $code < 0xc790 ) {
2760 return "\xe3\x85\x87";
2761 } elseif ( $code < 0xcc28 ) {
2762 return "\xe3\x85\x88";
2763 } elseif ( $code < 0xce74 ) {
2764 return "\xe3\x85\x8a";
2765 } elseif ( $code < 0xd0c0 ) {
2766 return "\xe3\x85\x8b";
2767 } elseif ( $code < 0xd30c ) {
2768 return "\xe3\x85\x8c";
2769 } elseif ( $code < 0xd558 ) {
2770 return "\xe3\x85\x8d";
2771 } else {
2772 return "\xe3\x85\x8e";
2774 } else {
2775 return '';
2779 function initEncoding() {
2780 # Some languages may have an alternate char encoding option
2781 # (Esperanto X-coding, Japanese furigana conversion, etc)
2782 # If this language is used as the primary content language,
2783 # an override to the defaults can be set here on startup.
2787 * @param string $s
2788 * @return string
2790 function recodeForEdit( $s ) {
2791 # For some languages we'll want to explicitly specify
2792 # which characters make it into the edit box raw
2793 # or are converted in some way or another.
2794 global $wgEditEncoding;
2795 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2796 return $s;
2797 } else {
2798 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2803 * @param string $s
2804 * @return string
2806 function recodeInput( $s ) {
2807 # Take the previous into account.
2808 global $wgEditEncoding;
2809 if ( $wgEditEncoding != '' ) {
2810 $enc = $wgEditEncoding;
2811 } else {
2812 $enc = 'UTF-8';
2814 if ( $enc == 'UTF-8' ) {
2815 return $s;
2816 } else {
2817 return $this->iconv( $enc, 'UTF-8', $s );
2822 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2823 * also cleans up certain backwards-compatible sequences, converting them
2824 * to the modern Unicode equivalent.
2826 * This is language-specific for performance reasons only.
2828 * @param string $s
2830 * @return string
2832 function normalize( $s ) {
2833 global $wgAllUnicodeFixes;
2834 $s = UtfNormal::cleanUp( $s );
2835 if ( $wgAllUnicodeFixes ) {
2836 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2837 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2840 return $s;
2844 * Transform a string using serialized data stored in the given file (which
2845 * must be in the serialized subdirectory of $IP). The file contains pairs
2846 * mapping source characters to destination characters.
2848 * The data is cached in process memory. This will go faster if you have the
2849 * FastStringSearch extension.
2851 * @param string $file
2852 * @param string $string
2854 * @throws MWException
2855 * @return string
2857 function transformUsingPairFile( $file, $string ) {
2858 if ( !isset( $this->transformData[$file] ) ) {
2859 $data = wfGetPrecompiledData( $file );
2860 if ( $data === false ) {
2861 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2863 $this->transformData[$file] = new ReplacementArray( $data );
2865 return $this->transformData[$file]->replace( $string );
2869 * For right-to-left language support
2871 * @return bool
2873 function isRTL() {
2874 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2878 * Return the correct HTML 'dir' attribute value for this language.
2879 * @return string
2881 function getDir() {
2882 return $this->isRTL() ? 'rtl' : 'ltr';
2886 * Return 'left' or 'right' as appropriate alignment for line-start
2887 * for this language's text direction.
2889 * Should be equivalent to CSS3 'start' text-align value....
2891 * @return string
2893 function alignStart() {
2894 return $this->isRTL() ? 'right' : 'left';
2898 * Return 'right' or 'left' as appropriate alignment for line-end
2899 * for this language's text direction.
2901 * Should be equivalent to CSS3 'end' text-align value....
2903 * @return string
2905 function alignEnd() {
2906 return $this->isRTL() ? 'left' : 'right';
2910 * A hidden direction mark (LRM or RLM), depending on the language direction.
2911 * Unlike getDirMark(), this function returns the character as an HTML entity.
2912 * This function should be used when the output is guaranteed to be HTML,
2913 * because it makes the output HTML source code more readable. When
2914 * the output is plain text or can be escaped, getDirMark() should be used.
2916 * @param bool $opposite Get the direction mark opposite to your language
2917 * @return string
2918 * @since 1.20
2920 function getDirMarkEntity( $opposite = false ) {
2921 if ( $opposite ) {
2922 return $this->isRTL() ? '&lrm;' : '&rlm;';
2924 return $this->isRTL() ? '&rlm;' : '&lrm;';
2928 * A hidden direction mark (LRM or RLM), depending on the language direction.
2929 * This function produces them as invisible Unicode characters and
2930 * the output may be hard to read and debug, so it should only be used
2931 * when the output is plain text or can be escaped. When the output is
2932 * HTML, use getDirMarkEntity() instead.
2934 * @param bool $opposite Get the direction mark opposite to your language
2935 * @return string
2937 function getDirMark( $opposite = false ) {
2938 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2939 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2940 if ( $opposite ) {
2941 return $this->isRTL() ? $lrm : $rlm;
2943 return $this->isRTL() ? $rlm : $lrm;
2947 * @return array
2949 function capitalizeAllNouns() {
2950 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2954 * An arrow, depending on the language direction.
2956 * @param string $direction The direction of the arrow: forwards (default),
2957 * backwards, left, right, up, down.
2958 * @return string
2960 function getArrow( $direction = 'forwards' ) {
2961 switch ( $direction ) {
2962 case 'forwards':
2963 return $this->isRTL() ? '←' : '→';
2964 case 'backwards':
2965 return $this->isRTL() ? '→' : '←';
2966 case 'left':
2967 return '←';
2968 case 'right':
2969 return '→';
2970 case 'up':
2971 return '↑';
2972 case 'down':
2973 return '↓';
2978 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2980 * @return bool
2982 function linkPrefixExtension() {
2983 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2987 * Get all magic words from cache.
2988 * @return array
2990 function getMagicWords() {
2991 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2995 * Run the LanguageGetMagic hook once.
2997 protected function doMagicHook() {
2998 if ( $this->mMagicHookDone ) {
2999 return;
3001 $this->mMagicHookDone = true;
3002 wfProfileIn( 'LanguageGetMagic' );
3003 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3004 wfProfileOut( 'LanguageGetMagic' );
3008 * Fill a MagicWord object with data from here
3010 * @param MagicWord $mw
3012 function getMagic( $mw ) {
3013 // Saves a function call
3014 if ( ! $this->mMagicHookDone ) {
3015 $this->doMagicHook();
3018 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3019 $rawEntry = $this->mMagicExtensions[$mw->mId];
3020 } else {
3021 $rawEntry = self::$dataCache->getSubitem(
3022 $this->mCode, 'magicWords', $mw->mId );
3025 if ( !is_array( $rawEntry ) ) {
3026 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3027 } else {
3028 $mw->mCaseSensitive = $rawEntry[0];
3029 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3034 * Add magic words to the extension array
3036 * @param array $newWords
3038 function addMagicWordsByLang( $newWords ) {
3039 $fallbackChain = $this->getFallbackLanguages();
3040 $fallbackChain = array_reverse( $fallbackChain );
3041 foreach ( $fallbackChain as $code ) {
3042 if ( isset( $newWords[$code] ) ) {
3043 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3049 * Get special page names, as an associative array
3050 * case folded alias => real name
3052 function getSpecialPageAliases() {
3053 // Cache aliases because it may be slow to load them
3054 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3055 // Initialise array
3056 $this->mExtendedSpecialPageAliases =
3057 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3058 wfRunHooks( 'LanguageGetSpecialPageAliases',
3059 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3062 return $this->mExtendedSpecialPageAliases;
3066 * Italic is unsuitable for some languages
3068 * @param string $text The text to be emphasized.
3069 * @return string
3071 function emphasize( $text ) {
3072 return "<em>$text</em>";
3076 * Normally we output all numbers in plain en_US style, that is
3077 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3078 * point twohundredthirtyfive. However this is not suitable for all
3079 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3080 * Icelandic just want to use commas instead of dots, and dots instead
3081 * of commas like "293.291,235".
3083 * An example of this function being called:
3084 * <code>
3085 * wfMessage( 'message' )->numParams( $num )->text()
3086 * </code>
3088 * See $separatorTransformTable on MessageIs.php for
3089 * the , => . and . => , implementation.
3091 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3092 * @param int|float $number The string to be formatted, should be an integer
3093 * or a floating point number.
3094 * @param bool $nocommafy Set to true for special numbers like dates
3095 * @return string
3097 public function formatNum( $number, $nocommafy = false ) {
3098 global $wgTranslateNumerals;
3099 if ( !$nocommafy ) {
3100 $number = $this->commafy( $number );
3101 $s = $this->separatorTransformTable();
3102 if ( $s ) {
3103 $number = strtr( $number, $s );
3107 if ( $wgTranslateNumerals ) {
3108 $s = $this->digitTransformTable();
3109 if ( $s ) {
3110 $number = strtr( $number, $s );
3114 return $number;
3118 * Front-end for non-commafied formatNum
3120 * @param int|float $number The string to be formatted, should be an integer
3121 * or a floating point number.
3122 * @since 1.21
3123 * @return string
3125 public function formatNumNoSeparators( $number ) {
3126 return $this->formatNum( $number, true );
3130 * @param string $number
3131 * @return string
3133 function parseFormattedNumber( $number ) {
3134 $s = $this->digitTransformTable();
3135 if ( $s ) {
3136 $number = strtr( $number, array_flip( $s ) );
3139 $s = $this->separatorTransformTable();
3140 if ( $s ) {
3141 $number = strtr( $number, array_flip( $s ) );
3144 $number = strtr( $number, array( ',' => '' ) );
3145 return $number;
3149 * Adds commas to a given number
3150 * @since 1.19
3151 * @param mixed $number
3152 * @return string
3154 function commafy( $number ) {
3155 $digitGroupingPattern = $this->digitGroupingPattern();
3156 if ( $number === null ) {
3157 return '';
3160 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3161 // default grouping is at thousands, use the same for ###,###,### pattern too.
3162 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3163 } else {
3164 // Ref: http://cldr.unicode.org/translation/number-patterns
3165 $sign = "";
3166 if ( intval( $number ) < 0 ) {
3167 // For negative numbers apply the algorithm like positive number and add sign.
3168 $sign = "-";
3169 $number = substr( $number, 1 );
3171 $integerPart = array();
3172 $decimalPart = array();
3173 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3174 preg_match( "/\d+/", $number, $integerPart );
3175 preg_match( "/\.\d*/", $number, $decimalPart );
3176 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3177 if ( $groupedNumber === $number ) {
3178 // the string does not have any number part. Eg: .12345
3179 return $sign . $groupedNumber;
3181 $start = $end = strlen( $integerPart[0] );
3182 while ( $start > 0 ) {
3183 $match = $matches[0][$numMatches - 1];
3184 $matchLen = strlen( $match );
3185 $start = $end - $matchLen;
3186 if ( $start < 0 ) {
3187 $start = 0;
3189 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3190 $end = $start;
3191 if ( $numMatches > 1 ) {
3192 // use the last pattern for the rest of the number
3193 $numMatches--;
3195 if ( $start > 0 ) {
3196 $groupedNumber = "," . $groupedNumber;
3199 return $sign . $groupedNumber;
3204 * @return string
3206 function digitGroupingPattern() {
3207 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3211 * @return array
3213 function digitTransformTable() {
3214 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3218 * @return array
3220 function separatorTransformTable() {
3221 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3225 * Take a list of strings and build a locale-friendly comma-separated
3226 * list, using the local comma-separator message.
3227 * The last two strings are chained with an "and".
3228 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3230 * @param string[] $l
3231 * @return string
3233 function listToText( array $l ) {
3234 $m = count( $l ) - 1;
3235 if ( $m < 0 ) {
3236 return '';
3238 if ( $m > 0 ) {
3239 $and = $this->getMessageFromDB( 'and' );
3240 $space = $this->getMessageFromDB( 'word-separator' );
3241 if ( $m > 1 ) {
3242 $comma = $this->getMessageFromDB( 'comma-separator' );
3245 $s = $l[$m];
3246 for ( $i = $m - 1; $i >= 0; $i-- ) {
3247 if ( $i == $m - 1 ) {
3248 $s = $l[$i] . $and . $space . $s;
3249 } else {
3250 $s = $l[$i] . $comma . $s;
3253 return $s;
3257 * Take a list of strings and build a locale-friendly comma-separated
3258 * list, using the local comma-separator message.
3259 * @param string[] $list Array of strings to put in a comma list
3260 * @return string
3262 function commaList( array $list ) {
3263 return implode(
3264 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3265 $list
3270 * Take a list of strings and build a locale-friendly semicolon-separated
3271 * list, using the local semicolon-separator message.
3272 * @param string[] $list Array of strings to put in a semicolon list
3273 * @return string
3275 function semicolonList( array $list ) {
3276 return implode(
3277 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3278 $list
3283 * Same as commaList, but separate it with the pipe instead.
3284 * @param string[] $list Array of strings to put in a pipe list
3285 * @return string
3287 function pipeList( array $list ) {
3288 return implode(
3289 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3290 $list
3295 * Truncate a string to a specified length in bytes, appending an optional
3296 * string (e.g. for ellipses)
3298 * The database offers limited byte lengths for some columns in the database;
3299 * multi-byte character sets mean we need to ensure that only whole characters
3300 * are included, otherwise broken characters can be passed to the user
3302 * If $length is negative, the string will be truncated from the beginning
3304 * @param string $string String to truncate
3305 * @param int $length Maximum length (including ellipses)
3306 * @param string $ellipsis String to append to the truncated text
3307 * @param bool $adjustLength Subtract length of ellipsis from $length.
3308 * $adjustLength was introduced in 1.18, before that behaved as if false.
3309 * @return string
3311 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3312 # Use the localized ellipsis character
3313 if ( $ellipsis == '...' ) {
3314 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3316 # Check if there is no need to truncate
3317 if ( $length == 0 ) {
3318 return $ellipsis; // convention
3319 } elseif ( strlen( $string ) <= abs( $length ) ) {
3320 return $string; // no need to truncate
3322 $stringOriginal = $string;
3323 # If ellipsis length is >= $length then we can't apply $adjustLength
3324 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3325 $string = $ellipsis; // this can be slightly unexpected
3326 # Otherwise, truncate and add ellipsis...
3327 } else {
3328 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3329 if ( $length > 0 ) {
3330 $length -= $eLength;
3331 $string = substr( $string, 0, $length ); // xyz...
3332 $string = $this->removeBadCharLast( $string );
3333 $string = rtrim( $string );
3334 $string = $string . $ellipsis;
3335 } else {
3336 $length += $eLength;
3337 $string = substr( $string, $length ); // ...xyz
3338 $string = $this->removeBadCharFirst( $string );
3339 $string = ltrim( $string );
3340 $string = $ellipsis . $string;
3343 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3344 # This check is *not* redundant if $adjustLength, due to the single case where
3345 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3346 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3347 return $string;
3348 } else {
3349 return $stringOriginal;
3354 * Remove bytes that represent an incomplete Unicode character
3355 * at the end of string (e.g. bytes of the char are missing)
3357 * @param string $string
3358 * @return string
3360 protected function removeBadCharLast( $string ) {
3361 if ( $string != '' ) {
3362 $char = ord( $string[strlen( $string ) - 1] );
3363 $m = array();
3364 if ( $char >= 0xc0 ) {
3365 # We got the first byte only of a multibyte char; remove it.
3366 $string = substr( $string, 0, -1 );
3367 } elseif ( $char >= 0x80 &&
3368 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3369 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3371 # We chopped in the middle of a character; remove it
3372 $string = $m[1];
3375 return $string;
3379 * Remove bytes that represent an incomplete Unicode character
3380 * at the start of string (e.g. bytes of the char are missing)
3382 * @param string $string
3383 * @return string
3385 protected function removeBadCharFirst( $string ) {
3386 if ( $string != '' ) {
3387 $char = ord( $string[0] );
3388 if ( $char >= 0x80 && $char < 0xc0 ) {
3389 # We chopped in the middle of a character; remove the whole thing
3390 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3393 return $string;
3397 * Truncate a string of valid HTML to a specified length in bytes,
3398 * appending an optional string (e.g. for ellipses), and return valid HTML
3400 * This is only intended for styled/linked text, such as HTML with
3401 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3402 * Also, this will not detect things like "display:none" CSS.
3404 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3406 * @param string $text HTML string to truncate
3407 * @param int $length (zero/positive) Maximum length (including ellipses)
3408 * @param string $ellipsis String to append to the truncated text
3409 * @return string
3411 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3412 # Use the localized ellipsis character
3413 if ( $ellipsis == '...' ) {
3414 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3416 # Check if there is clearly no need to truncate
3417 if ( $length <= 0 ) {
3418 return $ellipsis; // no text shown, nothing to format (convention)
3419 } elseif ( strlen( $text ) <= $length ) {
3420 return $text; // string short enough even *with* HTML (short-circuit)
3423 $dispLen = 0; // innerHTML legth so far
3424 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3425 $tagType = 0; // 0-open, 1-close
3426 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3427 $entityState = 0; // 0-not entity, 1-entity
3428 $tag = $ret = ''; // accumulated tag name, accumulated result string
3429 $openTags = array(); // open tag stack
3430 $maybeState = null; // possible truncation state
3432 $textLen = strlen( $text );
3433 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3434 for ( $pos = 0; true; ++$pos ) {
3435 # Consider truncation once the display length has reached the maximim.
3436 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3437 # Check that we're not in the middle of a bracket/entity...
3438 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3439 if ( !$testingEllipsis ) {
3440 $testingEllipsis = true;
3441 # Save where we are; we will truncate here unless there turn out to
3442 # be so few remaining characters that truncation is not necessary.
3443 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3444 $maybeState = array( $ret, $openTags ); // save state
3446 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3447 # String in fact does need truncation, the truncation point was OK.
3448 list( $ret, $openTags ) = $maybeState; // reload state
3449 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3450 $ret .= $ellipsis; // add ellipsis
3451 break;
3454 if ( $pos >= $textLen ) {
3455 break; // extra iteration just for above checks
3458 # Read the next char...
3459 $ch = $text[$pos];
3460 $lastCh = $pos ? $text[$pos - 1] : '';
3461 $ret .= $ch; // add to result string
3462 if ( $ch == '<' ) {
3463 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3464 $entityState = 0; // for bad HTML
3465 $bracketState = 1; // tag started (checking for backslash)
3466 } elseif ( $ch == '>' ) {
3467 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3468 $entityState = 0; // for bad HTML
3469 $bracketState = 0; // out of brackets
3470 } elseif ( $bracketState == 1 ) {
3471 if ( $ch == '/' ) {
3472 $tagType = 1; // close tag (e.g. "</span>")
3473 } else {
3474 $tagType = 0; // open tag (e.g. "<span>")
3475 $tag .= $ch;
3477 $bracketState = 2; // building tag name
3478 } elseif ( $bracketState == 2 ) {
3479 if ( $ch != ' ' ) {
3480 $tag .= $ch;
3481 } else {
3482 // Name found (e.g. "<a href=..."), add on tag attributes...
3483 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3485 } elseif ( $bracketState == 0 ) {
3486 if ( $entityState ) {
3487 if ( $ch == ';' ) {
3488 $entityState = 0;
3489 $dispLen++; // entity is one displayed char
3491 } else {
3492 if ( $neLength == 0 && !$maybeState ) {
3493 // Save state without $ch. We want to *hit* the first
3494 // display char (to get tags) but not *use* it if truncating.
3495 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3497 if ( $ch == '&' ) {
3498 $entityState = 1; // entity found, (e.g. "&#160;")
3499 } else {
3500 $dispLen++; // this char is displayed
3501 // Add the next $max display text chars after this in one swoop...
3502 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3503 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3504 $dispLen += $skipped;
3505 $pos += $skipped;
3510 // Close the last tag if left unclosed by bad HTML
3511 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3512 while ( count( $openTags ) > 0 ) {
3513 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3515 return $ret;
3519 * truncateHtml() helper function
3520 * like strcspn() but adds the skipped chars to $ret
3522 * @param string $ret
3523 * @param string $text
3524 * @param string $search
3525 * @param int $start
3526 * @param null|int $len
3527 * @return int
3529 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3530 if ( $len === null ) {
3531 $len = -1; // -1 means "no limit" for strcspn
3532 } elseif ( $len < 0 ) {
3533 $len = 0; // sanity
3535 $skipCount = 0;
3536 if ( $start < strlen( $text ) ) {
3537 $skipCount = strcspn( $text, $search, $start, $len );
3538 $ret .= substr( $text, $start, $skipCount );
3540 return $skipCount;
3544 * truncateHtml() helper function
3545 * (a) push or pop $tag from $openTags as needed
3546 * (b) clear $tag value
3547 * @param string &$tag Current HTML tag name we are looking at
3548 * @param int $tagType (0-open tag, 1-close tag)
3549 * @param string $lastCh Character before the '>' that ended this tag
3550 * @param array &$openTags Open tag stack (not accounting for $tag)
3552 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3553 $tag = ltrim( $tag );
3554 if ( $tag != '' ) {
3555 if ( $tagType == 0 && $lastCh != '/' ) {
3556 $openTags[] = $tag; // tag opened (didn't close itself)
3557 } elseif ( $tagType == 1 ) {
3558 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3559 array_pop( $openTags ); // tag closed
3562 $tag = '';
3567 * Grammatical transformations, needed for inflected languages
3568 * Invoked by putting {{grammar:case|word}} in a message
3570 * @param string $word
3571 * @param string $case
3572 * @return string
3574 function convertGrammar( $word, $case ) {
3575 global $wgGrammarForms;
3576 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3577 return $wgGrammarForms[$this->getCode()][$case][$word];
3580 return $word;
3583 * Get the grammar forms for the content language
3584 * @return array Array of grammar forms
3585 * @since 1.20
3587 function getGrammarForms() {
3588 global $wgGrammarForms;
3589 if ( isset( $wgGrammarForms[$this->getCode()] )
3590 && is_array( $wgGrammarForms[$this->getCode()] )
3592 return $wgGrammarForms[$this->getCode()];
3595 return array();
3598 * Provides an alternative text depending on specified gender.
3599 * Usage {{gender:username|masculine|feminine|unknown}}.
3600 * username is optional, in which case the gender of current user is used,
3601 * but only in (some) interface messages; otherwise default gender is used.
3603 * If no forms are given, an empty string is returned. If only one form is
3604 * given, it will be returned unconditionally. These details are implied by
3605 * the caller and cannot be overridden in subclasses.
3607 * If three forms are given, the default is to use the third (unknown) form.
3608 * If fewer than three forms are given, the default is to use the first (masculine) form.
3609 * These details can be overridden in subclasses.
3611 * @param string $gender
3612 * @param array $forms
3614 * @return string
3616 function gender( $gender, $forms ) {
3617 if ( !count( $forms ) ) {
3618 return '';
3620 $forms = $this->preConvertPlural( $forms, 2 );
3621 if ( $gender === 'male' ) {
3622 return $forms[0];
3624 if ( $gender === 'female' ) {
3625 return $forms[1];
3627 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3631 * Plural form transformations, needed for some languages.
3632 * For example, there are 3 form of plural in Russian and Polish,
3633 * depending on "count mod 10". See [[w:Plural]]
3634 * For English it is pretty simple.
3636 * Invoked by putting {{plural:count|wordform1|wordform2}}
3637 * or {{plural:count|wordform1|wordform2|wordform3}}
3639 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3641 * @param int $count Non-localized number
3642 * @param array $forms Different plural forms
3643 * @return string Correct form of plural for $count in this language
3645 function convertPlural( $count, $forms ) {
3646 // Handle explicit n=pluralform cases
3647 $forms = $this->handleExplicitPluralForms( $count, $forms );
3648 if ( is_string( $forms ) ) {
3649 return $forms;
3651 if ( !count( $forms ) ) {
3652 return '';
3655 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3656 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3657 return $forms[$pluralForm];
3661 * Handles explicit plural forms for Language::convertPlural()
3663 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3664 * If an explicitly defined plural form matches the $count, then
3665 * string value returned, otherwise array returned for further consideration
3666 * by CLDR rules or overridden convertPlural().
3668 * @since 1.23
3670 * @param int $count non-localized number
3671 * @param array $forms different plural forms
3673 * @return array|string
3675 protected function handleExplicitPluralForms( $count, array $forms ) {
3676 foreach ( $forms as $index => $form ) {
3677 if ( preg_match( '/\d+=/i', $form ) ) {
3678 $pos = strpos( $form, '=' );
3679 if ( substr( $form, 0, $pos ) === (string) $count ) {
3680 return substr( $form, $pos + 1 );
3682 unset( $forms[$index] );
3685 return array_values( $forms );
3689 * Checks that convertPlural was given an array and pads it to requested
3690 * amount of forms by copying the last one.
3692 * @param int $count How many forms should there be at least
3693 * @param array $forms Array of forms given to convertPlural
3694 * @return array Padded array of forms or an exception if not an array
3696 protected function preConvertPlural( /* Array */ $forms, $count ) {
3697 while ( count( $forms ) < $count ) {
3698 $forms[] = $forms[count( $forms ) - 1];
3700 return $forms;
3704 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3705 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3706 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3707 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3708 * match up with it.
3710 * @param string $str The validated block duration in English
3711 * @return string Somehow translated block duration
3712 * @see LanguageFi.php for example implementation
3714 function translateBlockExpiry( $str ) {
3715 $duration = SpecialBlock::getSuggestedDurations( $this );
3716 foreach ( $duration as $show => $value ) {
3717 if ( strcmp( $str, $value ) == 0 ) {
3718 return htmlspecialchars( trim( $show ) );
3722 // Since usually only infinite or indefinite is only on list, so try
3723 // equivalents if still here.
3724 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3725 if ( in_array( $str, $indefs ) ) {
3726 foreach ( $indefs as $val ) {
3727 $show = array_search( $val, $duration, true );
3728 if ( $show !== false ) {
3729 return htmlspecialchars( trim( $show ) );
3734 // If all else fails, return a standard duration or timestamp description.
3735 $time = strtotime( $str, 0 );
3736 if ( $time === false ) { // Unknown format. Return it as-is in case.
3737 return $str;
3738 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3739 // $time is relative to 0 so it's a duration length.
3740 return $this->formatDuration( $time );
3741 } else { // It's an absolute timestamp.
3742 if ( $time === 0 ) {
3743 // wfTimestamp() handles 0 as current time instead of epoch.
3744 return $this->timeanddate( '19700101000000' );
3745 } else {
3746 return $this->timeanddate( $time );
3752 * languages like Chinese need to be segmented in order for the diff
3753 * to be of any use
3755 * @param string $text
3756 * @return string
3758 public function segmentForDiff( $text ) {
3759 return $text;
3763 * and unsegment to show the result
3765 * @param string $text
3766 * @return string
3768 public function unsegmentForDiff( $text ) {
3769 return $text;
3773 * Return the LanguageConverter used in the Language
3775 * @since 1.19
3776 * @return LanguageConverter
3778 public function getConverter() {
3779 return $this->mConverter;
3783 * convert text to all supported variants
3785 * @param string $text
3786 * @return array
3788 public function autoConvertToAllVariants( $text ) {
3789 return $this->mConverter->autoConvertToAllVariants( $text );
3793 * convert text to different variants of a language.
3795 * @param string $text
3796 * @return string
3798 public function convert( $text ) {
3799 return $this->mConverter->convert( $text );
3803 * Convert a Title object to a string in the preferred variant
3805 * @param Title $title
3806 * @return string
3808 public function convertTitle( $title ) {
3809 return $this->mConverter->convertTitle( $title );
3813 * Convert a namespace index to a string in the preferred variant
3815 * @param int $ns
3816 * @return string
3818 public function convertNamespace( $ns ) {
3819 return $this->mConverter->convertNamespace( $ns );
3823 * Check if this is a language with variants
3825 * @return bool
3827 public function hasVariants() {
3828 return count( $this->getVariants() ) > 1;
3832 * Check if the language has the specific variant
3834 * @since 1.19
3835 * @param string $variant
3836 * @return bool
3838 public function hasVariant( $variant ) {
3839 return (bool)$this->mConverter->validateVariant( $variant );
3843 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3845 * @param string $text
3846 * @return string
3847 * @deprecated since 1.22 is no longer used
3849 public function armourMath( $text ) {
3850 return $this->mConverter->armourMath( $text );
3854 * Perform output conversion on a string, and encode for safe HTML output.
3855 * @param string $text Text to be converted
3856 * @param bool $isTitle Whether this conversion is for the article title
3857 * @return string
3858 * @todo this should get integrated somewhere sane
3860 public function convertHtml( $text, $isTitle = false ) {
3861 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3865 * @param string $key
3866 * @return string
3868 public function convertCategoryKey( $key ) {
3869 return $this->mConverter->convertCategoryKey( $key );
3873 * Get the list of variants supported by this language
3874 * see sample implementation in LanguageZh.php
3876 * @return array an array of language codes
3878 public function getVariants() {
3879 return $this->mConverter->getVariants();
3883 * @return string
3885 public function getPreferredVariant() {
3886 return $this->mConverter->getPreferredVariant();
3890 * @return string
3892 public function getDefaultVariant() {
3893 return $this->mConverter->getDefaultVariant();
3897 * @return string
3899 public function getURLVariant() {
3900 return $this->mConverter->getURLVariant();
3904 * If a language supports multiple variants, it is
3905 * possible that non-existing link in one variant
3906 * actually exists in another variant. this function
3907 * tries to find it. See e.g. LanguageZh.php
3909 * @param string $link The name of the link
3910 * @param Title $nt The title object of the link
3911 * @param bool $ignoreOtherCond To disable other conditions when
3912 * we need to transclude a template or update a category's link
3913 * @return null the input parameters may be modified upon return
3915 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3916 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3920 * returns language specific options used by User::getPageRenderHash()
3921 * for example, the preferred language variant
3923 * @return string
3925 function getExtraHashOptions() {
3926 return $this->mConverter->getExtraHashOptions();
3930 * For languages that support multiple variants, the title of an
3931 * article may be displayed differently in different variants. this
3932 * function returns the apporiate title defined in the body of the article.
3934 * @return string
3936 public function getParsedTitle() {
3937 return $this->mConverter->getParsedTitle();
3941 * Prepare external link text for conversion. When the text is
3942 * a URL, it shouldn't be converted, and it'll be wrapped in
3943 * the "raw" tag (-{R| }-) to prevent conversion.
3945 * This function is called "markNoConversion" for historical
3946 * reasons.
3948 * @param string $text Text to be used for external link
3949 * @param bool $noParse Wrap it without confirming it's a real URL first
3950 * @return string The tagged text
3952 public function markNoConversion( $text, $noParse = false ) {
3953 // Excluding protocal-relative URLs may avoid many false positives.
3954 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3955 return $this->mConverter->markNoConversion( $text );
3956 } else {
3957 return $text;
3962 * A regular expression to match legal word-trailing characters
3963 * which should be merged onto a link of the form [[foo]]bar.
3965 * @return string
3967 public function linkTrail() {
3968 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3972 * A regular expression character set to match legal word-prefixing
3973 * characters which should be merged onto a link of the form foo[[bar]].
3975 * @return string
3977 public function linkPrefixCharset() {
3978 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
3982 * @return Language
3984 function getLangObj() {
3985 return $this;
3989 * Get the "parent" language which has a converter to convert a "compatible" language
3990 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
3992 * @return Language|null
3993 * @since 1.22
3995 public function getParentLanguage() {
3996 if ( $this->mParentLanguage !== false ) {
3997 return $this->mParentLanguage;
4000 $pieces = explode( '-', $this->getCode() );
4001 $code = $pieces[0];
4002 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4003 $this->mParentLanguage = null;
4004 return null;
4006 $lang = Language::factory( $code );
4007 if ( !$lang->hasVariant( $this->getCode() ) ) {
4008 $this->mParentLanguage = null;
4009 return null;
4012 $this->mParentLanguage = $lang;
4013 return $lang;
4017 * Get the RFC 3066 code for this language object
4019 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4020 * htmlspecialchars() or similar
4022 * @return string
4024 public function getCode() {
4025 return $this->mCode;
4029 * Get the code in Bcp47 format which we can use
4030 * inside of html lang="" tags.
4032 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4033 * htmlspecialchars() or similar.
4035 * @since 1.19
4036 * @return string
4038 public function getHtmlCode() {
4039 if ( is_null( $this->mHtmlCode ) ) {
4040 $this->mHtmlCode = wfBCP47( $this->getCode() );
4042 return $this->mHtmlCode;
4046 * @param string $code
4048 public function setCode( $code ) {
4049 $this->mCode = $code;
4050 // Ensure we don't leave incorrect cached data lying around
4051 $this->mHtmlCode = null;
4052 $this->mParentLanguage = false;
4056 * Get the name of a file for a certain language code
4057 * @param string $prefix Prepend this to the filename
4058 * @param string $code Language code
4059 * @param string $suffix Append this to the filename
4060 * @throws MWException
4061 * @return string $prefix . $mangledCode . $suffix
4063 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4064 if ( !self::isValidBuiltInCode( $code ) ) {
4065 throw new MWException( "Invalid language code \"$code\"" );
4068 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4072 * Get the language code from a file name. Inverse of getFileName()
4073 * @param string $filename $prefix . $languageCode . $suffix
4074 * @param string $prefix Prefix before the language code
4075 * @param string $suffix Suffix after the language code
4076 * @return string Language code, or false if $prefix or $suffix isn't found
4078 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4079 $m = null;
4080 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4081 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4082 if ( !count( $m ) ) {
4083 return false;
4085 return str_replace( '_', '-', strtolower( $m[1] ) );
4089 * @param string $code
4090 * @return string
4092 public static function getMessagesFileName( $code ) {
4093 global $IP;
4094 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4095 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4096 return $file;
4100 * @param string $code
4101 * @return string
4102 * @since 1.23
4104 public static function getJsonMessagesFileName( $code ) {
4105 global $IP;
4107 if ( !self::isValidBuiltInCode( $code ) ) {
4108 throw new MWException( "Invalid language code \"$code\"" );
4111 return "$IP/languages/i18n/$code.json";
4115 * @param string $code
4116 * @return string
4118 public static function getClassFileName( $code ) {
4119 global $IP;
4120 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4124 * Get the first fallback for a given language.
4126 * @param string $code
4128 * @return bool|string
4130 public static function getFallbackFor( $code ) {
4131 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4132 return false;
4133 } else {
4134 $fallbacks = self::getFallbacksFor( $code );
4135 $first = array_shift( $fallbacks );
4136 return $first;
4141 * Get the ordered list of fallback languages.
4143 * @since 1.19
4144 * @param string $code Language code
4145 * @return array
4147 public static function getFallbacksFor( $code ) {
4148 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4149 return array();
4150 } else {
4151 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4152 $v = array_map( 'trim', explode( ',', $v ) );
4153 if ( $v[count( $v ) - 1] !== 'en' ) {
4154 $v[] = 'en';
4156 return $v;
4161 * Get the ordered list of fallback languages, ending with the fallback
4162 * language chain for the site language.
4164 * @since 1.22
4165 * @param string $code Language code
4166 * @return array array( fallbacks, site fallbacks )
4168 public static function getFallbacksIncludingSiteLanguage( $code ) {
4169 global $wgLanguageCode;
4171 // Usually, we will only store a tiny number of fallback chains, so we
4172 // keep them in static memory.
4173 $cacheKey = "{$code}-{$wgLanguageCode}";
4175 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4176 $fallbacks = self::getFallbacksFor( $code );
4178 // Append the site's fallback chain, including the site language itself
4179 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4180 array_unshift( $siteFallbacks, $wgLanguageCode );
4182 // Eliminate any languages already included in the chain
4183 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4185 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4187 return self::$fallbackLanguageCache[$cacheKey];
4191 * Get all messages for a given language
4192 * WARNING: this may take a long time. If you just need all message *keys*
4193 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4195 * @param string $code
4197 * @return array
4199 public static function getMessagesFor( $code ) {
4200 return self::getLocalisationCache()->getItem( $code, 'messages' );
4204 * Get a message for a given language
4206 * @param string $key
4207 * @param string $code
4209 * @return string
4211 public static function getMessageFor( $key, $code ) {
4212 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4216 * Get all message keys for a given language. This is a faster alternative to
4217 * array_keys( Language::getMessagesFor( $code ) )
4219 * @since 1.19
4220 * @param string $code Language code
4221 * @return array of message keys (strings)
4223 public static function getMessageKeysFor( $code ) {
4224 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4228 * @param string $talk
4229 * @return mixed
4231 function fixVariableInNamespace( $talk ) {
4232 if ( strpos( $talk, '$1' ) === false ) {
4233 return $talk;
4236 global $wgMetaNamespace;
4237 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4239 # Allow grammar transformations
4240 # Allowing full message-style parsing would make simple requests
4241 # such as action=raw much more expensive than they need to be.
4242 # This will hopefully cover most cases.
4243 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4244 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4245 return str_replace( ' ', '_', $talk );
4249 * @param string $m
4250 * @return string
4252 function replaceGrammarInNamespace( $m ) {
4253 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4257 * @throws MWException
4258 * @return array
4260 static function getCaseMaps() {
4261 static $wikiUpperChars, $wikiLowerChars;
4262 if ( isset( $wikiUpperChars ) ) {
4263 return array( $wikiUpperChars, $wikiLowerChars );
4266 wfProfileIn( __METHOD__ );
4267 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4268 if ( $arr === false ) {
4269 throw new MWException(
4270 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4272 $wikiUpperChars = $arr['wikiUpperChars'];
4273 $wikiLowerChars = $arr['wikiLowerChars'];
4274 wfProfileOut( __METHOD__ );
4275 return array( $wikiUpperChars, $wikiLowerChars );
4279 * Decode an expiry (block, protection, etc) which has come from the DB
4281 * @todo FIXME: why are we returnings DBMS-dependent strings???
4283 * @param string $expiry Database expiry String
4284 * @param bool|int $format True to process using language functions, or TS_ constant
4285 * to return the expiry in a given timestamp
4286 * @return string
4287 * @since 1.18
4289 public function formatExpiry( $expiry, $format = true ) {
4290 static $infinity;
4291 if ( $infinity === null ) {
4292 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4295 if ( $expiry == '' || $expiry == $infinity ) {
4296 return $format === true
4297 ? $this->getMessageFromDB( 'infiniteblock' )
4298 : $infinity;
4299 } else {
4300 return $format === true
4301 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4302 : wfTimestamp( $format, $expiry );
4307 * @todo Document
4308 * @param int|float $seconds
4309 * @param array $format Optional
4310 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4311 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4312 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4313 * and friends.
4314 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4315 * or 'avoidminutes'.
4316 * @return string
4318 function formatTimePeriod( $seconds, $format = array() ) {
4319 if ( !is_array( $format ) ) {
4320 $format = array( 'avoid' => $format ); // For backwards compatibility
4322 if ( !isset( $format['avoid'] ) ) {
4323 $format['avoid'] = false;
4325 if ( !isset( $format['noabbrevs' ] ) ) {
4326 $format['noabbrevs'] = false;
4328 $secondsMsg = wfMessage(
4329 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4330 $minutesMsg = wfMessage(
4331 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4332 $hoursMsg = wfMessage(
4333 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4334 $daysMsg = wfMessage(
4335 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4337 if ( round( $seconds * 10 ) < 100 ) {
4338 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4339 $s = $secondsMsg->params( $s )->text();
4340 } elseif ( round( $seconds ) < 60 ) {
4341 $s = $this->formatNum( round( $seconds ) );
4342 $s = $secondsMsg->params( $s )->text();
4343 } elseif ( round( $seconds ) < 3600 ) {
4344 $minutes = floor( $seconds / 60 );
4345 $secondsPart = round( fmod( $seconds, 60 ) );
4346 if ( $secondsPart == 60 ) {
4347 $secondsPart = 0;
4348 $minutes++;
4350 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4351 $s .= ' ';
4352 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4353 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4354 $hours = floor( $seconds / 3600 );
4355 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4356 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4357 if ( $secondsPart == 60 ) {
4358 $secondsPart = 0;
4359 $minutes++;
4361 if ( $minutes == 60 ) {
4362 $minutes = 0;
4363 $hours++;
4365 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4366 $s .= ' ';
4367 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4368 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4369 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4371 } else {
4372 $days = floor( $seconds / 86400 );
4373 if ( $format['avoid'] === 'avoidminutes' ) {
4374 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4375 if ( $hours == 24 ) {
4376 $hours = 0;
4377 $days++;
4379 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4380 $s .= ' ';
4381 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4382 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4383 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4384 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4385 if ( $minutes == 60 ) {
4386 $minutes = 0;
4387 $hours++;
4389 if ( $hours == 24 ) {
4390 $hours = 0;
4391 $days++;
4393 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4394 $s .= ' ';
4395 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4396 $s .= ' ';
4397 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4398 } else {
4399 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4400 $s .= ' ';
4401 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4404 return $s;
4408 * Format a bitrate for output, using an appropriate
4409 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4410 * the magnitude in question.
4412 * This use base 1000. For base 1024 use formatSize(), for another base
4413 * see formatComputingNumbers().
4415 * @param int $bps
4416 * @return string
4418 function formatBitrate( $bps ) {
4419 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4423 * @param int $size Size of the unit
4424 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4425 * @param string $messageKey Message key to be uesd
4426 * @return string
4428 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4429 if ( $size <= 0 ) {
4430 return str_replace( '$1', $this->formatNum( $size ),
4431 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4434 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4435 $index = 0;
4437 $maxIndex = count( $sizes ) - 1;
4438 while ( $size >= $boundary && $index < $maxIndex ) {
4439 $index++;
4440 $size /= $boundary;
4443 // For small sizes no decimal places necessary
4444 $round = 0;
4445 if ( $index > 1 ) {
4446 // For MB and bigger two decimal places are smarter
4447 $round = 2;
4449 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4451 $size = round( $size, $round );
4452 $text = $this->getMessageFromDB( $msg );
4453 return str_replace( '$1', $this->formatNum( $size ), $text );
4457 * Format a size in bytes for output, using an appropriate
4458 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4460 * This method use base 1024. For base 1000 use formatBitrate(), for
4461 * another base see formatComputingNumbers()
4463 * @param int $size Size to format
4464 * @return string Plain text (not HTML)
4466 function formatSize( $size ) {
4467 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4471 * Make a list item, used by various special pages
4473 * @param string $page Page link
4474 * @param string $details Text between brackets
4475 * @param bool $oppositedm Add the direction mark opposite to your
4476 * language, to display text properly
4477 * @return string
4479 function specialList( $page, $details, $oppositedm = true ) {
4480 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4481 $this->getDirMark();
4482 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4483 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4484 return $page . $details;
4488 * Generate (prev x| next x) (20|50|100...) type links for paging
4490 * @param Title $title Title object to link
4491 * @param int $offset
4492 * @param int $limit
4493 * @param array|string $query Optional URL query parameter string
4494 * @param bool $atend Optional param for specified if this is the last page
4495 * @return string
4497 public function viewPrevNext( Title $title, $offset, $limit,
4498 array $query = array(), $atend = false
4500 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4502 # Make 'previous' link
4503 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4504 if ( $offset > 0 ) {
4505 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4506 $query, $prev, 'prevn-title', 'mw-prevlink' );
4507 } else {
4508 $plink = htmlspecialchars( $prev );
4511 # Make 'next' link
4512 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4513 if ( $atend ) {
4514 $nlink = htmlspecialchars( $next );
4515 } else {
4516 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4517 $query, $next, 'nextn-title', 'mw-nextlink' );
4520 # Make links to set number of items per page
4521 $numLinks = array();
4522 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4523 $numLinks[] = $this->numLink( $title, $offset, $num,
4524 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4527 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4528 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4532 * Helper function for viewPrevNext() that generates links
4534 * @param Title $title Title object to link
4535 * @param int $offset
4536 * @param int $limit
4537 * @param array $query Extra query parameters
4538 * @param string $link Text to use for the link; will be escaped
4539 * @param string $tooltipMsg Name of the message to use as tooltip
4540 * @param string $class Value of the "class" attribute of the link
4541 * @return string HTML fragment
4543 private function numLink( Title $title, $offset, $limit, array $query, $link,
4544 $tooltipMsg, $class
4546 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4547 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4548 ->numParams( $limit )->text();
4550 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4551 'title' => $tooltip, 'class' => $class ), $link );
4555 * Get the conversion rule title, if any.
4557 * @return string
4559 public function getConvRuleTitle() {
4560 return $this->mConverter->getConvRuleTitle();
4564 * Get the compiled plural rules for the language
4565 * @since 1.20
4566 * @return array Associative array with plural form, and plural rule as key-value pairs
4568 public function getCompiledPluralRules() {
4569 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4570 $fallbacks = Language::getFallbacksFor( $this->mCode );
4571 if ( !$pluralRules ) {
4572 foreach ( $fallbacks as $fallbackCode ) {
4573 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4574 if ( $pluralRules ) {
4575 break;
4579 return $pluralRules;
4583 * Get the plural rules for the language
4584 * @since 1.20
4585 * @return array Associative array with plural form number and plural rule as key-value pairs
4587 public function getPluralRules() {
4588 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4589 $fallbacks = Language::getFallbacksFor( $this->mCode );
4590 if ( !$pluralRules ) {
4591 foreach ( $fallbacks as $fallbackCode ) {
4592 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4593 if ( $pluralRules ) {
4594 break;
4598 return $pluralRules;
4602 * Get the plural rule types for the language
4603 * @since 1.22
4604 * @return array Associative array with plural form number and plural rule type as key-value pairs
4606 public function getPluralRuleTypes() {
4607 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4608 $fallbacks = Language::getFallbacksFor( $this->mCode );
4609 if ( !$pluralRuleTypes ) {
4610 foreach ( $fallbacks as $fallbackCode ) {
4611 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4612 if ( $pluralRuleTypes ) {
4613 break;
4617 return $pluralRuleTypes;
4621 * Find the index number of the plural rule appropriate for the given number
4622 * @return int The index number of the plural rule
4624 public function getPluralRuleIndexNumber( $number ) {
4625 $pluralRules = $this->getCompiledPluralRules();
4626 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4627 return $form;
4631 * Find the plural rule type appropriate for the given number
4632 * For example, if the language is set to Arabic, getPluralType(5) should
4633 * return 'few'.
4634 * @since 1.22
4635 * @return string The name of the plural rule type, e.g. one, two, few, many
4637 public function getPluralRuleType( $number ) {
4638 $index = $this->getPluralRuleIndexNumber( $number );
4639 $pluralRuleTypes = $this->getPluralRuleTypes();
4640 if ( isset( $pluralRuleTypes[$index] ) ) {
4641 return $pluralRuleTypes[$index];
4642 } else {
4643 return 'other';