Add 2 new options to importImages.php
[mediawiki.git] / languages / Language.php
blob40d1f36cd9a42901482cebda703b4e8d2978a824
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 # Read language names
34 global $wgLanguageNames;
35 require_once( __DIR__ . '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
41 /**
42 * a fake language converter
44 * @ingroup Language
46 class FakeConverter {
48 /**
49 * @var Language
51 var $mLang;
52 function __construct( $langobj ) { $this->mLang = $langobj; }
53 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
54 function convert( $t ) { return $t; }
55 function convertTo( $text, $variant ) { return $text; }
56 function convertTitle( $t ) { return $t->getPrefixedText(); }
57 function getVariants() { return array( $this->mLang->getCode() ); }
58 function getPreferredVariant() { return $this->mLang->getCode(); }
59 function getDefaultVariant() { return $this->mLang->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
71 /**
72 * Internationalisation code
73 * @ingroup Language
75 class Language {
77 /**
78 * @var LanguageConverter
80 var $mConverter;
82 var $mVariants, $mCode, $mLoaded = false;
83 var $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 var $dateFormatStrings = array();
87 var $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
91 /**
92 * ReplacementArray object caches
94 var $transformData = array();
96 /**
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
105 'friday', 'saturday'
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
115 'december'
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
120 'december-gen'
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
158 * @since 1.20
159 * @var array
161 static public $durationIntervals = array(
162 'millennia' => 31557600000,
163 'centuries' => 3155760000,
164 'decades' => 315576000,
165 'years' => 31557600, // 86400 * 365.25
166 'weeks' => 604800,
167 'days' => 86400,
168 'hours' => 3600,
169 'minutes' => 60,
170 'seconds' => 1,
174 * Get a cached language object for a given language code
175 * @param $code String
176 * @return Language
178 static function factory( $code ) {
179 if ( !isset( self::$mLangObjCache[$code] ) ) {
180 if ( count( self::$mLangObjCache ) > 10 ) {
181 // Don't keep a billion objects around, that's stupid.
182 self::$mLangObjCache = array();
184 self::$mLangObjCache[$code] = self::newFromCode( $code );
186 return self::$mLangObjCache[$code];
190 * Create a language object for a given language code
191 * @param $code String
192 * @throws MWException
193 * @return Language
195 protected static function newFromCode( $code ) {
196 // Protect against path traversal below
197 if ( !Language::isValidCode( $code )
198 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
200 throw new MWException( "Invalid language code \"$code\"" );
203 if ( !Language::isValidBuiltInCode( $code ) ) {
204 // It's not possible to customise this code with class files, so
205 // just return a Language object. This is to support uselang= hacks.
206 $lang = new Language;
207 $lang->setCode( $code );
208 return $lang;
211 // Check if there is a language class for the code
212 $class = self::classFromCode( $code );
213 self::preloadLanguageClass( $class );
214 if ( MWInit::classExists( $class ) ) {
215 $lang = new $class;
216 return $lang;
219 // Keep trying the fallback list until we find an existing class
220 $fallbacks = Language::getFallbacksFor( $code );
221 foreach ( $fallbacks as $fallbackCode ) {
222 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
223 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
226 $class = self::classFromCode( $fallbackCode );
227 self::preloadLanguageClass( $class );
228 if ( MWInit::classExists( $class ) ) {
229 $lang = Language::newFromCode( $fallbackCode );
230 $lang->setCode( $code );
231 return $lang;
235 throw new MWException( "Invalid fallback sequence for language '$code'" );
239 * Returns true if a language code string is of a valid form, whether or
240 * not it exists. This includes codes which are used solely for
241 * customisation via the MediaWiki namespace.
243 * @param $code string
245 * @return bool
247 public static function isValidCode( $code ) {
248 return
249 // People think language codes are html safe, so enforce it.
250 // Ideally we should only allow a-zA-Z0-9-
251 // but, .+ and other chars are often used for {{int:}} hacks
252 // see bugs 37564, 37587, 36938
253 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
254 && !preg_match( Title::getTitleInvalidRegex(), $code );
258 * Returns true if a language code is of a valid form for the purposes of
259 * internal customisation of MediaWiki, via Messages*.php.
261 * @param $code string
263 * @throws MWException
264 * @since 1.18
265 * @return bool
267 public static function isValidBuiltInCode( $code ) {
269 if ( !is_string( $code ) ) {
270 $type = gettype( $code );
271 if ( $type === 'object' ) {
272 $addmsg = " of class " . get_class( $code );
273 } else {
274 $addmsg = '';
276 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
279 return preg_match( '/^[a-z0-9-]+$/i', $code );
283 * @param $code
284 * @return String Name of the language class
286 public static function classFromCode( $code ) {
287 if ( $code == 'en' ) {
288 return 'Language';
289 } else {
290 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
295 * Includes language class files
297 * @param $class string Name of the language class
299 public static function preloadLanguageClass( $class ) {
300 global $IP;
302 if ( $class === 'Language' ) {
303 return;
306 if ( !defined( 'MW_COMPILED' ) ) {
307 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
308 include_once( "$IP/languages/classes/$class.php" );
314 * Get the LocalisationCache instance
316 * @return LocalisationCache
318 public static function getLocalisationCache() {
319 if ( is_null( self::$dataCache ) ) {
320 global $wgLocalisationCacheConf;
321 $class = $wgLocalisationCacheConf['class'];
322 self::$dataCache = new $class( $wgLocalisationCacheConf );
324 return self::$dataCache;
327 function __construct() {
328 $this->mConverter = new FakeConverter( $this );
329 // Set the code to the name of the descendant
330 if ( get_class( $this ) == 'Language' ) {
331 $this->mCode = 'en';
332 } else {
333 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
335 self::getLocalisationCache();
339 * Reduce memory usage
341 function __destruct() {
342 foreach ( $this as $name => $value ) {
343 unset( $this->$name );
348 * Hook which will be called if this is the content language.
349 * Descendants can use this to register hook functions or modify globals
351 function initContLang() { }
354 * Same as getFallbacksFor for current language.
355 * @return array|bool
356 * @deprecated in 1.19
358 function getFallbackLanguageCode() {
359 wfDeprecated( __METHOD__ );
360 return self::getFallbackFor( $this->mCode );
364 * @return array
365 * @since 1.19
367 function getFallbackLanguages() {
368 return self::getFallbacksFor( $this->mCode );
372 * Exports $wgBookstoreListEn
373 * @return array
375 function getBookstoreList() {
376 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
380 * @return array
382 public function getNamespaces() {
383 if ( is_null( $this->namespaceNames ) ) {
384 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
386 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
387 $validNamespaces = MWNamespace::getCanonicalNamespaces();
389 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
391 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
392 if ( $wgMetaNamespaceTalk ) {
393 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
394 } else {
395 $talk = $this->namespaceNames[NS_PROJECT_TALK];
396 $this->namespaceNames[NS_PROJECT_TALK] =
397 $this->fixVariableInNamespace( $talk );
400 # Sometimes a language will be localised but not actually exist on this wiki.
401 foreach ( $this->namespaceNames as $key => $text ) {
402 if ( !isset( $validNamespaces[$key] ) ) {
403 unset( $this->namespaceNames[$key] );
407 # The above mixing may leave namespaces out of canonical order.
408 # Re-order by namespace ID number...
409 ksort( $this->namespaceNames );
411 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
413 return $this->namespaceNames;
417 * Arbitrarily set all of the namespace names at once. Mainly used for testing
418 * @param $namespaces Array of namespaces (id => name)
420 public function setNamespaces( array $namespaces ) {
421 $this->namespaceNames = $namespaces;
425 * A convenience function that returns the same thing as
426 * getNamespaces() except with the array values changed to ' '
427 * where it found '_', useful for producing output to be displayed
428 * e.g. in <select> forms.
430 * @return array
432 function getFormattedNamespaces() {
433 $ns = $this->getNamespaces();
434 foreach ( $ns as $k => $v ) {
435 $ns[$k] = strtr( $v, '_', ' ' );
437 return $ns;
441 * Get a namespace value by key
442 * <code>
443 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
444 * echo $mw_ns; // prints 'MediaWiki'
445 * </code>
447 * @param $index Int: the array key of the namespace to return
448 * @return mixed, string if the namespace value exists, otherwise false
450 function getNsText( $index ) {
451 $ns = $this->getNamespaces();
452 return isset( $ns[$index] ) ? $ns[$index] : false;
456 * A convenience function that returns the same thing as
457 * getNsText() except with '_' changed to ' ', useful for
458 * producing output.
460 * @param $index string
462 * @return array
464 function getFormattedNsText( $index ) {
465 $ns = $this->getNsText( $index );
466 return strtr( $ns, '_', ' ' );
470 * Returns gender-dependent namespace alias if available.
471 * @param $index Int: namespace index
472 * @param $gender String: gender key (male, female... )
473 * @return String
474 * @since 1.18
476 function getGenderNsText( $index, $gender ) {
477 global $wgExtraGenderNamespaces;
479 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
480 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
484 * Whether this language makes distinguishes genders for example in
485 * namespaces.
486 * @return bool
487 * @since 1.18
489 function needsGenderDistinction() {
490 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
491 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
492 // $wgExtraGenderNamespaces overrides everything
493 return true;
494 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
495 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
496 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
497 return false;
498 } else {
499 // Check what is in i18n files
500 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
501 return count( $aliases ) > 0;
506 * Get a namespace key by value, case insensitive.
507 * Only matches namespace names for the current language, not the
508 * canonical ones defined in Namespace.php.
510 * @param $text String
511 * @return mixed An integer if $text is a valid value otherwise false
513 function getLocalNsIndex( $text ) {
514 $lctext = $this->lc( $text );
515 $ids = $this->getNamespaceIds();
516 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
520 * @return array
522 function getNamespaceAliases() {
523 if ( is_null( $this->namespaceAliases ) ) {
524 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
525 if ( !$aliases ) {
526 $aliases = array();
527 } else {
528 foreach ( $aliases as $name => $index ) {
529 if ( $index === NS_PROJECT_TALK ) {
530 unset( $aliases[$name] );
531 $name = $this->fixVariableInNamespace( $name );
532 $aliases[$name] = $index;
537 global $wgExtraGenderNamespaces;
538 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
539 foreach ( $genders as $index => $forms ) {
540 foreach ( $forms as $alias ) {
541 $aliases[$alias] = $index;
545 $this->namespaceAliases = $aliases;
547 return $this->namespaceAliases;
551 * @return array
553 function getNamespaceIds() {
554 if ( is_null( $this->mNamespaceIds ) ) {
555 global $wgNamespaceAliases;
556 # Put namespace names and aliases into a hashtable.
557 # If this is too slow, then we should arrange it so that it is done
558 # before caching. The catch is that at pre-cache time, the above
559 # class-specific fixup hasn't been done.
560 $this->mNamespaceIds = array();
561 foreach ( $this->getNamespaces() as $index => $name ) {
562 $this->mNamespaceIds[$this->lc( $name )] = $index;
564 foreach ( $this->getNamespaceAliases() as $name => $index ) {
565 $this->mNamespaceIds[$this->lc( $name )] = $index;
567 if ( $wgNamespaceAliases ) {
568 foreach ( $wgNamespaceAliases as $name => $index ) {
569 $this->mNamespaceIds[$this->lc( $name )] = $index;
573 return $this->mNamespaceIds;
577 * Get a namespace key by value, case insensitive. Canonical namespace
578 * names override custom ones defined for the current language.
580 * @param $text String
581 * @return mixed An integer if $text is a valid value otherwise false
583 function getNsIndex( $text ) {
584 $lctext = $this->lc( $text );
585 $ns = MWNamespace::getCanonicalIndex( $lctext );
586 if ( $ns !== null ) {
587 return $ns;
589 $ids = $this->getNamespaceIds();
590 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
594 * short names for language variants used for language conversion links.
596 * @param $code String
597 * @param $usemsg bool Use the "variantname-xyz" message if it exists
598 * @return string
600 function getVariantname( $code, $usemsg = true ) {
601 $msg = "variantname-$code";
602 if ( $usemsg && wfMessage( $msg )->exists() ) {
603 return $this->getMessageFromDB( $msg );
605 $name = self::fetchLanguageName( $code );
606 if ( $name ) {
607 return $name; # if it's defined as a language name, show that
608 } else {
609 # otherwise, output the language code
610 return $code;
615 * @param $name string
616 * @return string
618 function specialPage( $name ) {
619 $aliases = $this->getSpecialPageAliases();
620 if ( isset( $aliases[$name][0] ) ) {
621 $name = $aliases[$name][0];
623 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
627 * @return array
629 function getQuickbarSettings() {
630 return array(
631 $this->getMessage( 'qbsettings-none' ),
632 $this->getMessage( 'qbsettings-fixedleft' ),
633 $this->getMessage( 'qbsettings-fixedright' ),
634 $this->getMessage( 'qbsettings-floatingleft' ),
635 $this->getMessage( 'qbsettings-floatingright' ),
636 $this->getMessage( 'qbsettings-directionality' )
641 * @return array
643 function getDatePreferences() {
644 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
648 * @return array
650 function getDateFormats() {
651 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
655 * @return array|string
657 function getDefaultDateFormat() {
658 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
659 if ( $df === 'dmy or mdy' ) {
660 global $wgAmericanDates;
661 return $wgAmericanDates ? 'mdy' : 'dmy';
662 } else {
663 return $df;
668 * @return array
670 function getDatePreferenceMigrationMap() {
671 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
675 * @param $image
676 * @return array|null
678 function getImageFile( $image ) {
679 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
683 * @return array
685 function getExtraUserToggles() {
686 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
690 * @param $tog
691 * @return string
693 function getUserToggle( $tog ) {
694 return $this->getMessageFromDB( "tog-$tog" );
698 * Get native language names, indexed by code.
699 * Only those defined in MediaWiki, no other data like CLDR.
700 * If $customisedOnly is true, only returns codes with a messages file
702 * @param $customisedOnly bool
704 * @return array
705 * @deprecated in 1.20, use fetchLanguageNames()
707 public static function getLanguageNames( $customisedOnly = false ) {
708 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
712 * Get translated language names. This is done on best effort and
713 * by default this is exactly the same as Language::getLanguageNames.
714 * The CLDR extension provides translated names.
715 * @param $code String Language code.
716 * @return Array language code => language name
717 * @since 1.18.0
718 * @deprecated in 1.20, use fetchLanguageNames()
720 public static function getTranslatedLanguageNames( $code ) {
721 return self::fetchLanguageNames( $code, 'all' );
725 * Get an array of language names, indexed by code.
726 * @param $inLanguage null|string: Code of language in which to return the names
727 * Use null for autonyms (native names)
728 * @param $include string:
729 * 'all' all available languages
730 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
731 * 'mwfile' only if the language is in 'mw' *and* has a message file
732 * @return array: language code => language name
733 * @since 1.20
735 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
736 global $wgExtraLanguageNames;
737 static $coreLanguageNames;
739 if ( $coreLanguageNames === null ) {
740 include( MWInit::compiledPath( 'languages/Names.php' ) );
743 $names = array();
745 if ( $inLanguage ) {
746 # TODO: also include when $inLanguage is null, when this code is more efficient
747 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
750 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
751 foreach ( $mwNames as $mwCode => $mwName ) {
752 # - Prefer own MediaWiki native name when not using the hook
753 # - For other names just add if not added through the hook
754 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
755 $names[$mwCode] = $mwName;
759 if ( $include === 'all' ) {
760 return $names;
763 $returnMw = array();
764 $coreCodes = array_keys( $mwNames );
765 foreach ( $coreCodes as $coreCode ) {
766 $returnMw[$coreCode] = $names[$coreCode];
769 if ( $include === 'mwfile' ) {
770 $namesMwFile = array();
771 # We do this using a foreach over the codes instead of a directory
772 # loop so that messages files in extensions will work correctly.
773 foreach ( $returnMw as $code => $value ) {
774 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
775 $namesMwFile[$code] = $names[$code];
778 return $namesMwFile;
780 # 'mw' option; default if it's not one of the other two options (all/mwfile)
781 return $returnMw;
785 * @param $code string: The code of the language for which to get the name
786 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
787 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
788 * @return string: Language name or empty
789 * @since 1.20
791 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
792 $array = self::fetchLanguageNames( $inLanguage, $include );
793 return !array_key_exists( $code, $array ) ? '' : $array[$code];
797 * Get a message from the MediaWiki namespace.
799 * @param $msg String: message name
800 * @return string
802 function getMessageFromDB( $msg ) {
803 return wfMessage( $msg )->inLanguage( $this )->text();
807 * Get the native language name of $code.
808 * Only if defined in MediaWiki, no other data like CLDR.
809 * @param $code string
810 * @return string
811 * @deprecated in 1.20, use fetchLanguageName()
813 function getLanguageName( $code ) {
814 return self::fetchLanguageName( $code );
818 * @param $key string
819 * @return string
821 function getMonthName( $key ) {
822 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
826 * @return array
828 function getMonthNamesArray() {
829 $monthNames = array( '' );
830 for ( $i = 1; $i < 13; $i++ ) {
831 $monthNames[] = $this->getMonthName( $i );
833 return $monthNames;
837 * @param $key string
838 * @return string
840 function getMonthNameGen( $key ) {
841 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
845 * @param $key string
846 * @return string
848 function getMonthAbbreviation( $key ) {
849 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
853 * @return array
855 function getMonthAbbreviationsArray() {
856 $monthNames = array( '' );
857 for ( $i = 1; $i < 13; $i++ ) {
858 $monthNames[] = $this->getMonthAbbreviation( $i );
860 return $monthNames;
864 * @param $key string
865 * @return string
867 function getWeekdayName( $key ) {
868 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
872 * @param $key string
873 * @return string
875 function getWeekdayAbbreviation( $key ) {
876 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
880 * @param $key string
881 * @return string
883 function getIranianCalendarMonthName( $key ) {
884 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
888 * @param $key string
889 * @return string
891 function getHebrewCalendarMonthName( $key ) {
892 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
896 * @param $key string
897 * @return string
899 function getHebrewCalendarMonthNameGen( $key ) {
900 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
904 * @param $key string
905 * @return string
907 function getHijriCalendarMonthName( $key ) {
908 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
912 * This is a workalike of PHP's date() function, but with better
913 * internationalisation, a reduced set of format characters, and a better
914 * escaping format.
916 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
917 * PHP manual for definitions. There are a number of extensions, which
918 * start with "x":
920 * xn Do not translate digits of the next numeric format character
921 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
922 * xr Use roman numerals for the next numeric format character
923 * xh Use hebrew numerals for the next numeric format character
924 * xx Literal x
925 * xg Genitive month name
927 * xij j (day number) in Iranian calendar
928 * xiF F (month name) in Iranian calendar
929 * xin n (month number) in Iranian calendar
930 * xiy y (two digit year) in Iranian calendar
931 * xiY Y (full year) in Iranian calendar
933 * xjj j (day number) in Hebrew calendar
934 * xjF F (month name) in Hebrew calendar
935 * xjt t (days in month) in Hebrew calendar
936 * xjx xg (genitive month name) in Hebrew calendar
937 * xjn n (month number) in Hebrew calendar
938 * xjY Y (full year) in Hebrew calendar
940 * xmj j (day number) in Hijri calendar
941 * xmF F (month name) in Hijri calendar
942 * xmn n (month number) in Hijri calendar
943 * xmY Y (full year) in Hijri calendar
945 * xkY Y (full year) in Thai solar calendar. Months and days are
946 * identical to the Gregorian calendar
947 * xoY Y (full year) in Minguo calendar or Juche year.
948 * Months and days are identical to the
949 * Gregorian calendar
950 * xtY Y (full year) in Japanese nengo. Months and days are
951 * identical to the Gregorian calendar
953 * Characters enclosed in double quotes will be considered literal (with
954 * the quotes themselves removed). Unmatched quotes will be considered
955 * literal quotes. Example:
957 * "The month is" F => The month is January
958 * i's" => 20'11"
960 * Backslash escaping is also supported.
962 * Input timestamp is assumed to be pre-normalized to the desired local
963 * time zone, if any.
965 * @param $format String
966 * @param $ts String: 14-character timestamp
967 * YYYYMMDDHHMMSS
968 * 01234567890123
969 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
971 * @return string
973 function sprintfDate( $format, $ts ) {
974 $s = '';
975 $raw = false;
976 $roman = false;
977 $hebrewNum = false;
978 $unix = false;
979 $rawToggle = false;
980 $iranian = false;
981 $hebrew = false;
982 $hijri = false;
983 $thai = false;
984 $minguo = false;
985 $tenno = false;
986 for ( $p = 0; $p < strlen( $format ); $p++ ) {
987 $num = false;
988 $code = $format[$p];
989 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
990 $code .= $format[++$p];
993 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
994 $code .= $format[++$p];
997 switch ( $code ) {
998 case 'xx':
999 $s .= 'x';
1000 break;
1001 case 'xn':
1002 $raw = true;
1003 break;
1004 case 'xN':
1005 $rawToggle = !$rawToggle;
1006 break;
1007 case 'xr':
1008 $roman = true;
1009 break;
1010 case 'xh':
1011 $hebrewNum = true;
1012 break;
1013 case 'xg':
1014 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1015 break;
1016 case 'xjx':
1017 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
1018 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1019 break;
1020 case 'd':
1021 $num = substr( $ts, 6, 2 );
1022 break;
1023 case 'D':
1024 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
1025 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
1026 break;
1027 case 'j':
1028 $num = intval( substr( $ts, 6, 2 ) );
1029 break;
1030 case 'xij':
1031 if ( !$iranian ) {
1032 $iranian = self::tsToIranian( $ts );
1034 $num = $iranian[2];
1035 break;
1036 case 'xmj':
1037 if ( !$hijri ) {
1038 $hijri = self::tsToHijri( $ts );
1040 $num = $hijri[2];
1041 break;
1042 case 'xjj':
1043 if ( !$hebrew ) {
1044 $hebrew = self::tsToHebrew( $ts );
1046 $num = $hebrew[2];
1047 break;
1048 case 'l':
1049 if ( !$unix ) {
1050 $unix = wfTimestamp( TS_UNIX, $ts );
1052 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
1053 break;
1054 case 'N':
1055 if ( !$unix ) {
1056 $unix = wfTimestamp( TS_UNIX, $ts );
1058 $w = gmdate( 'w', $unix );
1059 $num = $w ? $w : 7;
1060 break;
1061 case 'w':
1062 if ( !$unix ) {
1063 $unix = wfTimestamp( TS_UNIX, $ts );
1065 $num = gmdate( 'w', $unix );
1066 break;
1067 case 'z':
1068 if ( !$unix ) {
1069 $unix = wfTimestamp( TS_UNIX, $ts );
1071 $num = gmdate( 'z', $unix );
1072 break;
1073 case 'W':
1074 if ( !$unix ) {
1075 $unix = wfTimestamp( TS_UNIX, $ts );
1077 $num = gmdate( 'W', $unix );
1078 break;
1079 case 'F':
1080 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1081 break;
1082 case 'xiF':
1083 if ( !$iranian ) {
1084 $iranian = self::tsToIranian( $ts );
1086 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1087 break;
1088 case 'xmF':
1089 if ( !$hijri ) {
1090 $hijri = self::tsToHijri( $ts );
1092 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1093 break;
1094 case 'xjF':
1095 if ( !$hebrew ) {
1096 $hebrew = self::tsToHebrew( $ts );
1098 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1099 break;
1100 case 'm':
1101 $num = substr( $ts, 4, 2 );
1102 break;
1103 case 'M':
1104 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1105 break;
1106 case 'n':
1107 $num = intval( substr( $ts, 4, 2 ) );
1108 break;
1109 case 'xin':
1110 if ( !$iranian ) {
1111 $iranian = self::tsToIranian( $ts );
1113 $num = $iranian[1];
1114 break;
1115 case 'xmn':
1116 if ( !$hijri ) {
1117 $hijri = self::tsToHijri ( $ts );
1119 $num = $hijri[1];
1120 break;
1121 case 'xjn':
1122 if ( !$hebrew ) {
1123 $hebrew = self::tsToHebrew( $ts );
1125 $num = $hebrew[1];
1126 break;
1127 case 't':
1128 if ( !$unix ) {
1129 $unix = wfTimestamp( TS_UNIX, $ts );
1131 $num = gmdate( 't', $unix );
1132 break;
1133 case 'xjt':
1134 if ( !$hebrew ) {
1135 $hebrew = self::tsToHebrew( $ts );
1137 $num = $hebrew[3];
1138 break;
1139 case 'L':
1140 if ( !$unix ) {
1141 $unix = wfTimestamp( TS_UNIX, $ts );
1143 $num = gmdate( 'L', $unix );
1144 break;
1145 case 'o':
1146 if ( !$unix ) {
1147 $unix = wfTimestamp( TS_UNIX, $ts );
1149 $num = gmdate( 'o', $unix );
1150 break;
1151 case 'Y':
1152 $num = substr( $ts, 0, 4 );
1153 break;
1154 case 'xiY':
1155 if ( !$iranian ) {
1156 $iranian = self::tsToIranian( $ts );
1158 $num = $iranian[0];
1159 break;
1160 case 'xmY':
1161 if ( !$hijri ) {
1162 $hijri = self::tsToHijri( $ts );
1164 $num = $hijri[0];
1165 break;
1166 case 'xjY':
1167 if ( !$hebrew ) {
1168 $hebrew = self::tsToHebrew( $ts );
1170 $num = $hebrew[0];
1171 break;
1172 case 'xkY':
1173 if ( !$thai ) {
1174 $thai = self::tsToYear( $ts, 'thai' );
1176 $num = $thai[0];
1177 break;
1178 case 'xoY':
1179 if ( !$minguo ) {
1180 $minguo = self::tsToYear( $ts, 'minguo' );
1182 $num = $minguo[0];
1183 break;
1184 case 'xtY':
1185 if ( !$tenno ) {
1186 $tenno = self::tsToYear( $ts, 'tenno' );
1188 $num = $tenno[0];
1189 break;
1190 case 'y':
1191 $num = substr( $ts, 2, 2 );
1192 break;
1193 case 'xiy':
1194 if ( !$iranian ) {
1195 $iranian = self::tsToIranian( $ts );
1197 $num = substr( $iranian[0], -2 );
1198 break;
1199 case 'a':
1200 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1201 break;
1202 case 'A':
1203 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1204 break;
1205 case 'g':
1206 $h = substr( $ts, 8, 2 );
1207 $num = $h % 12 ? $h % 12 : 12;
1208 break;
1209 case 'G':
1210 $num = intval( substr( $ts, 8, 2 ) );
1211 break;
1212 case 'h':
1213 $h = substr( $ts, 8, 2 );
1214 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1215 break;
1216 case 'H':
1217 $num = substr( $ts, 8, 2 );
1218 break;
1219 case 'i':
1220 $num = substr( $ts, 10, 2 );
1221 break;
1222 case 's':
1223 $num = substr( $ts, 12, 2 );
1224 break;
1225 case 'c':
1226 if ( !$unix ) {
1227 $unix = wfTimestamp( TS_UNIX, $ts );
1229 $s .= gmdate( 'c', $unix );
1230 break;
1231 case 'r':
1232 if ( !$unix ) {
1233 $unix = wfTimestamp( TS_UNIX, $ts );
1235 $s .= gmdate( 'r', $unix );
1236 break;
1237 case 'U':
1238 if ( !$unix ) {
1239 $unix = wfTimestamp( TS_UNIX, $ts );
1241 $num = $unix;
1242 break;
1243 case '\\':
1244 # Backslash escaping
1245 if ( $p < strlen( $format ) - 1 ) {
1246 $s .= $format[++$p];
1247 } else {
1248 $s .= '\\';
1250 break;
1251 case '"':
1252 # Quoted literal
1253 if ( $p < strlen( $format ) - 1 ) {
1254 $endQuote = strpos( $format, '"', $p + 1 );
1255 if ( $endQuote === false ) {
1256 # No terminating quote, assume literal "
1257 $s .= '"';
1258 } else {
1259 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1260 $p = $endQuote;
1262 } else {
1263 # Quote at end of string, assume literal "
1264 $s .= '"';
1266 break;
1267 default:
1268 $s .= $format[$p];
1270 if ( $num !== false ) {
1271 if ( $rawToggle || $raw ) {
1272 $s .= $num;
1273 $raw = false;
1274 } elseif ( $roman ) {
1275 $s .= Language::romanNumeral( $num );
1276 $roman = false;
1277 } elseif ( $hebrewNum ) {
1278 $s .= self::hebrewNumeral( $num );
1279 $hebrewNum = false;
1280 } else {
1281 $s .= $this->formatNum( $num, true );
1285 return $s;
1288 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1289 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1292 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1293 * Gregorian dates to Iranian dates. Originally written in C, it
1294 * is released under the terms of GNU Lesser General Public
1295 * License. Conversion to PHP was performed by Niklas Laxström.
1297 * Link: http://www.farsiweb.info/jalali/jalali.c
1299 * @param $ts string
1301 * @return string
1303 private static function tsToIranian( $ts ) {
1304 $gy = substr( $ts, 0, 4 ) -1600;
1305 $gm = substr( $ts, 4, 2 ) -1;
1306 $gd = substr( $ts, 6, 2 ) -1;
1308 # Days passed from the beginning (including leap years)
1309 $gDayNo = 365 * $gy
1310 + floor( ( $gy + 3 ) / 4 )
1311 - floor( ( $gy + 99 ) / 100 )
1312 + floor( ( $gy + 399 ) / 400 );
1314 // Add days of the past months of this year
1315 for ( $i = 0; $i < $gm; $i++ ) {
1316 $gDayNo += self::$GREG_DAYS[$i];
1319 // Leap years
1320 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1321 $gDayNo++;
1324 // Days passed in current month
1325 $gDayNo += (int)$gd;
1327 $jDayNo = $gDayNo - 79;
1329 $jNp = floor( $jDayNo / 12053 );
1330 $jDayNo %= 12053;
1332 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1333 $jDayNo %= 1461;
1335 if ( $jDayNo >= 366 ) {
1336 $jy += floor( ( $jDayNo - 1 ) / 365 );
1337 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1340 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1341 $jDayNo -= self::$IRANIAN_DAYS[$i];
1344 $jm = $i + 1;
1345 $jd = $jDayNo + 1;
1347 return array( $jy, $jm, $jd );
1351 * Converting Gregorian dates to Hijri dates.
1353 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1355 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1357 * @param $ts string
1359 * @return string
1361 private static function tsToHijri( $ts ) {
1362 $year = substr( $ts, 0, 4 );
1363 $month = substr( $ts, 4, 2 );
1364 $day = substr( $ts, 6, 2 );
1366 $zyr = $year;
1367 $zd = $day;
1368 $zm = $month;
1369 $zy = $zyr;
1371 if (
1372 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1373 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1376 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1377 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1378 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1379 $zd - 32075;
1380 } else {
1381 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1382 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1385 $zl = $zjd -1948440 + 10632;
1386 $zn = (int)( ( $zl - 1 ) / 10631 );
1387 $zl = $zl - 10631 * $zn + 354;
1388 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1389 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1390 $zm = (int)( ( 24 * $zl ) / 709 );
1391 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1392 $zy = 30 * $zn + $zj - 30;
1394 return array( $zy, $zm, $zd );
1398 * Converting Gregorian dates to Hebrew dates.
1400 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1401 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1402 * to translate the relevant functions into PHP and release them under
1403 * GNU GPL.
1405 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1406 * and Adar II is 14. In a non-leap year, Adar is 6.
1408 * @param $ts string
1410 * @return string
1412 private static function tsToHebrew( $ts ) {
1413 # Parse date
1414 $year = substr( $ts, 0, 4 );
1415 $month = substr( $ts, 4, 2 );
1416 $day = substr( $ts, 6, 2 );
1418 # Calculate Hebrew year
1419 $hebrewYear = $year + 3760;
1421 # Month number when September = 1, August = 12
1422 $month += 4;
1423 if ( $month > 12 ) {
1424 # Next year
1425 $month -= 12;
1426 $year++;
1427 $hebrewYear++;
1430 # Calculate day of year from 1 September
1431 $dayOfYear = $day;
1432 for ( $i = 1; $i < $month; $i++ ) {
1433 if ( $i == 6 ) {
1434 # February
1435 $dayOfYear += 28;
1436 # Check if the year is leap
1437 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1438 $dayOfYear++;
1440 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1441 $dayOfYear += 30;
1442 } else {
1443 $dayOfYear += 31;
1447 # Calculate the start of the Hebrew year
1448 $start = self::hebrewYearStart( $hebrewYear );
1450 # Calculate next year's start
1451 if ( $dayOfYear <= $start ) {
1452 # Day is before the start of the year - it is the previous year
1453 # Next year's start
1454 $nextStart = $start;
1455 # Previous year
1456 $year--;
1457 $hebrewYear--;
1458 # Add days since previous year's 1 September
1459 $dayOfYear += 365;
1460 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1461 # Leap year
1462 $dayOfYear++;
1464 # Start of the new (previous) year
1465 $start = self::hebrewYearStart( $hebrewYear );
1466 } else {
1467 # Next year's start
1468 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1471 # Calculate Hebrew day of year
1472 $hebrewDayOfYear = $dayOfYear - $start;
1474 # Difference between year's days
1475 $diff = $nextStart - $start;
1476 # Add 12 (or 13 for leap years) days to ignore the difference between
1477 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1478 # difference is only about the year type
1479 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1480 $diff += 13;
1481 } else {
1482 $diff += 12;
1485 # Check the year pattern, and is leap year
1486 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1487 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1488 # and non-leap years
1489 $yearPattern = $diff % 30;
1490 # Check if leap year
1491 $isLeap = $diff >= 30;
1493 # Calculate day in the month from number of day in the Hebrew year
1494 # Don't check Adar - if the day is not in Adar, we will stop before;
1495 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1496 $hebrewDay = $hebrewDayOfYear;
1497 $hebrewMonth = 1;
1498 $days = 0;
1499 while ( $hebrewMonth <= 12 ) {
1500 # Calculate days in this month
1501 if ( $isLeap && $hebrewMonth == 6 ) {
1502 # Adar in a leap year
1503 if ( $isLeap ) {
1504 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1505 $days = 30;
1506 if ( $hebrewDay <= $days ) {
1507 # Day in Adar I
1508 $hebrewMonth = 13;
1509 } else {
1510 # Subtract the days of Adar I
1511 $hebrewDay -= $days;
1512 # Try Adar II
1513 $days = 29;
1514 if ( $hebrewDay <= $days ) {
1515 # Day in Adar II
1516 $hebrewMonth = 14;
1520 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1521 # Cheshvan in a complete year (otherwise as the rule below)
1522 $days = 30;
1523 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1524 # Kislev in an incomplete year (otherwise as the rule below)
1525 $days = 29;
1526 } else {
1527 # Odd months have 30 days, even have 29
1528 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1530 if ( $hebrewDay <= $days ) {
1531 # In the current month
1532 break;
1533 } else {
1534 # Subtract the days of the current month
1535 $hebrewDay -= $days;
1536 # Try in the next month
1537 $hebrewMonth++;
1541 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1545 * This calculates the Hebrew year start, as days since 1 September.
1546 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1547 * Used for Hebrew date.
1549 * @param $year int
1551 * @return string
1553 private static function hebrewYearStart( $year ) {
1554 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1555 $b = intval( ( $year - 1 ) % 4 );
1556 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1557 if ( $m < 0 ) {
1558 $m--;
1560 $Mar = intval( $m );
1561 if ( $m < 0 ) {
1562 $m++;
1564 $m -= $Mar;
1566 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1567 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1568 $Mar++;
1569 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1570 $Mar += 2;
1571 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1572 $Mar++;
1575 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1576 return $Mar;
1580 * Algorithm to convert Gregorian dates to Thai solar dates,
1581 * Minguo dates or Minguo dates.
1583 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1584 * http://en.wikipedia.org/wiki/Minguo_calendar
1585 * http://en.wikipedia.org/wiki/Japanese_era_name
1587 * @param $ts String: 14-character timestamp
1588 * @param $cName String: calender name
1589 * @return Array: converted year, month, day
1591 private static function tsToYear( $ts, $cName ) {
1592 $gy = substr( $ts, 0, 4 );
1593 $gm = substr( $ts, 4, 2 );
1594 $gd = substr( $ts, 6, 2 );
1596 if ( !strcmp( $cName, 'thai' ) ) {
1597 # Thai solar dates
1598 # Add 543 years to the Gregorian calendar
1599 # Months and days are identical
1600 $gy_offset = $gy + 543;
1601 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1602 # Minguo dates
1603 # Deduct 1911 years from the Gregorian calendar
1604 # Months and days are identical
1605 $gy_offset = $gy - 1911;
1606 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1607 # Nengō dates up to Meiji period
1608 # Deduct years from the Gregorian calendar
1609 # depending on the nengo periods
1610 # Months and days are identical
1611 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1612 # Meiji period
1613 $gy_gannen = $gy - 1868 + 1;
1614 $gy_offset = $gy_gannen;
1615 if ( $gy_gannen == 1 ) {
1616 $gy_offset = '元';
1618 $gy_offset = '明治' . $gy_offset;
1619 } elseif (
1620 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1621 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1622 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1623 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1624 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1627 # Taishō period
1628 $gy_gannen = $gy - 1912 + 1;
1629 $gy_offset = $gy_gannen;
1630 if ( $gy_gannen == 1 ) {
1631 $gy_offset = '元';
1633 $gy_offset = '大正' . $gy_offset;
1634 } elseif (
1635 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1636 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1637 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1640 # Shōwa period
1641 $gy_gannen = $gy - 1926 + 1;
1642 $gy_offset = $gy_gannen;
1643 if ( $gy_gannen == 1 ) {
1644 $gy_offset = '元';
1646 $gy_offset = '昭和' . $gy_offset;
1647 } else {
1648 # Heisei period
1649 $gy_gannen = $gy - 1989 + 1;
1650 $gy_offset = $gy_gannen;
1651 if ( $gy_gannen == 1 ) {
1652 $gy_offset = '元';
1654 $gy_offset = '平成' . $gy_offset;
1656 } else {
1657 $gy_offset = $gy;
1660 return array( $gy_offset, $gm, $gd );
1664 * Roman number formatting up to 10000
1666 * @param $num int
1668 * @return string
1670 static function romanNumeral( $num ) {
1671 static $table = array(
1672 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1673 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1674 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1675 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1678 $num = intval( $num );
1679 if ( $num > 10000 || $num <= 0 ) {
1680 return $num;
1683 $s = '';
1684 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1685 if ( $num >= $pow10 ) {
1686 $s .= $table[$i][(int)floor( $num / $pow10 )];
1688 $num = $num % $pow10;
1690 return $s;
1694 * Hebrew Gematria number formatting up to 9999
1696 * @param $num int
1698 * @return string
1700 static function hebrewNumeral( $num ) {
1701 static $table = array(
1702 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1703 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1704 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1705 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1708 $num = intval( $num );
1709 if ( $num > 9999 || $num <= 0 ) {
1710 return $num;
1713 $s = '';
1714 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1715 if ( $num >= $pow10 ) {
1716 if ( $num == 15 || $num == 16 ) {
1717 $s .= $table[0][9] . $table[0][$num - 9];
1718 $num = 0;
1719 } else {
1720 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1721 if ( $pow10 == 1000 ) {
1722 $s .= "'";
1726 $num = $num % $pow10;
1728 if ( strlen( $s ) == 2 ) {
1729 $str = $s . "'";
1730 } else {
1731 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1732 $str .= substr( $s, strlen( $s ) - 2, 2 );
1734 $start = substr( $str, 0, strlen( $str ) - 2 );
1735 $end = substr( $str, strlen( $str ) - 2 );
1736 switch( $end ) {
1737 case 'כ':
1738 $str = $start . 'ך';
1739 break;
1740 case 'מ':
1741 $str = $start . 'ם';
1742 break;
1743 case 'נ':
1744 $str = $start . 'ן';
1745 break;
1746 case 'פ':
1747 $str = $start . 'ף';
1748 break;
1749 case 'צ':
1750 $str = $start . 'ץ';
1751 break;
1753 return $str;
1757 * Used by date() and time() to adjust the time output.
1759 * @param $ts Int the time in date('YmdHis') format
1760 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1761 * get user timecorrection setting)
1762 * @return int
1764 function userAdjust( $ts, $tz = false ) {
1765 global $wgUser, $wgLocalTZoffset;
1767 if ( $tz === false ) {
1768 $tz = $wgUser->getOption( 'timecorrection' );
1771 $data = explode( '|', $tz, 3 );
1773 if ( $data[0] == 'ZoneInfo' ) {
1774 wfSuppressWarnings();
1775 $userTZ = timezone_open( $data[2] );
1776 wfRestoreWarnings();
1777 if ( $userTZ !== false ) {
1778 $date = date_create( $ts, timezone_open( 'UTC' ) );
1779 date_timezone_set( $date, $userTZ );
1780 $date = date_format( $date, 'YmdHis' );
1781 return $date;
1783 # Unrecognized timezone, default to 'Offset' with the stored offset.
1784 $data[0] = 'Offset';
1787 $minDiff = 0;
1788 if ( $data[0] == 'System' || $tz == '' ) {
1789 #  Global offset in minutes.
1790 if ( isset( $wgLocalTZoffset ) ) {
1791 $minDiff = $wgLocalTZoffset;
1793 } elseif ( $data[0] == 'Offset' ) {
1794 $minDiff = intval( $data[1] );
1795 } else {
1796 $data = explode( ':', $tz );
1797 if ( count( $data ) == 2 ) {
1798 $data[0] = intval( $data[0] );
1799 $data[1] = intval( $data[1] );
1800 $minDiff = abs( $data[0] ) * 60 + $data[1];
1801 if ( $data[0] < 0 ) {
1802 $minDiff = -$minDiff;
1804 } else {
1805 $minDiff = intval( $data[0] ) * 60;
1809 # No difference ? Return time unchanged
1810 if ( 0 == $minDiff ) {
1811 return $ts;
1814 wfSuppressWarnings(); // E_STRICT system time bitching
1815 # Generate an adjusted date; take advantage of the fact that mktime
1816 # will normalize out-of-range values so we don't have to split $minDiff
1817 # into hours and minutes.
1818 $t = mktime( (
1819 (int)substr( $ts, 8, 2 ) ), # Hours
1820 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1821 (int)substr( $ts, 12, 2 ), # Seconds
1822 (int)substr( $ts, 4, 2 ), # Month
1823 (int)substr( $ts, 6, 2 ), # Day
1824 (int)substr( $ts, 0, 4 ) ); # Year
1826 $date = date( 'YmdHis', $t );
1827 wfRestoreWarnings();
1829 return $date;
1833 * This is meant to be used by time(), date(), and timeanddate() to get
1834 * the date preference they're supposed to use, it should be used in
1835 * all children.
1837 *<code>
1838 * function timeanddate([...], $format = true) {
1839 * $datePreference = $this->dateFormat($format);
1840 * [...]
1842 *</code>
1844 * @param $usePrefs Mixed: if true, the user's preference is used
1845 * if false, the site/language default is used
1846 * if int/string, assumed to be a format.
1847 * @return string
1849 function dateFormat( $usePrefs = true ) {
1850 global $wgUser;
1852 if ( is_bool( $usePrefs ) ) {
1853 if ( $usePrefs ) {
1854 $datePreference = $wgUser->getDatePreference();
1855 } else {
1856 $datePreference = (string)User::getDefaultOption( 'date' );
1858 } else {
1859 $datePreference = (string)$usePrefs;
1862 // return int
1863 if ( $datePreference == '' ) {
1864 return 'default';
1867 return $datePreference;
1871 * Get a format string for a given type and preference
1872 * @param $type string May be date, time or both
1873 * @param $pref string The format name as it appears in Messages*.php
1875 * @return string
1877 function getDateFormatString( $type, $pref ) {
1878 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1879 if ( $pref == 'default' ) {
1880 $pref = $this->getDefaultDateFormat();
1881 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1882 } else {
1883 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1884 if ( is_null( $df ) ) {
1885 $pref = $this->getDefaultDateFormat();
1886 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1889 $this->dateFormatStrings[$type][$pref] = $df;
1891 return $this->dateFormatStrings[$type][$pref];
1895 * @param $ts Mixed: the time format which needs to be turned into a
1896 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1897 * @param $adj Bool: whether to adjust the time output according to the
1898 * user configured offset ($timecorrection)
1899 * @param $format Mixed: true to use user's date format preference
1900 * @param $timecorrection String|bool the time offset as returned by
1901 * validateTimeZone() in Special:Preferences
1902 * @return string
1904 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1905 $ts = wfTimestamp( TS_MW, $ts );
1906 if ( $adj ) {
1907 $ts = $this->userAdjust( $ts, $timecorrection );
1909 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1910 return $this->sprintfDate( $df, $ts );
1914 * @param $ts Mixed: the time format which needs to be turned into a
1915 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1916 * @param $adj Bool: whether to adjust the time output according to the
1917 * user configured offset ($timecorrection)
1918 * @param $format Mixed: true to use user's date format preference
1919 * @param $timecorrection String|bool the time offset as returned by
1920 * validateTimeZone() in Special:Preferences
1921 * @return string
1923 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1924 $ts = wfTimestamp( TS_MW, $ts );
1925 if ( $adj ) {
1926 $ts = $this->userAdjust( $ts, $timecorrection );
1928 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1929 return $this->sprintfDate( $df, $ts );
1933 * @param $ts Mixed: the time format which needs to be turned into a
1934 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1935 * @param $adj Bool: whether to adjust the time output according to the
1936 * user configured offset ($timecorrection)
1937 * @param $format Mixed: what format to return, if it's false output the
1938 * default one (default true)
1939 * @param $timecorrection String|bool the time offset as returned by
1940 * validateTimeZone() in Special:Preferences
1941 * @return string
1943 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1944 $ts = wfTimestamp( TS_MW, $ts );
1945 if ( $adj ) {
1946 $ts = $this->userAdjust( $ts, $timecorrection );
1948 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1949 return $this->sprintfDate( $df, $ts );
1953 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1955 * @since 1.20
1957 * @param integer $seconds The amount of seconds.
1958 * @param array $chosenIntervals The intervals to enable.
1960 * @return string
1962 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1963 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1965 $segments = array();
1967 foreach ( $intervals as $intervalName => $intervalValue ) {
1968 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1969 $segments[] = $message->inLanguage( $this )->escaped();
1972 return $this->listToText( $segments );
1976 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1977 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1979 * @since 1.20
1981 * @param integer $seconds The amount of seconds.
1982 * @param array $chosenIntervals The intervals to enable.
1984 * @return array
1986 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1987 if ( empty( $chosenIntervals ) ) {
1988 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1991 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
1992 $sortedNames = array_keys( $intervals );
1993 $smallestInterval = array_pop( $sortedNames );
1995 $segments = array();
1997 foreach ( $intervals as $name => $length ) {
1998 $value = floor( $seconds / $length );
2000 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2001 $seconds -= $value * $length;
2002 $segments[$name] = $value;
2006 return $segments;
2010 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2012 * @param $type String: can be 'date', 'time' or 'both'
2013 * @param $ts Mixed: the time format which needs to be turned into a
2014 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2015 * @param $user User object used to get preferences for timezone and format
2016 * @param $options Array, can contain the following keys:
2017 * - 'timecorrection': time correction, can have the following values:
2018 * - true: use user's preference
2019 * - false: don't use time correction
2020 * - integer: value of time correction in minutes
2021 * - 'format': format to use, can have the following values:
2022 * - true: use user's preference
2023 * - false: use default preference
2024 * - string: format to use
2025 * @since 1.19
2026 * @return String
2028 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2029 $ts = wfTimestamp( TS_MW, $ts );
2030 $options += array( 'timecorrection' => true, 'format' => true );
2031 if ( $options['timecorrection'] !== false ) {
2032 if ( $options['timecorrection'] === true ) {
2033 $offset = $user->getOption( 'timecorrection' );
2034 } else {
2035 $offset = $options['timecorrection'];
2037 $ts = $this->userAdjust( $ts, $offset );
2039 if ( $options['format'] === true ) {
2040 $format = $user->getDatePreference();
2041 } else {
2042 $format = $options['format'];
2044 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2045 return $this->sprintfDate( $df, $ts );
2049 * Get the formatted date for the given timestamp and formatted for
2050 * the given user.
2052 * @param $ts Mixed: the time format which needs to be turned into a
2053 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2054 * @param $user User object used to get preferences for timezone and format
2055 * @param $options Array, can contain the following keys:
2056 * - 'timecorrection': time correction, can have the following values:
2057 * - true: use user's preference
2058 * - false: don't use time correction
2059 * - integer: value of time correction in minutes
2060 * - 'format': format to use, can have the following values:
2061 * - true: use user's preference
2062 * - false: use default preference
2063 * - string: format to use
2064 * @since 1.19
2065 * @return String
2067 public function userDate( $ts, User $user, array $options = array() ) {
2068 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2072 * Get the formatted time for the given timestamp and formatted for
2073 * the given user.
2075 * @param $ts Mixed: the time format which needs to be turned into a
2076 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2077 * @param $user User object used to get preferences for timezone and format
2078 * @param $options Array, can contain the following keys:
2079 * - 'timecorrection': time correction, can have the following values:
2080 * - true: use user's preference
2081 * - false: don't use time correction
2082 * - integer: value of time correction in minutes
2083 * - 'format': format to use, can have the following values:
2084 * - true: use user's preference
2085 * - false: use default preference
2086 * - string: format to use
2087 * @since 1.19
2088 * @return String
2090 public function userTime( $ts, User $user, array $options = array() ) {
2091 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2095 * Get the formatted date and time for the given timestamp and formatted for
2096 * the given user.
2098 * @param $ts Mixed: the time format which needs to be turned into a
2099 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2100 * @param $user User object used to get preferences for timezone and format
2101 * @param $options Array, can contain the following keys:
2102 * - 'timecorrection': time correction, can have the following values:
2103 * - true: use user's preference
2104 * - false: don't use time correction
2105 * - integer: value of time correction in minutes
2106 * - 'format': format to use, can have the following values:
2107 * - true: use user's preference
2108 * - false: use default preference
2109 * - string: format to use
2110 * @since 1.19
2111 * @return String
2113 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2114 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2118 * @param $key string
2119 * @return array|null
2121 function getMessage( $key ) {
2122 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2126 * @return array
2128 function getAllMessages() {
2129 return self::$dataCache->getItem( $this->mCode, 'messages' );
2133 * @param $in
2134 * @param $out
2135 * @param $string
2136 * @return string
2138 function iconv( $in, $out, $string ) {
2139 # This is a wrapper for iconv in all languages except esperanto,
2140 # which does some nasty x-conversions beforehand
2142 # Even with //IGNORE iconv can whine about illegal characters in
2143 # *input* string. We just ignore those too.
2144 # REF: http://bugs.php.net/bug.php?id=37166
2145 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2146 wfSuppressWarnings();
2147 $text = iconv( $in, $out . '//IGNORE', $string );
2148 wfRestoreWarnings();
2149 return $text;
2152 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2155 * @param $matches array
2156 * @return mixed|string
2158 function ucwordbreaksCallbackAscii( $matches ) {
2159 return $this->ucfirst( $matches[1] );
2163 * @param $matches array
2164 * @return string
2166 function ucwordbreaksCallbackMB( $matches ) {
2167 return mb_strtoupper( $matches[0] );
2171 * @param $matches array
2172 * @return string
2174 function ucCallback( $matches ) {
2175 list( $wikiUpperChars ) = self::getCaseMaps();
2176 return strtr( $matches[1], $wikiUpperChars );
2180 * @param $matches array
2181 * @return string
2183 function lcCallback( $matches ) {
2184 list( , $wikiLowerChars ) = self::getCaseMaps();
2185 return strtr( $matches[1], $wikiLowerChars );
2189 * @param $matches array
2190 * @return string
2192 function ucwordsCallbackMB( $matches ) {
2193 return mb_strtoupper( $matches[0] );
2197 * @param $matches array
2198 * @return string
2200 function ucwordsCallbackWiki( $matches ) {
2201 list( $wikiUpperChars ) = self::getCaseMaps();
2202 return strtr( $matches[0], $wikiUpperChars );
2206 * Make a string's first character uppercase
2208 * @param $str string
2210 * @return string
2212 function ucfirst( $str ) {
2213 $o = ord( $str );
2214 if ( $o < 96 ) { // if already uppercase...
2215 return $str;
2216 } elseif ( $o < 128 ) {
2217 return ucfirst( $str ); // use PHP's ucfirst()
2218 } else {
2219 // fall back to more complex logic in case of multibyte strings
2220 return $this->uc( $str, true );
2225 * Convert a string to uppercase
2227 * @param $str string
2228 * @param $first bool
2230 * @return string
2232 function uc( $str, $first = false ) {
2233 if ( function_exists( 'mb_strtoupper' ) ) {
2234 if ( $first ) {
2235 if ( $this->isMultibyte( $str ) ) {
2236 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2237 } else {
2238 return ucfirst( $str );
2240 } else {
2241 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2243 } else {
2244 if ( $this->isMultibyte( $str ) ) {
2245 $x = $first ? '^' : '';
2246 return preg_replace_callback(
2247 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2248 array( $this, 'ucCallback' ),
2249 $str
2251 } else {
2252 return $first ? ucfirst( $str ) : strtoupper( $str );
2258 * @param $str string
2259 * @return mixed|string
2261 function lcfirst( $str ) {
2262 $o = ord( $str );
2263 if ( !$o ) {
2264 return strval( $str );
2265 } elseif ( $o >= 128 ) {
2266 return $this->lc( $str, true );
2267 } elseif ( $o > 96 ) {
2268 return $str;
2269 } else {
2270 $str[0] = strtolower( $str[0] );
2271 return $str;
2276 * @param $str string
2277 * @param $first bool
2278 * @return mixed|string
2280 function lc( $str, $first = false ) {
2281 if ( function_exists( 'mb_strtolower' ) ) {
2282 if ( $first ) {
2283 if ( $this->isMultibyte( $str ) ) {
2284 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2285 } else {
2286 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2288 } else {
2289 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2291 } else {
2292 if ( $this->isMultibyte( $str ) ) {
2293 $x = $first ? '^' : '';
2294 return preg_replace_callback(
2295 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2296 array( $this, 'lcCallback' ),
2297 $str
2299 } else {
2300 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2306 * @param $str string
2307 * @return bool
2309 function isMultibyte( $str ) {
2310 return (bool)preg_match( '/[\x80-\xff]/', $str );
2314 * @param $str string
2315 * @return mixed|string
2317 function ucwords( $str ) {
2318 if ( $this->isMultibyte( $str ) ) {
2319 $str = $this->lc( $str );
2321 // regexp to find first letter in each word (i.e. after each space)
2322 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2324 // function to use to capitalize a single char
2325 if ( function_exists( 'mb_strtoupper' ) ) {
2326 return preg_replace_callback(
2327 $replaceRegexp,
2328 array( $this, 'ucwordsCallbackMB' ),
2329 $str
2331 } else {
2332 return preg_replace_callback(
2333 $replaceRegexp,
2334 array( $this, 'ucwordsCallbackWiki' ),
2335 $str
2338 } else {
2339 return ucwords( strtolower( $str ) );
2344 * capitalize words at word breaks
2346 * @param $str string
2347 * @return mixed
2349 function ucwordbreaks( $str ) {
2350 if ( $this->isMultibyte( $str ) ) {
2351 $str = $this->lc( $str );
2353 // since \b doesn't work for UTF-8, we explicitely define word break chars
2354 $breaks = "[ \-\(\)\}\{\.,\?!]";
2356 // find first letter after word break
2357 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2359 if ( function_exists( 'mb_strtoupper' ) ) {
2360 return preg_replace_callback(
2361 $replaceRegexp,
2362 array( $this, 'ucwordbreaksCallbackMB' ),
2363 $str
2365 } else {
2366 return preg_replace_callback(
2367 $replaceRegexp,
2368 array( $this, 'ucwordsCallbackWiki' ),
2369 $str
2372 } else {
2373 return preg_replace_callback(
2374 '/\b([\w\x80-\xff]+)\b/',
2375 array( $this, 'ucwordbreaksCallbackAscii' ),
2376 $str
2382 * Return a case-folded representation of $s
2384 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2385 * and $s2 are the same except for the case of their characters. It is not
2386 * necessary for the value returned to make sense when displayed.
2388 * Do *not* perform any other normalisation in this function. If a caller
2389 * uses this function when it should be using a more general normalisation
2390 * function, then fix the caller.
2392 * @param $s string
2394 * @return string
2396 function caseFold( $s ) {
2397 return $this->uc( $s );
2401 * @param $s string
2402 * @return string
2404 function checkTitleEncoding( $s ) {
2405 if ( is_array( $s ) ) {
2406 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2408 # Check for non-UTF-8 URLs
2409 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2410 if ( !$ishigh ) {
2411 return $s;
2414 if ( function_exists( 'mb_check_encoding' ) ) {
2415 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2416 } else {
2417 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2418 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2420 if ( $isutf8 ) {
2421 return $s;
2424 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2428 * @return array
2430 function fallback8bitEncoding() {
2431 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2435 * Most writing systems use whitespace to break up words.
2436 * Some languages such as Chinese don't conventionally do this,
2437 * which requires special handling when breaking up words for
2438 * searching etc.
2440 * @return bool
2442 function hasWordBreaks() {
2443 return true;
2447 * Some languages such as Chinese require word segmentation,
2448 * Specify such segmentation when overridden in derived class.
2450 * @param $string String
2451 * @return String
2453 function segmentByWord( $string ) {
2454 return $string;
2458 * Some languages have special punctuation need to be normalized.
2459 * Make such changes here.
2461 * @param $string String
2462 * @return String
2464 function normalizeForSearch( $string ) {
2465 return self::convertDoubleWidth( $string );
2469 * convert double-width roman characters to single-width.
2470 * range: ff00-ff5f ~= 0020-007f
2472 * @param $string string
2474 * @return string
2476 protected static function convertDoubleWidth( $string ) {
2477 static $full = null;
2478 static $half = null;
2480 if ( $full === null ) {
2481 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2482 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2483 $full = str_split( $fullWidth, 3 );
2484 $half = str_split( $halfWidth );
2487 $string = str_replace( $full, $half, $string );
2488 return $string;
2492 * @param $string string
2493 * @param $pattern string
2494 * @return string
2496 protected static function insertSpace( $string, $pattern ) {
2497 $string = preg_replace( $pattern, " $1 ", $string );
2498 $string = preg_replace( '/ +/', ' ', $string );
2499 return $string;
2503 * @param $termsArray array
2504 * @return array
2506 function convertForSearchResult( $termsArray ) {
2507 # some languages, e.g. Chinese, need to do a conversion
2508 # in order for search results to be displayed correctly
2509 return $termsArray;
2513 * Get the first character of a string.
2515 * @param $s string
2516 * @return string
2518 function firstChar( $s ) {
2519 $matches = array();
2520 preg_match(
2521 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2522 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2524 $matches
2527 if ( isset( $matches[1] ) ) {
2528 if ( strlen( $matches[1] ) != 3 ) {
2529 return $matches[1];
2532 // Break down Hangul syllables to grab the first jamo
2533 $code = utf8ToCodepoint( $matches[1] );
2534 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2535 return $matches[1];
2536 } elseif ( $code < 0xb098 ) {
2537 return "\xe3\x84\xb1";
2538 } elseif ( $code < 0xb2e4 ) {
2539 return "\xe3\x84\xb4";
2540 } elseif ( $code < 0xb77c ) {
2541 return "\xe3\x84\xb7";
2542 } elseif ( $code < 0xb9c8 ) {
2543 return "\xe3\x84\xb9";
2544 } elseif ( $code < 0xbc14 ) {
2545 return "\xe3\x85\x81";
2546 } elseif ( $code < 0xc0ac ) {
2547 return "\xe3\x85\x82";
2548 } elseif ( $code < 0xc544 ) {
2549 return "\xe3\x85\x85";
2550 } elseif ( $code < 0xc790 ) {
2551 return "\xe3\x85\x87";
2552 } elseif ( $code < 0xcc28 ) {
2553 return "\xe3\x85\x88";
2554 } elseif ( $code < 0xce74 ) {
2555 return "\xe3\x85\x8a";
2556 } elseif ( $code < 0xd0c0 ) {
2557 return "\xe3\x85\x8b";
2558 } elseif ( $code < 0xd30c ) {
2559 return "\xe3\x85\x8c";
2560 } elseif ( $code < 0xd558 ) {
2561 return "\xe3\x85\x8d";
2562 } else {
2563 return "\xe3\x85\x8e";
2565 } else {
2566 return '';
2570 function initEncoding() {
2571 # Some languages may have an alternate char encoding option
2572 # (Esperanto X-coding, Japanese furigana conversion, etc)
2573 # If this language is used as the primary content language,
2574 # an override to the defaults can be set here on startup.
2578 * @param $s string
2579 * @return string
2581 function recodeForEdit( $s ) {
2582 # For some languages we'll want to explicitly specify
2583 # which characters make it into the edit box raw
2584 # or are converted in some way or another.
2585 global $wgEditEncoding;
2586 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2587 return $s;
2588 } else {
2589 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2594 * @param $s string
2595 * @return string
2597 function recodeInput( $s ) {
2598 # Take the previous into account.
2599 global $wgEditEncoding;
2600 if ( $wgEditEncoding != '' ) {
2601 $enc = $wgEditEncoding;
2602 } else {
2603 $enc = 'UTF-8';
2605 if ( $enc == 'UTF-8' ) {
2606 return $s;
2607 } else {
2608 return $this->iconv( $enc, 'UTF-8', $s );
2613 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2614 * also cleans up certain backwards-compatible sequences, converting them
2615 * to the modern Unicode equivalent.
2617 * This is language-specific for performance reasons only.
2619 * @param $s string
2621 * @return string
2623 function normalize( $s ) {
2624 global $wgAllUnicodeFixes;
2625 $s = UtfNormal::cleanUp( $s );
2626 if ( $wgAllUnicodeFixes ) {
2627 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2628 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2631 return $s;
2635 * Transform a string using serialized data stored in the given file (which
2636 * must be in the serialized subdirectory of $IP). The file contains pairs
2637 * mapping source characters to destination characters.
2639 * The data is cached in process memory. This will go faster if you have the
2640 * FastStringSearch extension.
2642 * @param $file string
2643 * @param $string string
2645 * @throws MWException
2646 * @return string
2648 function transformUsingPairFile( $file, $string ) {
2649 if ( !isset( $this->transformData[$file] ) ) {
2650 $data = wfGetPrecompiledData( $file );
2651 if ( $data === false ) {
2652 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2654 $this->transformData[$file] = new ReplacementArray( $data );
2656 return $this->transformData[$file]->replace( $string );
2660 * For right-to-left language support
2662 * @return bool
2664 function isRTL() {
2665 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2669 * Return the correct HTML 'dir' attribute value for this language.
2670 * @return String
2672 function getDir() {
2673 return $this->isRTL() ? 'rtl' : 'ltr';
2677 * Return 'left' or 'right' as appropriate alignment for line-start
2678 * for this language's text direction.
2680 * Should be equivalent to CSS3 'start' text-align value....
2682 * @return String
2684 function alignStart() {
2685 return $this->isRTL() ? 'right' : 'left';
2689 * Return 'right' or 'left' as appropriate alignment for line-end
2690 * for this language's text direction.
2692 * Should be equivalent to CSS3 'end' text-align value....
2694 * @return String
2696 function alignEnd() {
2697 return $this->isRTL() ? 'left' : 'right';
2701 * A hidden direction mark (LRM or RLM), depending on the language direction.
2702 * Unlike getDirMark(), this function returns the character as an HTML entity.
2703 * This function should be used when the output is guaranteed to be HTML,
2704 * because it makes the output HTML source code more readable. When
2705 * the output is plain text or can be escaped, getDirMark() should be used.
2707 * @param $opposite Boolean Get the direction mark opposite to your language
2708 * @return string
2709 * @since 1.20
2711 function getDirMarkEntity( $opposite = false ) {
2712 if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
2713 return $this->isRTL() ? '&rlm;' : '&lrm;';
2717 * A hidden direction mark (LRM or RLM), depending on the language direction.
2718 * This function produces them as invisible Unicode characters and
2719 * the output may be hard to read and debug, so it should only be used
2720 * when the output is plain text or can be escaped. When the output is
2721 * HTML, use getDirMarkEntity() instead.
2723 * @param $opposite Boolean Get the direction mark opposite to your language
2724 * @return string
2726 function getDirMark( $opposite = false ) {
2727 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2728 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2729 if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
2730 return $this->isRTL() ? $rlm : $lrm;
2734 * @return array
2736 function capitalizeAllNouns() {
2737 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2741 * An arrow, depending on the language direction.
2743 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2744 * @return string
2746 function getArrow( $direction = 'forwards' ) {
2747 switch ( $direction ) {
2748 case 'forwards':
2749 return $this->isRTL() ? '←' : '→';
2750 case 'backwards':
2751 return $this->isRTL() ? '→' : '←';
2752 case 'left':
2753 return '←';
2754 case 'right':
2755 return '→';
2756 case 'up':
2757 return '↑';
2758 case 'down':
2759 return '↓';
2764 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2766 * @return bool
2768 function linkPrefixExtension() {
2769 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2773 * @return array
2775 function getMagicWords() {
2776 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2779 protected function doMagicHook() {
2780 if ( $this->mMagicHookDone ) {
2781 return;
2783 $this->mMagicHookDone = true;
2784 wfProfileIn( 'LanguageGetMagic' );
2785 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2786 wfProfileOut( 'LanguageGetMagic' );
2790 * Fill a MagicWord object with data from here
2792 * @param $mw
2794 function getMagic( $mw ) {
2795 $this->doMagicHook();
2797 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2798 $rawEntry = $this->mMagicExtensions[$mw->mId];
2799 } else {
2800 $magicWords = $this->getMagicWords();
2801 if ( isset( $magicWords[$mw->mId] ) ) {
2802 $rawEntry = $magicWords[$mw->mId];
2803 } else {
2804 $rawEntry = false;
2808 if ( !is_array( $rawEntry ) ) {
2809 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2810 } else {
2811 $mw->mCaseSensitive = $rawEntry[0];
2812 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2817 * Add magic words to the extension array
2819 * @param $newWords array
2821 function addMagicWordsByLang( $newWords ) {
2822 $fallbackChain = $this->getFallbackLanguages();
2823 $fallbackChain = array_reverse( $fallbackChain );
2824 foreach ( $fallbackChain as $code ) {
2825 if ( isset( $newWords[$code] ) ) {
2826 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2832 * Get special page names, as an associative array
2833 * case folded alias => real name
2835 function getSpecialPageAliases() {
2836 // Cache aliases because it may be slow to load them
2837 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2838 // Initialise array
2839 $this->mExtendedSpecialPageAliases =
2840 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2841 wfRunHooks( 'LanguageGetSpecialPageAliases',
2842 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2845 return $this->mExtendedSpecialPageAliases;
2849 * Italic is unsuitable for some languages
2851 * @param $text String: the text to be emphasized.
2852 * @return string
2854 function emphasize( $text ) {
2855 return "<em>$text</em>";
2859 * Normally we output all numbers in plain en_US style, that is
2860 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2861 * point twohundredthirtyfive. However this is not suitable for all
2862 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2863 * Icelandic just want to use commas instead of dots, and dots instead
2864 * of commas like "293.291,235".
2866 * An example of this function being called:
2867 * <code>
2868 * wfMessage( 'message' )->numParams( $num )->text()
2869 * </code>
2871 * See LanguageGu.php for the Gujarati implementation and
2872 * $separatorTransformTable on MessageIs.php for
2873 * the , => . and . => , implementation.
2875 * @todo check if it's viable to use localeconv() for the decimal
2876 * separator thing.
2877 * @param $number Mixed: the string to be formatted, should be an integer
2878 * or a floating point number.
2879 * @param $nocommafy Bool: set to true for special numbers like dates
2880 * @return string
2882 public function formatNum( $number, $nocommafy = false ) {
2883 global $wgTranslateNumerals;
2884 if ( !$nocommafy ) {
2885 $number = $this->commafy( $number );
2886 $s = $this->separatorTransformTable();
2887 if ( $s ) {
2888 $number = strtr( $number, $s );
2892 if ( $wgTranslateNumerals ) {
2893 $s = $this->digitTransformTable();
2894 if ( $s ) {
2895 $number = strtr( $number, $s );
2899 return $number;
2903 * @param $number string
2904 * @return string
2906 function parseFormattedNumber( $number ) {
2907 $s = $this->digitTransformTable();
2908 if ( $s ) {
2909 $number = strtr( $number, array_flip( $s ) );
2912 $s = $this->separatorTransformTable();
2913 if ( $s ) {
2914 $number = strtr( $number, array_flip( $s ) );
2917 $number = strtr( $number, array( ',' => '' ) );
2918 return $number;
2922 * Adds commas to a given number
2923 * @since 1.19
2924 * @param $_ mixed
2925 * @return string
2927 function commafy( $_ ) {
2928 $digitGroupingPattern = $this->digitGroupingPattern();
2929 if ( $_ === null ) {
2930 return '';
2933 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2934 // default grouping is at thousands, use the same for ###,###,### pattern too.
2935 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2936 } else {
2937 // Ref: http://cldr.unicode.org/translation/number-patterns
2938 $sign = "";
2939 if ( intval( $_ ) < 0 ) {
2940 // For negative numbers apply the algorithm like positive number and add sign.
2941 $sign = "-";
2942 $_ = substr( $_, 1 );
2944 $numberpart = array();
2945 $decimalpart = array();
2946 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2947 preg_match( "/\d+/", $_, $numberpart );
2948 preg_match( "/\.\d*/", $_, $decimalpart );
2949 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2950 if ( $groupedNumber === $_ ) {
2951 // the string does not have any number part. Eg: .12345
2952 return $sign . $groupedNumber;
2954 $start = $end = strlen( $numberpart[0] );
2955 while ( $start > 0 ) {
2956 $match = $matches[0][$numMatches -1] ;
2957 $matchLen = strlen( $match );
2958 $start = $end - $matchLen;
2959 if ( $start < 0 ) {
2960 $start = 0;
2962 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2963 $end = $start;
2964 if ( $numMatches > 1 ) {
2965 // use the last pattern for the rest of the number
2966 $numMatches--;
2968 if ( $start > 0 ) {
2969 $groupedNumber = "," . $groupedNumber;
2972 return $sign . $groupedNumber;
2976 * @return String
2978 function digitGroupingPattern() {
2979 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
2983 * @return array
2985 function digitTransformTable() {
2986 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2990 * @return array
2992 function separatorTransformTable() {
2993 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2997 * Take a list of strings and build a locale-friendly comma-separated
2998 * list, using the local comma-separator message.
2999 * The last two strings are chained with an "and".
3000 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3002 * @param $l Array
3003 * @return string
3005 function listToText( array $l ) {
3006 $s = '';
3007 $m = count( $l ) - 1;
3009 if ( $m === 0 ) {
3010 return $l[0];
3011 } elseif ( $m === 1 ) {
3012 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3013 } else {
3014 for ( $i = $m; $i >= 0; $i-- ) {
3015 if ( $i == $m ) {
3016 $s = $l[$i];
3017 } elseif ( $i == $m - 1 ) {
3018 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3019 } else {
3020 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3023 return $s;
3028 * Take a list of strings and build a locale-friendly comma-separated
3029 * list, using the local comma-separator message.
3030 * @param $list array of strings to put in a comma list
3031 * @return string
3033 function commaList( array $list ) {
3034 return implode(
3035 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3036 $list
3041 * Take a list of strings and build a locale-friendly semicolon-separated
3042 * list, using the local semicolon-separator message.
3043 * @param $list array of strings to put in a semicolon list
3044 * @return string
3046 function semicolonList( array $list ) {
3047 return implode(
3048 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3049 $list
3054 * Same as commaList, but separate it with the pipe instead.
3055 * @param $list array of strings to put in a pipe list
3056 * @return string
3058 function pipeList( array $list ) {
3059 return implode(
3060 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3061 $list
3066 * Truncate a string to a specified length in bytes, appending an optional
3067 * string (e.g. for ellipses)
3069 * The database offers limited byte lengths for some columns in the database;
3070 * multi-byte character sets mean we need to ensure that only whole characters
3071 * are included, otherwise broken characters can be passed to the user
3073 * If $length is negative, the string will be truncated from the beginning
3075 * @param $string String to truncate
3076 * @param $length Int: maximum length (including ellipses)
3077 * @param $ellipsis String to append to the truncated text
3078 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3079 * $adjustLength was introduced in 1.18, before that behaved as if false.
3080 * @return string
3082 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3083 # Use the localized ellipsis character
3084 if ( $ellipsis == '...' ) {
3085 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3087 # Check if there is no need to truncate
3088 if ( $length == 0 ) {
3089 return $ellipsis; // convention
3090 } elseif ( strlen( $string ) <= abs( $length ) ) {
3091 return $string; // no need to truncate
3093 $stringOriginal = $string;
3094 # If ellipsis length is >= $length then we can't apply $adjustLength
3095 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3096 $string = $ellipsis; // this can be slightly unexpected
3097 # Otherwise, truncate and add ellipsis...
3098 } else {
3099 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3100 if ( $length > 0 ) {
3101 $length -= $eLength;
3102 $string = substr( $string, 0, $length ); // xyz...
3103 $string = $this->removeBadCharLast( $string );
3104 $string = $string . $ellipsis;
3105 } else {
3106 $length += $eLength;
3107 $string = substr( $string, $length ); // ...xyz
3108 $string = $this->removeBadCharFirst( $string );
3109 $string = $ellipsis . $string;
3112 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3113 # This check is *not* redundant if $adjustLength, due to the single case where
3114 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3115 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3116 return $string;
3117 } else {
3118 return $stringOriginal;
3123 * Remove bytes that represent an incomplete Unicode character
3124 * at the end of string (e.g. bytes of the char are missing)
3126 * @param $string String
3127 * @return string
3129 protected function removeBadCharLast( $string ) {
3130 if ( $string != '' ) {
3131 $char = ord( $string[strlen( $string ) - 1] );
3132 $m = array();
3133 if ( $char >= 0xc0 ) {
3134 # We got the first byte only of a multibyte char; remove it.
3135 $string = substr( $string, 0, -1 );
3136 } elseif ( $char >= 0x80 &&
3137 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3138 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3140 # We chopped in the middle of a character; remove it
3141 $string = $m[1];
3144 return $string;
3148 * Remove bytes that represent an incomplete Unicode character
3149 * at the start of string (e.g. bytes of the char are missing)
3151 * @param $string String
3152 * @return string
3154 protected function removeBadCharFirst( $string ) {
3155 if ( $string != '' ) {
3156 $char = ord( $string[0] );
3157 if ( $char >= 0x80 && $char < 0xc0 ) {
3158 # We chopped in the middle of a character; remove the whole thing
3159 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3162 return $string;
3166 * Truncate a string of valid HTML to a specified length in bytes,
3167 * appending an optional string (e.g. for ellipses), and return valid HTML
3169 * This is only intended for styled/linked text, such as HTML with
3170 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3171 * Also, this will not detect things like "display:none" CSS.
3173 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3175 * @param string $text HTML string to truncate
3176 * @param int $length (zero/positive) Maximum length (including ellipses)
3177 * @param string $ellipsis String to append to the truncated text
3178 * @return string
3180 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3181 # Use the localized ellipsis character
3182 if ( $ellipsis == '...' ) {
3183 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3185 # Check if there is clearly no need to truncate
3186 if ( $length <= 0 ) {
3187 return $ellipsis; // no text shown, nothing to format (convention)
3188 } elseif ( strlen( $text ) <= $length ) {
3189 return $text; // string short enough even *with* HTML (short-circuit)
3192 $dispLen = 0; // innerHTML legth so far
3193 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3194 $tagType = 0; // 0-open, 1-close
3195 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3196 $entityState = 0; // 0-not entity, 1-entity
3197 $tag = $ret = ''; // accumulated tag name, accumulated result string
3198 $openTags = array(); // open tag stack
3199 $maybeState = null; // possible truncation state
3201 $textLen = strlen( $text );
3202 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3203 for ( $pos = 0; true; ++$pos ) {
3204 # Consider truncation once the display length has reached the maximim.
3205 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3206 # Check that we're not in the middle of a bracket/entity...
3207 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3208 if ( !$testingEllipsis ) {
3209 $testingEllipsis = true;
3210 # Save where we are; we will truncate here unless there turn out to
3211 # be so few remaining characters that truncation is not necessary.
3212 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3213 $maybeState = array( $ret, $openTags ); // save state
3215 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3216 # String in fact does need truncation, the truncation point was OK.
3217 list( $ret, $openTags ) = $maybeState; // reload state
3218 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3219 $ret .= $ellipsis; // add ellipsis
3220 break;
3223 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3225 # Read the next char...
3226 $ch = $text[$pos];
3227 $lastCh = $pos ? $text[$pos - 1] : '';
3228 $ret .= $ch; // add to result string
3229 if ( $ch == '<' ) {
3230 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3231 $entityState = 0; // for bad HTML
3232 $bracketState = 1; // tag started (checking for backslash)
3233 } elseif ( $ch == '>' ) {
3234 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3235 $entityState = 0; // for bad HTML
3236 $bracketState = 0; // out of brackets
3237 } elseif ( $bracketState == 1 ) {
3238 if ( $ch == '/' ) {
3239 $tagType = 1; // close tag (e.g. "</span>")
3240 } else {
3241 $tagType = 0; // open tag (e.g. "<span>")
3242 $tag .= $ch;
3244 $bracketState = 2; // building tag name
3245 } elseif ( $bracketState == 2 ) {
3246 if ( $ch != ' ' ) {
3247 $tag .= $ch;
3248 } else {
3249 // Name found (e.g. "<a href=..."), add on tag attributes...
3250 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3252 } elseif ( $bracketState == 0 ) {
3253 if ( $entityState ) {
3254 if ( $ch == ';' ) {
3255 $entityState = 0;
3256 $dispLen++; // entity is one displayed char
3258 } else {
3259 if ( $neLength == 0 && !$maybeState ) {
3260 // Save state without $ch. We want to *hit* the first
3261 // display char (to get tags) but not *use* it if truncating.
3262 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3264 if ( $ch == '&' ) {
3265 $entityState = 1; // entity found, (e.g. "&#160;")
3266 } else {
3267 $dispLen++; // this char is displayed
3268 // Add the next $max display text chars after this in one swoop...
3269 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3270 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3271 $dispLen += $skipped;
3272 $pos += $skipped;
3277 // Close the last tag if left unclosed by bad HTML
3278 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3279 while ( count( $openTags ) > 0 ) {
3280 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3282 return $ret;
3286 * truncateHtml() helper function
3287 * like strcspn() but adds the skipped chars to $ret
3289 * @param $ret
3290 * @param $text
3291 * @param $search
3292 * @param $start
3293 * @param $len
3294 * @return int
3296 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3297 if ( $len === null ) {
3298 $len = -1; // -1 means "no limit" for strcspn
3299 } elseif ( $len < 0 ) {
3300 $len = 0; // sanity
3302 $skipCount = 0;
3303 if ( $start < strlen( $text ) ) {
3304 $skipCount = strcspn( $text, $search, $start, $len );
3305 $ret .= substr( $text, $start, $skipCount );
3307 return $skipCount;
3311 * truncateHtml() helper function
3312 * (a) push or pop $tag from $openTags as needed
3313 * (b) clear $tag value
3314 * @param &$tag string Current HTML tag name we are looking at
3315 * @param $tagType int (0-open tag, 1-close tag)
3316 * @param $lastCh string Character before the '>' that ended this tag
3317 * @param &$openTags array Open tag stack (not accounting for $tag)
3319 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3320 $tag = ltrim( $tag );
3321 if ( $tag != '' ) {
3322 if ( $tagType == 0 && $lastCh != '/' ) {
3323 $openTags[] = $tag; // tag opened (didn't close itself)
3324 } elseif ( $tagType == 1 ) {
3325 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3326 array_pop( $openTags ); // tag closed
3329 $tag = '';
3334 * Grammatical transformations, needed for inflected languages
3335 * Invoked by putting {{grammar:case|word}} in a message
3337 * @param $word string
3338 * @param $case string
3339 * @return string
3341 function convertGrammar( $word, $case ) {
3342 global $wgGrammarForms;
3343 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3344 return $wgGrammarForms[$this->getCode()][$case][$word];
3346 return $word;
3349 * Get the grammar forms for the content language
3350 * @return array of grammar forms
3351 * @since 1.20
3353 function getGrammarForms() {
3354 global $wgGrammarForms;
3355 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3356 return $wgGrammarForms[$this->getCode()];
3358 return array();
3361 * Provides an alternative text depending on specified gender.
3362 * Usage {{gender:username|masculine|feminine|neutral}}.
3363 * username is optional, in which case the gender of current user is used,
3364 * but only in (some) interface messages; otherwise default gender is used.
3366 * If no forms are given, an empty string is returned. If only one form is
3367 * given, it will be returned unconditionally. These details are implied by
3368 * the caller and cannot be overridden in subclasses.
3370 * If more than one form is given, the default is to use the neutral one
3371 * if it is specified, and to use the masculine one otherwise. These
3372 * details can be overridden in subclasses.
3374 * @param $gender string
3375 * @param $forms array
3377 * @return string
3379 function gender( $gender, $forms ) {
3380 if ( !count( $forms ) ) {
3381 return '';
3383 $forms = $this->preConvertPlural( $forms, 2 );
3384 if ( $gender === 'male' ) {
3385 return $forms[0];
3387 if ( $gender === 'female' ) {
3388 return $forms[1];
3390 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3394 * Plural form transformations, needed for some languages.
3395 * For example, there are 3 form of plural in Russian and Polish,
3396 * depending on "count mod 10". See [[w:Plural]]
3397 * For English it is pretty simple.
3399 * Invoked by putting {{plural:count|wordform1|wordform2}}
3400 * or {{plural:count|wordform1|wordform2|wordform3}}
3402 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3404 * @param $count Integer: non-localized number
3405 * @param $forms Array: different plural forms
3406 * @return string Correct form of plural for $count in this language
3408 function convertPlural( $count, $forms ) {
3409 if ( !count( $forms ) ) {
3410 return '';
3412 $pluralForm = $this->getPluralForm( $count );
3413 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3414 return $forms[$pluralForm];
3418 * Checks that convertPlural was given an array and pads it to requested
3419 * amount of forms by copying the last one.
3421 * @param $count Integer: How many forms should there be at least
3422 * @param $forms Array of forms given to convertPlural
3423 * @return array Padded array of forms or an exception if not an array
3425 protected function preConvertPlural( /* Array */ $forms, $count ) {
3426 while ( count( $forms ) < $count ) {
3427 $forms[] = $forms[count( $forms ) - 1];
3429 return $forms;
3433 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3434 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3435 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3436 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3437 * match up with it.
3439 * @param $str String: the validated block duration in English
3440 * @return string Somehow translated block duration
3441 * @see LanguageFi.php for example implementation
3443 function translateBlockExpiry( $str ) {
3444 $duration = SpecialBlock::getSuggestedDurations( $this );
3445 foreach ( $duration as $show => $value ) {
3446 if ( strcmp( $str, $value ) == 0 ) {
3447 return htmlspecialchars( trim( $show ) );
3451 // Since usually only infinite or indefinite is only on list, so try
3452 // equivalents if still here.
3453 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3454 if ( in_array( $str, $indefs ) ) {
3455 foreach ( $indefs as $val ) {
3456 $show = array_search( $val, $duration, true );
3457 if ( $show !== false ) {
3458 return htmlspecialchars( trim( $show ) );
3462 // If all else fails, return the original string.
3463 return $str;
3467 * languages like Chinese need to be segmented in order for the diff
3468 * to be of any use
3470 * @param $text String
3471 * @return String
3473 public function segmentForDiff( $text ) {
3474 return $text;
3478 * and unsegment to show the result
3480 * @param $text String
3481 * @return String
3483 public function unsegmentForDiff( $text ) {
3484 return $text;
3488 * Return the LanguageConverter used in the Language
3490 * @since 1.19
3491 * @return LanguageConverter
3493 public function getConverter() {
3494 return $this->mConverter;
3498 * convert text to all supported variants
3500 * @param $text string
3501 * @return array
3503 public function autoConvertToAllVariants( $text ) {
3504 return $this->mConverter->autoConvertToAllVariants( $text );
3508 * convert text to different variants of a language.
3510 * @param $text string
3511 * @return string
3513 public function convert( $text ) {
3514 return $this->mConverter->convert( $text );
3518 * Convert a Title object to a string in the preferred variant
3520 * @param $title Title
3521 * @return string
3523 public function convertTitle( $title ) {
3524 return $this->mConverter->convertTitle( $title );
3528 * Check if this is a language with variants
3530 * @return bool
3532 public function hasVariants() {
3533 return sizeof( $this->getVariants() ) > 1;
3537 * Check if the language has the specific variant
3539 * @since 1.19
3540 * @param $variant string
3541 * @return bool
3543 public function hasVariant( $variant ) {
3544 return (bool)$this->mConverter->validateVariant( $variant );
3548 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3550 * @param $text string
3551 * @return string
3553 public function armourMath( $text ) {
3554 return $this->mConverter->armourMath( $text );
3558 * Perform output conversion on a string, and encode for safe HTML output.
3559 * @param $text String text to be converted
3560 * @param $isTitle Bool whether this conversion is for the article title
3561 * @return string
3562 * @todo this should get integrated somewhere sane
3564 public function convertHtml( $text, $isTitle = false ) {
3565 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3569 * @param $key string
3570 * @return string
3572 public function convertCategoryKey( $key ) {
3573 return $this->mConverter->convertCategoryKey( $key );
3577 * Get the list of variants supported by this language
3578 * see sample implementation in LanguageZh.php
3580 * @return array an array of language codes
3582 public function getVariants() {
3583 return $this->mConverter->getVariants();
3587 * @return string
3589 public function getPreferredVariant() {
3590 return $this->mConverter->getPreferredVariant();
3594 * @return string
3596 public function getDefaultVariant() {
3597 return $this->mConverter->getDefaultVariant();
3601 * @return string
3603 public function getURLVariant() {
3604 return $this->mConverter->getURLVariant();
3608 * If a language supports multiple variants, it is
3609 * possible that non-existing link in one variant
3610 * actually exists in another variant. this function
3611 * tries to find it. See e.g. LanguageZh.php
3613 * @param $link String: the name of the link
3614 * @param $nt Mixed: the title object of the link
3615 * @param $ignoreOtherCond Boolean: to disable other conditions when
3616 * we need to transclude a template or update a category's link
3617 * @return null the input parameters may be modified upon return
3619 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3620 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3624 * If a language supports multiple variants, converts text
3625 * into an array of all possible variants of the text:
3626 * 'variant' => text in that variant
3628 * @deprecated since 1.17 Use autoConvertToAllVariants()
3630 * @param $text string
3632 * @return string
3634 public function convertLinkToAllVariants( $text ) {
3635 return $this->mConverter->convertLinkToAllVariants( $text );
3639 * returns language specific options used by User::getPageRenderHash()
3640 * for example, the preferred language variant
3642 * @return string
3644 function getExtraHashOptions() {
3645 return $this->mConverter->getExtraHashOptions();
3649 * For languages that support multiple variants, the title of an
3650 * article may be displayed differently in different variants. this
3651 * function returns the apporiate title defined in the body of the article.
3653 * @return string
3655 public function getParsedTitle() {
3656 return $this->mConverter->getParsedTitle();
3660 * Enclose a string with the "no conversion" tag. This is used by
3661 * various functions in the Parser
3663 * @param $text String: text to be tagged for no conversion
3664 * @param $noParse bool
3665 * @return string the tagged text
3667 public function markNoConversion( $text, $noParse = false ) {
3668 return $this->mConverter->markNoConversion( $text, $noParse );
3672 * A regular expression to match legal word-trailing characters
3673 * which should be merged onto a link of the form [[foo]]bar.
3675 * @return string
3677 public function linkTrail() {
3678 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3682 * @return Language
3684 function getLangObj() {
3685 return $this;
3689 * Get the RFC 3066 code for this language object
3691 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3692 * htmlspecialchars() or similar
3694 * @return string
3696 public function getCode() {
3697 return $this->mCode;
3701 * Get the code in Bcp47 format which we can use
3702 * inside of html lang="" tags.
3704 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3705 * htmlspecialchars() or similar.
3707 * @since 1.19
3708 * @return string
3710 public function getHtmlCode() {
3711 if ( is_null( $this->mHtmlCode ) ) {
3712 $this->mHtmlCode = wfBCP47( $this->getCode() );
3714 return $this->mHtmlCode;
3718 * @param $code string
3720 public function setCode( $code ) {
3721 $this->mCode = $code;
3722 // Ensure we don't leave an incorrect html code lying around
3723 $this->mHtmlCode = null;
3727 * Get the name of a file for a certain language code
3728 * @param $prefix string Prepend this to the filename
3729 * @param $code string Language code
3730 * @param $suffix string Append this to the filename
3731 * @throws MWException
3732 * @return string $prefix . $mangledCode . $suffix
3734 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3735 // Protect against path traversal
3736 if ( !Language::isValidCode( $code )
3737 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3739 throw new MWException( "Invalid language code \"$code\"" );
3742 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3746 * Get the language code from a file name. Inverse of getFileName()
3747 * @param $filename string $prefix . $languageCode . $suffix
3748 * @param $prefix string Prefix before the language code
3749 * @param $suffix string Suffix after the language code
3750 * @return string Language code, or false if $prefix or $suffix isn't found
3752 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3753 $m = null;
3754 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3755 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3756 if ( !count( $m ) ) {
3757 return false;
3759 return str_replace( '_', '-', strtolower( $m[1] ) );
3763 * @param $code string
3764 * @return string
3766 public static function getMessagesFileName( $code ) {
3767 global $IP;
3768 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3769 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3770 return $file;
3774 * @param $code string
3775 * @return string
3777 public static function getClassFileName( $code ) {
3778 global $IP;
3779 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3783 * Get the first fallback for a given language.
3785 * @param $code string
3787 * @return bool|string
3789 public static function getFallbackFor( $code ) {
3790 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3791 return false;
3792 } else {
3793 $fallbacks = self::getFallbacksFor( $code );
3794 $first = array_shift( $fallbacks );
3795 return $first;
3800 * Get the ordered list of fallback languages.
3802 * @since 1.19
3803 * @param $code string Language code
3804 * @return array
3806 public static function getFallbacksFor( $code ) {
3807 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3808 return array();
3809 } else {
3810 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3811 $v = array_map( 'trim', explode( ',', $v ) );
3812 if ( $v[count( $v ) - 1] !== 'en' ) {
3813 $v[] = 'en';
3815 return $v;
3820 * Get all messages for a given language
3821 * WARNING: this may take a long time. If you just need all message *keys*
3822 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3824 * @param $code string
3826 * @return array
3828 public static function getMessagesFor( $code ) {
3829 return self::getLocalisationCache()->getItem( $code, 'messages' );
3833 * Get a message for a given language
3835 * @param $key string
3836 * @param $code string
3838 * @return string
3840 public static function getMessageFor( $key, $code ) {
3841 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3845 * Get all message keys for a given language. This is a faster alternative to
3846 * array_keys( Language::getMessagesFor( $code ) )
3848 * @since 1.19
3849 * @param $code string Language code
3850 * @return array of message keys (strings)
3852 public static function getMessageKeysFor( $code ) {
3853 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3857 * @param $talk
3858 * @return mixed
3860 function fixVariableInNamespace( $talk ) {
3861 if ( strpos( $talk, '$1' ) === false ) {
3862 return $talk;
3865 global $wgMetaNamespace;
3866 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3868 # Allow grammar transformations
3869 # Allowing full message-style parsing would make simple requests
3870 # such as action=raw much more expensive than they need to be.
3871 # This will hopefully cover most cases.
3872 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3873 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3874 return str_replace( ' ', '_', $talk );
3878 * @param $m string
3879 * @return string
3881 function replaceGrammarInNamespace( $m ) {
3882 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3886 * @throws MWException
3887 * @return array
3889 static function getCaseMaps() {
3890 static $wikiUpperChars, $wikiLowerChars;
3891 if ( isset( $wikiUpperChars ) ) {
3892 return array( $wikiUpperChars, $wikiLowerChars );
3895 wfProfileIn( __METHOD__ );
3896 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3897 if ( $arr === false ) {
3898 throw new MWException(
3899 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3901 $wikiUpperChars = $arr['wikiUpperChars'];
3902 $wikiLowerChars = $arr['wikiLowerChars'];
3903 wfProfileOut( __METHOD__ );
3904 return array( $wikiUpperChars, $wikiLowerChars );
3908 * Decode an expiry (block, protection, etc) which has come from the DB
3910 * @todo FIXME: why are we returnings DBMS-dependent strings???
3912 * @param $expiry String: Database expiry String
3913 * @param $format Bool|Int true to process using language functions, or TS_ constant
3914 * to return the expiry in a given timestamp
3915 * @return String
3916 * @since 1.18
3918 public function formatExpiry( $expiry, $format = true ) {
3919 static $infinity, $infinityMsg;
3920 if ( $infinity === null ) {
3921 $infinityMsg = wfMessage( 'infiniteblock' );
3922 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3925 if ( $expiry == '' || $expiry == $infinity ) {
3926 return $format === true
3927 ? $infinityMsg
3928 : $infinity;
3929 } else {
3930 return $format === true
3931 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3932 : wfTimestamp( $format, $expiry );
3937 * @todo Document
3938 * @param $seconds int|float
3939 * @param $format Array Optional
3940 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3941 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3942 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3943 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3944 * @return string
3946 function formatTimePeriod( $seconds, $format = array() ) {
3947 if ( !is_array( $format ) ) {
3948 $format = array( 'avoid' => $format ); // For backwards compatibility
3950 if ( !isset( $format['avoid'] ) ) {
3951 $format['avoid'] = false;
3953 if ( !isset( $format['noabbrevs' ] ) ) {
3954 $format['noabbrevs'] = false;
3956 $secondsMsg = wfMessage(
3957 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3958 $minutesMsg = wfMessage(
3959 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3960 $hoursMsg = wfMessage(
3961 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
3962 $daysMsg = wfMessage(
3963 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
3965 if ( round( $seconds * 10 ) < 100 ) {
3966 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3967 $s = $secondsMsg->params( $s )->text();
3968 } elseif ( round( $seconds ) < 60 ) {
3969 $s = $this->formatNum( round( $seconds ) );
3970 $s = $secondsMsg->params( $s )->text();
3971 } elseif ( round( $seconds ) < 3600 ) {
3972 $minutes = floor( $seconds / 60 );
3973 $secondsPart = round( fmod( $seconds, 60 ) );
3974 if ( $secondsPart == 60 ) {
3975 $secondsPart = 0;
3976 $minutes++;
3978 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3979 $s .= ' ';
3980 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3981 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3982 $hours = floor( $seconds / 3600 );
3983 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3984 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3985 if ( $secondsPart == 60 ) {
3986 $secondsPart = 0;
3987 $minutes++;
3989 if ( $minutes == 60 ) {
3990 $minutes = 0;
3991 $hours++;
3993 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3994 $s .= ' ';
3995 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3996 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3997 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3999 } else {
4000 $days = floor( $seconds / 86400 );
4001 if ( $format['avoid'] === 'avoidminutes' ) {
4002 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4003 if ( $hours == 24 ) {
4004 $hours = 0;
4005 $days++;
4007 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4008 $s .= ' ';
4009 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4010 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4011 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4012 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4013 if ( $minutes == 60 ) {
4014 $minutes = 0;
4015 $hours++;
4017 if ( $hours == 24 ) {
4018 $hours = 0;
4019 $days++;
4021 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4022 $s .= ' ';
4023 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4024 $s .= ' ';
4025 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4026 } else {
4027 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4028 $s .= ' ';
4029 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4032 return $s;
4036 * Format a bitrate for output, using an appropriate
4037 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4039 * This use base 1000. For base 1024 use formatSize(), for another base
4040 * see formatComputingNumbers()
4042 * @param $bps int
4043 * @return string
4045 function formatBitrate( $bps ) {
4046 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4050 * @param $size int Size of the unit
4051 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4052 * @param $messageKey string Message key to be uesd
4053 * @return string
4055 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4056 if ( $size <= 0 ) {
4057 return str_replace( '$1', $this->formatNum( $size ),
4058 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4061 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4062 $index = 0;
4064 $maxIndex = count( $sizes ) - 1;
4065 while ( $size >= $boundary && $index < $maxIndex ) {
4066 $index++;
4067 $size /= $boundary;
4070 // For small sizes no decimal places necessary
4071 $round = 0;
4072 if ( $index > 1 ) {
4073 // For MB and bigger two decimal places are smarter
4074 $round = 2;
4076 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4078 $size = round( $size, $round );
4079 $text = $this->getMessageFromDB( $msg );
4080 return str_replace( '$1', $this->formatNum( $size ), $text );
4084 * Format a size in bytes for output, using an appropriate
4085 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4087 * This method use base 1024. For base 1000 use formatBitrate(), for
4088 * another base see formatComputingNumbers()
4090 * @param $size int Size to format
4091 * @return string Plain text (not HTML)
4093 function formatSize( $size ) {
4094 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4098 * Make a list item, used by various special pages
4100 * @param $page String Page link
4101 * @param $details String Text between brackets
4102 * @param $oppositedm Boolean Add the direction mark opposite to your
4103 * language, to display text properly
4104 * @return String
4106 function specialList( $page, $details, $oppositedm = true ) {
4107 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4108 $this->getDirMark();
4109 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4110 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4111 return $page . $details;
4115 * Generate (prev x| next x) (20|50|100...) type links for paging
4117 * @param $title Title object to link
4118 * @param $offset Integer offset parameter
4119 * @param $limit Integer limit parameter
4120 * @param $query array|String optional URL query parameter string
4121 * @param $atend Bool optional param for specified if this is the last page
4122 * @return String
4124 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4125 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4127 # Make 'previous' link
4128 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4129 if ( $offset > 0 ) {
4130 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4131 $query, $prev, 'prevn-title', 'mw-prevlink' );
4132 } else {
4133 $plink = htmlspecialchars( $prev );
4136 # Make 'next' link
4137 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4138 if ( $atend ) {
4139 $nlink = htmlspecialchars( $next );
4140 } else {
4141 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4142 $query, $next, 'prevn-title', 'mw-nextlink' );
4145 # Make links to set number of items per page
4146 $numLinks = array();
4147 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4148 $numLinks[] = $this->numLink( $title, $offset, $num,
4149 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4152 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4153 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4157 * Helper function for viewPrevNext() that generates links
4159 * @param $title Title object to link
4160 * @param $offset Integer offset parameter
4161 * @param $limit Integer limit parameter
4162 * @param $query Array extra query parameters
4163 * @param $link String text to use for the link; will be escaped
4164 * @param $tooltipMsg String name of the message to use as tooltip
4165 * @param $class String value of the "class" attribute of the link
4166 * @return String HTML fragment
4168 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4169 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4170 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4171 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4172 'title' => $tooltip, 'class' => $class ), $link );
4176 * Get the conversion rule title, if any.
4178 * @return string
4180 public function getConvRuleTitle() {
4181 return $this->mConverter->getConvRuleTitle();
4185 * Get the compiled plural rules for the language
4186 * @since 1.20
4187 * @return array Associative array with plural form, and plural rule as key-value pairs
4189 public function getCompiledPluralRules() {
4190 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4191 $fallbacks = Language::getFallbacksFor( $this->mCode );
4192 if ( !$pluralRules ) {
4193 foreach ( $fallbacks as $fallbackCode ) {
4194 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4195 if ( $pluralRules ) {
4196 break;
4200 return $pluralRules;
4204 * Get the plural rules for the language
4205 * @since 1.20
4206 * @return array Associative array with plural form, and plural rule as key-value pairs
4208 public function getPluralRules() {
4209 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4210 $fallbacks = Language::getFallbacksFor( $this->mCode );
4211 if ( !$pluralRules ) {
4212 foreach ( $fallbacks as $fallbackCode ) {
4213 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4214 if ( $pluralRules ) {
4215 break;
4219 return $pluralRules;
4223 * Find the plural form matching to the given number
4224 * It return the form index.
4225 * @return int The index of the plural form
4227 private function getPluralForm( $number ) {
4228 $pluralRules = $this->getCompiledPluralRules();
4229 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4230 return $form;