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
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once( dirname( __FILE__
) . '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
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; }
72 * Internationalisation code
78 * @var LanguageConverter
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;
92 * ReplacementArray object caches
94 var $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
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',
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',
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'
161 static public $durationIntervals = array(
162 'millennia' => 31557600000,
163 'centuries' => 3155760000,
164 'decades' => 315576000,
165 'years' => 31557600, // 86400 * 365.25
174 * Get a cached language object for a given language code
175 * @param $code String
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
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 );
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 ) ) {
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 );
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
247 public static function isValidCode( $code ) {
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
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 );
276 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
279 return preg_match( '/^[a-z0-9-]+$/i', $code );
284 * @return String Name of the language class
286 public static function classFromCode( $code ) {
287 if ( $code == 'en' ) {
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 ) {
302 if ( $class === 'Language' ) {
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' ) {
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.
356 * @deprecated in 1.19
358 function getFallbackLanguageCode() {
359 wfDeprecated( __METHOD__
);
360 return self
::getFallbackFor( $this->mCode
);
367 function getFallbackLanguages() {
368 return self
::getFallbacksFor( $this->mCode
);
372 * Exports $wgBookstoreListEn
375 function getBookstoreList() {
376 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
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;
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.
432 function getFormattedNamespaces() {
433 $ns = $this->getNamespaces();
434 foreach ( $ns as $k => $v ) {
435 $ns[$k] = strtr( $v, '_', ' ' );
441 * Get a namespace value by key
443 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
444 * echo $mw_ns; // prints 'MediaWiki'
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
460 * @param $index string
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... )
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
489 function needsGenderDistinction() {
490 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
491 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
492 // $wgExtraGenderNamespaces overrides everything
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
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;
522 function getNamespaceAliases() {
523 if ( is_null( $this->namespaceAliases
) ) {
524 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
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
;
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 ) {
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
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 );
607 return $name; # if it's defined as a language name, show that
609 # otherwise, output the language code
615 * @param $name 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;
629 function getQuickbarSettings() {
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' )
643 function getDatePreferences() {
644 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
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';
670 function getDatePreferenceMigrationMap() {
671 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
678 function getImageFile( $image ) {
679 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
685 function getExtraUserToggles() {
686 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
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
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
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
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' ) );
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' ) {
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];
780 # 'mw' option; default if it's not one of the other two options (all/mwfile)
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
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
802 function getMessageFromDB( $msg ) {
803 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
807 * Get the native language name of $code.
808 * Only if defined in MediaWiki, no other data like CLDR.
809 * @param $code string
811 * @deprecated in 1.20, use fetchLanguageName()
813 function getLanguageName( $code ) {
814 return self
::fetchLanguageName( $code );
821 function getMonthName( $key ) {
822 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
828 function getMonthNamesArray() {
829 $monthNames = array( '' );
830 for ( $i = 1; $i < 13; $i++
) {
831 $monthNames[] = $this->getMonthName( $i );
840 function getMonthNameGen( $key ) {
841 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
848 function getMonthAbbreviation( $key ) {
849 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
855 function getMonthAbbreviationsArray() {
856 $monthNames = array( '' );
857 for ( $i = 1; $i < 13; $i++
) {
858 $monthNames[] = $this->getMonthAbbreviation( $i );
867 function getWeekdayName( $key ) {
868 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
875 function getWeekdayAbbreviation( $key ) {
876 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
883 function getIranianCalendarMonthName( $key ) {
884 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
891 function getHebrewCalendarMonthName( $key ) {
892 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
899 function getHebrewCalendarMonthNameGen( $key ) {
900 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
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
916 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
917 * PHP manual for definitions. There are a number of extensions, which
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
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
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
960 * Backslash escaping is also supported.
962 * Input timestamp is assumed to be pre-normalized to the desired local
965 * @param $format String
966 * @param $ts String: 14-character timestamp
969 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
973 function sprintfDate( $format, $ts ) {
986 for ( $p = 0; $p < strlen( $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];
1005 $rawToggle = !$rawToggle;
1014 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1017 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1018 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1021 $num = substr( $ts, 6, 2 );
1024 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1025 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1028 $num = intval( substr( $ts, 6, 2 ) );
1032 $iranian = self
::tsToIranian( $ts );
1038 $hijri = self
::tsToHijri( $ts );
1044 $hebrew = self
::tsToHebrew( $ts );
1050 $unix = wfTimestamp( TS_UNIX
, $ts );
1052 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1056 $unix = wfTimestamp( TS_UNIX
, $ts );
1058 $w = gmdate( 'w', $unix );
1063 $unix = wfTimestamp( TS_UNIX
, $ts );
1065 $num = gmdate( 'w', $unix );
1069 $unix = wfTimestamp( TS_UNIX
, $ts );
1071 $num = gmdate( 'z', $unix );
1075 $unix = wfTimestamp( TS_UNIX
, $ts );
1077 $num = gmdate( 'W', $unix );
1080 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1084 $iranian = self
::tsToIranian( $ts );
1086 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1090 $hijri = self
::tsToHijri( $ts );
1092 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1096 $hebrew = self
::tsToHebrew( $ts );
1098 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1101 $num = substr( $ts, 4, 2 );
1104 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1107 $num = intval( substr( $ts, 4, 2 ) );
1111 $iranian = self
::tsToIranian( $ts );
1117 $hijri = self
::tsToHijri ( $ts );
1123 $hebrew = self
::tsToHebrew( $ts );
1129 $unix = wfTimestamp( TS_UNIX
, $ts );
1131 $num = gmdate( 't', $unix );
1135 $hebrew = self
::tsToHebrew( $ts );
1141 $unix = wfTimestamp( TS_UNIX
, $ts );
1143 $num = gmdate( 'L', $unix );
1147 $unix = wfTimestamp( TS_UNIX
, $ts );
1149 $num = gmdate( 'o', $unix );
1152 $num = substr( $ts, 0, 4 );
1156 $iranian = self
::tsToIranian( $ts );
1162 $hijri = self
::tsToHijri( $ts );
1168 $hebrew = self
::tsToHebrew( $ts );
1174 $thai = self
::tsToYear( $ts, 'thai' );
1180 $minguo = self
::tsToYear( $ts, 'minguo' );
1186 $tenno = self
::tsToYear( $ts, 'tenno' );
1191 $num = substr( $ts, 2, 2 );
1195 $iranian = self
::tsToIranian( $ts );
1197 $num = substr( $iranian[0], -2 );
1200 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1203 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1206 $h = substr( $ts, 8, 2 );
1207 $num = $h %
12 ?
$h %
12 : 12;
1210 $num = intval( substr( $ts, 8, 2 ) );
1213 $h = substr( $ts, 8, 2 );
1214 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1217 $num = substr( $ts, 8, 2 );
1220 $num = substr( $ts, 10, 2 );
1223 $num = substr( $ts, 12, 2 );
1227 $unix = wfTimestamp( TS_UNIX
, $ts );
1229 $s .= gmdate( 'c', $unix );
1233 $unix = wfTimestamp( TS_UNIX
, $ts );
1235 $s .= gmdate( 'r', $unix );
1239 $unix = wfTimestamp( TS_UNIX
, $ts );
1244 # Backslash escaping
1245 if ( $p < strlen( $format ) - 1 ) {
1246 $s .= $format[++
$p];
1253 if ( $p < strlen( $format ) - 1 ) {
1254 $endQuote = strpos( $format, '"', $p +
1 );
1255 if ( $endQuote === false ) {
1256 # No terminating quote, assume literal "
1259 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1263 # Quote at end of string, assume literal "
1270 if ( $num !== false ) {
1271 if ( $rawToggle ||
$raw ) {
1274 } elseif ( $roman ) {
1275 $s .= Language
::romanNumeral( $num );
1277 } elseif ( $hebrewNum ) {
1278 $s .= self
::hebrewNumeral( $num );
1281 $s .= $this->formatNum( $num, true );
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
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)
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];
1320 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1324 // Days passed in current month
1325 $gDayNo +
= (int)$gd;
1327 $jDayNo = $gDayNo - 79;
1329 $jNp = floor( $jDayNo / 12053 );
1332 $jy = 979 +
33 * $jNp +
4 * floor( $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];
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
1361 private static function tsToHijri( $ts ) {
1362 $year = substr( $ts, 0, 4 );
1363 $month = substr( $ts, 4, 2 );
1364 $day = substr( $ts, 6, 2 );
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 ) +
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
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.
1412 private static function tsToHebrew( $ts ) {
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
1423 if ( $month > 12 ) {
1430 # Calculate day of year from 1 September
1432 for ( $i = 1; $i < $month; $i++
) {
1436 # Check if the year is leap
1437 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1440 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
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
1454 $nextStart = $start;
1458 # Add days since previous year's 1 September
1460 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1464 # Start of the new (previous) year
1465 $start = self
::hebrewYearStart( $hebrewYear );
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 ) ) {
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;
1499 while ( $hebrewMonth <= 12 ) {
1500 # Calculate days in this month
1501 if ( $isLeap && $hebrewMonth == 6 ) {
1502 # Adar in a leap year
1504 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1506 if ( $hebrewDay <= $days ) {
1510 # Subtract the days of Adar I
1511 $hebrewDay -= $days;
1514 if ( $hebrewDay <= $days ) {
1520 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1521 # Cheshvan in a complete year (otherwise as the rule below)
1523 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1524 # Kislev in an incomplete year (otherwise as the rule below)
1527 # Odd months have 30 days, even have 29
1528 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1530 if ( $hebrewDay <= $days ) {
1531 # In the current month
1534 # Subtract the days of the current month
1535 $hebrewDay -= $days;
1536 # Try in the next month
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.
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 );
1560 $Mar = intval( $m );
1566 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1567 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1569 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1571 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1575 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
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' ) ) {
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' ) ) {
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 ) ) ) {
1613 $gy_gannen = $gy - 1868 +
1;
1614 $gy_offset = $gy_gannen;
1615 if ( $gy_gannen == 1 ) {
1618 $gy_offset = '明治' . $gy_offset;
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 ) )
1628 $gy_gannen = $gy - 1912 +
1;
1629 $gy_offset = $gy_gannen;
1630 if ( $gy_gannen == 1 ) {
1633 $gy_offset = '大正' . $gy_offset;
1635 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1636 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1637 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1641 $gy_gannen = $gy - 1926 +
1;
1642 $gy_offset = $gy_gannen;
1643 if ( $gy_gannen == 1 ) {
1646 $gy_offset = '昭和' . $gy_offset;
1649 $gy_gannen = $gy - 1989 +
1;
1650 $gy_offset = $gy_gannen;
1651 if ( $gy_gannen == 1 ) {
1654 $gy_offset = '平成' . $gy_offset;
1660 return array( $gy_offset, $gm, $gd );
1664 * Roman number formatting up to 10000
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 ) {
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;
1694 * Hebrew Gematria number formatting up to 9999
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 ) {
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];
1720 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1721 if ( $pow10 == 1000 ) {
1726 $num = $num %
$pow10;
1728 if ( strlen( $s ) == 2 ) {
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 );
1738 $str = $start . 'ך';
1741 $str = $start . 'ם';
1744 $str = $start . 'ן';
1747 $str = $start . 'ף';
1750 $str = $start . 'ץ';
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)
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' );
1783 # Unrecognized timezone, default to 'Offset' with the stored offset.
1784 $data[0] = 'Offset';
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] );
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;
1805 $minDiff = intval( $data[0] ) * 60;
1809 # No difference ? Return time unchanged
1810 if ( 0 == $minDiff ) {
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.
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();
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
1838 * function timeanddate([...], $format = true) {
1839 * $datePreference = $this->dateFormat($format);
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.
1849 function dateFormat( $usePrefs = true ) {
1852 if ( is_bool( $usePrefs ) ) {
1854 $datePreference = $wgUser->getDatePreference();
1856 $datePreference = (string)User
::getDefaultOption( 'date' );
1859 $datePreference = (string)$usePrefs;
1863 if ( $datePreference == '' ) {
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
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" );
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
1904 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1905 $ts = wfTimestamp( TS_MW
, $ts );
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
1923 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1924 $ts = wfTimestamp( TS_MW
, $ts );
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
1943 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1944 $ts = wfTimestamp( TS_MW
, $ts );
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.
1957 * @param integer $seconds The amount of seconds.
1958 * @param array $chosenIntervals The intervals to enable.
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 ).
1981 * @param integer $seconds The amount of seconds.
1982 * @param array $chosenIntervals The intervals to enable.
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;
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
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' );
2035 $offset = $options['timecorrection'];
2037 $ts = $this->userAdjust( $ts, $offset );
2039 if ( $options['format'] === true ) {
2040 $format = $user->getDatePreference();
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
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
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
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
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
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
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 );
2128 function getAllMessages() {
2129 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
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();
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
2166 function ucwordbreaksCallbackMB( $matches ) {
2167 return mb_strtoupper( $matches[0] );
2171 * @param $matches array
2174 function ucCallback( $matches ) {
2175 list( $wikiUpperChars ) = self
::getCaseMaps();
2176 return strtr( $matches[1], $wikiUpperChars );
2180 * @param $matches array
2183 function lcCallback( $matches ) {
2184 list( , $wikiLowerChars ) = self
::getCaseMaps();
2185 return strtr( $matches[1], $wikiLowerChars );
2189 * @param $matches array
2192 function ucwordsCallbackMB( $matches ) {
2193 return mb_strtoupper( $matches[0] );
2197 * @param $matches array
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
2212 function ucfirst( $str ) {
2214 if ( $o < 96 ) { // if already uppercase...
2216 } elseif ( $o < 128 ) {
2217 return ucfirst( $str ); // use PHP's ucfirst()
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
2232 function uc( $str, $first = false ) {
2233 if ( function_exists( 'mb_strtoupper' ) ) {
2235 if ( $this->isMultibyte( $str ) ) {
2236 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2238 return ucfirst( $str );
2241 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
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' ),
2252 return $first ?
ucfirst( $str ) : strtoupper( $str );
2258 * @param $str string
2259 * @return mixed|string
2261 function lcfirst( $str ) {
2264 return strval( $str );
2265 } elseif ( $o >= 128 ) {
2266 return $this->lc( $str, true );
2267 } elseif ( $o > 96 ) {
2270 $str[0] = strtolower( $str[0] );
2276 * @param $str string
2277 * @param $first bool
2278 * @return mixed|string
2280 function lc( $str, $first = false ) {
2281 if ( function_exists( 'mb_strtolower' ) ) {
2283 if ( $this->isMultibyte( $str ) ) {
2284 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2286 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2289 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
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' ),
2300 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2306 * @param $str string
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(
2328 array( $this, 'ucwordsCallbackMB' ),
2332 return preg_replace_callback(
2334 array( $this, 'ucwordsCallbackWiki' ),
2339 return ucwords( strtolower( $str ) );
2344 * capitalize words at word breaks
2346 * @param $str string
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(
2362 array( $this, 'ucwordbreaksCallbackMB' ),
2366 return preg_replace_callback(
2368 array( $this, 'ucwordsCallbackWiki' ),
2373 return preg_replace_callback(
2374 '/\b([\w\x80-\xff]+)\b/',
2375 array( $this, 'ucwordbreaksCallbackAscii' ),
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.
2396 function caseFold( $s ) {
2397 return $this->uc( $s );
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 );
2414 if ( function_exists( 'mb_check_encoding' ) ) {
2415 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2417 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2418 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2424 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
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
2442 function hasWordBreaks() {
2447 * Some languages such as Chinese require word segmentation,
2448 * Specify such segmentation when overridden in derived class.
2450 * @param $string String
2453 function segmentByWord( $string ) {
2458 * Some languages have special punctuation need to be normalized.
2459 * Make such changes here.
2461 * @param $string 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
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 );
2492 * @param $string string
2493 * @param $pattern string
2496 protected static function insertSpace( $string, $pattern ) {
2497 $string = preg_replace( $pattern, " $1 ", $string );
2498 $string = preg_replace( '/ +/', ' ', $string );
2503 * @param $termsArray 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
2513 * Get the first character of a string.
2518 function firstChar( $s ) {
2521 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2522 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2527 if ( isset( $matches[1] ) ) {
2528 if ( strlen( $matches[1] ) != 3 ) {
2532 // Break down Hangul syllables to grab the first jamo
2533 $code = utf8ToCodepoint( $matches[1] );
2534 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
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";
2563 return "\xe3\x85\x8e";
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.
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' ) {
2589 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2597 function recodeInput( $s ) {
2598 # Take the previous into account.
2599 global $wgEditEncoding;
2600 if ( $wgEditEncoding != '' ) {
2601 $enc = $wgEditEncoding;
2605 if ( $enc == 'UTF-8' ) {
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.
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 );
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
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
2665 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2669 * Return the correct HTML 'dir' attribute value for this language.
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....
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....
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
2710 function getDirMarkEntity( $opposite = false ) {
2711 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2712 return $this->isRTL() ?
'‏' : '‎';
2716 * A hidden direction mark (LRM or RLM), depending on the language direction.
2717 * This function produces them as invisible Unicode characters and
2718 * the output may be hard to read and debug, so it should only be used
2719 * when the output is plain text or can be escaped. When the output is
2720 * HTML, use getDirMarkEntity() instead.
2722 * @param $opposite Boolean Get the direction mark opposite to your language
2725 function getDirMark( $opposite = false ) {
2726 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2727 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2728 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2729 return $this->isRTL() ?
$rlm : $lrm;
2735 function capitalizeAllNouns() {
2736 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2740 * An arrow, depending on the language direction.
2742 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2745 function getArrow( $direction = 'forwards' ) {
2746 switch ( $direction ) {
2748 return $this->isRTL() ?
'←' : '→';
2750 return $this->isRTL() ?
'→' : '←';
2763 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2767 function linkPrefixExtension() {
2768 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2774 function getMagicWords() {
2775 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2778 protected function doMagicHook() {
2779 if ( $this->mMagicHookDone
) {
2782 $this->mMagicHookDone
= true;
2783 wfProfileIn( 'LanguageGetMagic' );
2784 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2785 wfProfileOut( 'LanguageGetMagic' );
2789 * Fill a MagicWord object with data from here
2793 function getMagic( $mw ) {
2794 $this->doMagicHook();
2796 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2797 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2799 $magicWords = $this->getMagicWords();
2800 if ( isset( $magicWords[$mw->mId
] ) ) {
2801 $rawEntry = $magicWords[$mw->mId
];
2807 if ( !is_array( $rawEntry ) ) {
2808 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2810 $mw->mCaseSensitive
= $rawEntry[0];
2811 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2816 * Add magic words to the extension array
2818 * @param $newWords array
2820 function addMagicWordsByLang( $newWords ) {
2821 $fallbackChain = $this->getFallbackLanguages();
2822 $fallbackChain = array_reverse( $fallbackChain );
2823 foreach ( $fallbackChain as $code ) {
2824 if ( isset( $newWords[$code] ) ) {
2825 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2831 * Get special page names, as an associative array
2832 * case folded alias => real name
2834 function getSpecialPageAliases() {
2835 // Cache aliases because it may be slow to load them
2836 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2838 $this->mExtendedSpecialPageAliases
=
2839 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2840 wfRunHooks( 'LanguageGetSpecialPageAliases',
2841 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2844 return $this->mExtendedSpecialPageAliases
;
2848 * Italic is unsuitable for some languages
2850 * @param $text String: the text to be emphasized.
2853 function emphasize( $text ) {
2854 return "<em>$text</em>";
2858 * Normally we output all numbers in plain en_US style, that is
2859 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2860 * point twohundredthirtyfive. However this is not suitable for all
2861 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2862 * Icelandic just want to use commas instead of dots, and dots instead
2863 * of commas like "293.291,235".
2865 * An example of this function being called:
2867 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2870 * See LanguageGu.php for the Gujarati implementation and
2871 * $separatorTransformTable on MessageIs.php for
2872 * the , => . and . => , implementation.
2874 * @todo check if it's viable to use localeconv() for the decimal
2876 * @param $number Mixed: the string to be formatted, should be an integer
2877 * or a floating point number.
2878 * @param $nocommafy Bool: set to true for special numbers like dates
2881 public function formatNum( $number, $nocommafy = false ) {
2882 global $wgTranslateNumerals;
2883 if ( !$nocommafy ) {
2884 $number = $this->commafy( $number );
2885 $s = $this->separatorTransformTable();
2887 $number = strtr( $number, $s );
2891 if ( $wgTranslateNumerals ) {
2892 $s = $this->digitTransformTable();
2894 $number = strtr( $number, $s );
2902 * @param $number string
2905 function parseFormattedNumber( $number ) {
2906 $s = $this->digitTransformTable();
2908 $number = strtr( $number, array_flip( $s ) );
2911 $s = $this->separatorTransformTable();
2913 $number = strtr( $number, array_flip( $s ) );
2916 $number = strtr( $number, array( ',' => '' ) );
2921 * Adds commas to a given number
2926 function commafy( $_ ) {
2927 $digitGroupingPattern = $this->digitGroupingPattern();
2928 if ( $_ === null ) {
2932 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2933 // default grouping is at thousands, use the same for ###,###,### pattern too.
2934 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2936 // Ref: http://cldr.unicode.org/translation/number-patterns
2938 if ( intval( $_ ) < 0 ) {
2939 // For negative numbers apply the algorithm like positive number and add sign.
2941 $_ = substr( $_, 1 );
2943 $numberpart = array();
2944 $decimalpart = array();
2945 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2946 preg_match( "/\d+/", $_, $numberpart );
2947 preg_match( "/\.\d*/", $_, $decimalpart );
2948 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2949 if ( $groupedNumber === $_ ) {
2950 // the string does not have any number part. Eg: .12345
2951 return $sign . $groupedNumber;
2953 $start = $end = strlen( $numberpart[0] );
2954 while ( $start > 0 ) {
2955 $match = $matches[0][$numMatches -1] ;
2956 $matchLen = strlen( $match );
2957 $start = $end - $matchLen;
2961 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2963 if ( $numMatches > 1 ) {
2964 // use the last pattern for the rest of the number
2968 $groupedNumber = "," . $groupedNumber;
2971 return $sign . $groupedNumber;
2977 function digitGroupingPattern() {
2978 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2984 function digitTransformTable() {
2985 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2991 function separatorTransformTable() {
2992 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2996 * Take a list of strings and build a locale-friendly comma-separated
2997 * list, using the local comma-separator message.
2998 * The last two strings are chained with an "and".
3003 function listToText( array $l ) {
3005 $m = count( $l ) - 1;
3007 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3009 for ( $i = $m; $i >= 0; $i-- ) {
3012 } elseif ( $i == $m - 1 ) {
3013 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3015 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3023 * Take a list of strings and build a locale-friendly comma-separated
3024 * list, using the local comma-separator message.
3025 * @param $list array of strings to put in a comma list
3028 function commaList( array $list ) {
3032 array( 'parsemag', 'escapenoentities', 'language' => $this )
3039 * Take a list of strings and build a locale-friendly semicolon-separated
3040 * list, using the local semicolon-separator message.
3041 * @param $list array of strings to put in a semicolon list
3044 function semicolonList( array $list ) {
3047 'semicolon-separator',
3048 array( 'parsemag', 'escapenoentities', 'language' => $this )
3055 * Same as commaList, but separate it with the pipe instead.
3056 * @param $list array of strings to put in a pipe list
3059 function pipeList( array $list ) {
3063 array( 'escapenoentities', 'language' => $this )
3070 * Truncate a string to a specified length in bytes, appending an optional
3071 * string (e.g. for ellipses)
3073 * The database offers limited byte lengths for some columns in the database;
3074 * multi-byte character sets mean we need to ensure that only whole characters
3075 * are included, otherwise broken characters can be passed to the user
3077 * If $length is negative, the string will be truncated from the beginning
3079 * @param $string String to truncate
3080 * @param $length Int: maximum length (including ellipses)
3081 * @param $ellipsis String to append to the truncated text
3082 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3083 * $adjustLength was introduced in 1.18, before that behaved as if false.
3086 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3087 # Use the localized ellipsis character
3088 if ( $ellipsis == '...' ) {
3089 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3091 # Check if there is no need to truncate
3092 if ( $length == 0 ) {
3093 return $ellipsis; // convention
3094 } elseif ( strlen( $string ) <= abs( $length ) ) {
3095 return $string; // no need to truncate
3097 $stringOriginal = $string;
3098 # If ellipsis length is >= $length then we can't apply $adjustLength
3099 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3100 $string = $ellipsis; // this can be slightly unexpected
3101 # Otherwise, truncate and add ellipsis...
3103 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3104 if ( $length > 0 ) {
3105 $length -= $eLength;
3106 $string = substr( $string, 0, $length ); // xyz...
3107 $string = $this->removeBadCharLast( $string );
3108 $string = $string . $ellipsis;
3110 $length +
= $eLength;
3111 $string = substr( $string, $length ); // ...xyz
3112 $string = $this->removeBadCharFirst( $string );
3113 $string = $ellipsis . $string;
3116 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3117 # This check is *not* redundant if $adjustLength, due to the single case where
3118 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3119 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3122 return $stringOriginal;
3127 * Remove bytes that represent an incomplete Unicode character
3128 * at the end of string (e.g. bytes of the char are missing)
3130 * @param $string String
3133 protected function removeBadCharLast( $string ) {
3134 if ( $string != '' ) {
3135 $char = ord( $string[strlen( $string ) - 1] );
3137 if ( $char >= 0xc0 ) {
3138 # We got the first byte only of a multibyte char; remove it.
3139 $string = substr( $string, 0, -1 );
3140 } elseif ( $char >= 0x80 &&
3141 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3142 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3144 # We chopped in the middle of a character; remove it
3152 * Remove bytes that represent an incomplete Unicode character
3153 * at the start of string (e.g. bytes of the char are missing)
3155 * @param $string String
3158 protected function removeBadCharFirst( $string ) {
3159 if ( $string != '' ) {
3160 $char = ord( $string[0] );
3161 if ( $char >= 0x80 && $char < 0xc0 ) {
3162 # We chopped in the middle of a character; remove the whole thing
3163 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3170 * Truncate a string of valid HTML to a specified length in bytes,
3171 * appending an optional string (e.g. for ellipses), and return valid HTML
3173 * This is only intended for styled/linked text, such as HTML with
3174 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3175 * Also, this will not detect things like "display:none" CSS.
3177 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3179 * @param string $text HTML string to truncate
3180 * @param int $length (zero/positive) Maximum length (including ellipses)
3181 * @param string $ellipsis String to append to the truncated text
3184 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3185 # Use the localized ellipsis character
3186 if ( $ellipsis == '...' ) {
3187 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3189 # Check if there is clearly no need to truncate
3190 if ( $length <= 0 ) {
3191 return $ellipsis; // no text shown, nothing to format (convention)
3192 } elseif ( strlen( $text ) <= $length ) {
3193 return $text; // string short enough even *with* HTML (short-circuit)
3196 $dispLen = 0; // innerHTML legth so far
3197 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3198 $tagType = 0; // 0-open, 1-close
3199 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3200 $entityState = 0; // 0-not entity, 1-entity
3201 $tag = $ret = ''; // accumulated tag name, accumulated result string
3202 $openTags = array(); // open tag stack
3203 $maybeState = null; // possible truncation state
3205 $textLen = strlen( $text );
3206 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3207 for ( $pos = 0; true; ++
$pos ) {
3208 # Consider truncation once the display length has reached the maximim.
3209 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3210 # Check that we're not in the middle of a bracket/entity...
3211 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3212 if ( !$testingEllipsis ) {
3213 $testingEllipsis = true;
3214 # Save where we are; we will truncate here unless there turn out to
3215 # be so few remaining characters that truncation is not necessary.
3216 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3217 $maybeState = array( $ret, $openTags ); // save state
3219 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3220 # String in fact does need truncation, the truncation point was OK.
3221 list( $ret, $openTags ) = $maybeState; // reload state
3222 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3223 $ret .= $ellipsis; // add ellipsis
3227 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3229 # Read the next char...
3231 $lastCh = $pos ?
$text[$pos - 1] : '';
3232 $ret .= $ch; // add to result string
3234 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3235 $entityState = 0; // for bad HTML
3236 $bracketState = 1; // tag started (checking for backslash)
3237 } elseif ( $ch == '>' ) {
3238 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3239 $entityState = 0; // for bad HTML
3240 $bracketState = 0; // out of brackets
3241 } elseif ( $bracketState == 1 ) {
3243 $tagType = 1; // close tag (e.g. "</span>")
3245 $tagType = 0; // open tag (e.g. "<span>")
3248 $bracketState = 2; // building tag name
3249 } elseif ( $bracketState == 2 ) {
3253 // Name found (e.g. "<a href=..."), add on tag attributes...
3254 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3256 } elseif ( $bracketState == 0 ) {
3257 if ( $entityState ) {
3260 $dispLen++
; // entity is one displayed char
3263 if ( $neLength == 0 && !$maybeState ) {
3264 // Save state without $ch. We want to *hit* the first
3265 // display char (to get tags) but not *use* it if truncating.
3266 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3269 $entityState = 1; // entity found, (e.g. " ")
3271 $dispLen++
; // this char is displayed
3272 // Add the next $max display text chars after this in one swoop...
3273 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3274 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3275 $dispLen +
= $skipped;
3281 // Close the last tag if left unclosed by bad HTML
3282 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3283 while ( count( $openTags ) > 0 ) {
3284 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3290 * truncateHtml() helper function
3291 * like strcspn() but adds the skipped chars to $ret
3300 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3301 if ( $len === null ) {
3302 $len = -1; // -1 means "no limit" for strcspn
3303 } elseif ( $len < 0 ) {
3307 if ( $start < strlen( $text ) ) {
3308 $skipCount = strcspn( $text, $search, $start, $len );
3309 $ret .= substr( $text, $start, $skipCount );
3315 * truncateHtml() helper function
3316 * (a) push or pop $tag from $openTags as needed
3317 * (b) clear $tag value
3318 * @param &$tag string Current HTML tag name we are looking at
3319 * @param $tagType int (0-open tag, 1-close tag)
3320 * @param $lastCh string Character before the '>' that ended this tag
3321 * @param &$openTags array Open tag stack (not accounting for $tag)
3323 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3324 $tag = ltrim( $tag );
3326 if ( $tagType == 0 && $lastCh != '/' ) {
3327 $openTags[] = $tag; // tag opened (didn't close itself)
3328 } elseif ( $tagType == 1 ) {
3329 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3330 array_pop( $openTags ); // tag closed
3338 * Grammatical transformations, needed for inflected languages
3339 * Invoked by putting {{grammar:case|word}} in a message
3341 * @param $word string
3342 * @param $case string
3345 function convertGrammar( $word, $case ) {
3346 global $wgGrammarForms;
3347 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3348 return $wgGrammarForms[$this->getCode()][$case][$word];
3353 * Get the grammar forms for the content language
3354 * @return array of grammar forms
3357 function getGrammarForms() {
3358 global $wgGrammarForms;
3359 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3360 return $wgGrammarForms[$this->getCode()];
3365 * Provides an alternative text depending on specified gender.
3366 * Usage {{gender:username|masculine|feminine|neutral}}.
3367 * username is optional, in which case the gender of current user is used,
3368 * but only in (some) interface messages; otherwise default gender is used.
3370 * If no forms are given, an empty string is returned. If only one form is
3371 * given, it will be returned unconditionally. These details are implied by
3372 * the caller and cannot be overridden in subclasses.
3374 * If more than one form is given, the default is to use the neutral one
3375 * if it is specified, and to use the masculine one otherwise. These
3376 * details can be overridden in subclasses.
3378 * @param $gender string
3379 * @param $forms array
3383 function gender( $gender, $forms ) {
3384 if ( !count( $forms ) ) {
3387 $forms = $this->preConvertPlural( $forms, 2 );
3388 if ( $gender === 'male' ) {
3391 if ( $gender === 'female' ) {
3394 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3398 * Plural form transformations, needed for some languages.
3399 * For example, there are 3 form of plural in Russian and Polish,
3400 * depending on "count mod 10". See [[w:Plural]]
3401 * For English it is pretty simple.
3403 * Invoked by putting {{plural:count|wordform1|wordform2}}
3404 * or {{plural:count|wordform1|wordform2|wordform3}}
3406 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3408 * @param $count Integer: non-localized number
3409 * @param $forms Array: different plural forms
3410 * @return string Correct form of plural for $count in this language
3412 function convertPlural( $count, $forms ) {
3413 if ( !count( $forms ) ) {
3416 $forms = $this->preConvertPlural( $forms, 2 );
3418 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3422 * Checks that convertPlural was given an array and pads it to requested
3423 * amount of forms by copying the last one.
3425 * @param $count Integer: How many forms should there be at least
3426 * @param $forms Array of forms given to convertPlural
3427 * @return array Padded array of forms or an exception if not an array
3429 protected function preConvertPlural( /* Array */ $forms, $count ) {
3430 while ( count( $forms ) < $count ) {
3431 $forms[] = $forms[count( $forms ) - 1];
3437 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3438 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3439 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3440 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3443 * @param $str String: the validated block duration in English
3444 * @return string Somehow translated block duration
3445 * @see LanguageFi.php for example implementation
3447 function translateBlockExpiry( $str ) {
3448 $duration = SpecialBlock
::getSuggestedDurations( $this );
3449 foreach ( $duration as $show => $value ) {
3450 if ( strcmp( $str, $value ) == 0 ) {
3451 return htmlspecialchars( trim( $show ) );
3455 // Since usually only infinite or indefinite is only on list, so try
3456 // equivalents if still here.
3457 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3458 if ( in_array( $str, $indefs ) ) {
3459 foreach ( $indefs as $val ) {
3460 $show = array_search( $val, $duration, true );
3461 if ( $show !== false ) {
3462 return htmlspecialchars( trim( $show ) );
3466 // If all else fails, return the original string.
3471 * languages like Chinese need to be segmented in order for the diff
3474 * @param $text String
3477 public function segmentForDiff( $text ) {
3482 * and unsegment to show the result
3484 * @param $text String
3487 public function unsegmentForDiff( $text ) {
3492 * Return the LanguageConverter used in the Language
3495 * @return LanguageConverter
3497 public function getConverter() {
3498 return $this->mConverter
;
3502 * convert text to all supported variants
3504 * @param $text string
3507 public function autoConvertToAllVariants( $text ) {
3508 return $this->mConverter
->autoConvertToAllVariants( $text );
3512 * convert text to different variants of a language.
3514 * @param $text string
3517 public function convert( $text ) {
3518 return $this->mConverter
->convert( $text );
3522 * Convert a Title object to a string in the preferred variant
3524 * @param $title Title
3527 public function convertTitle( $title ) {
3528 return $this->mConverter
->convertTitle( $title );
3532 * Check if this is a language with variants
3536 public function hasVariants() {
3537 return sizeof( $this->getVariants() ) > 1;
3541 * Check if the language has the specific variant
3544 * @param $variant string
3547 public function hasVariant( $variant ) {
3548 return (bool)$this->mConverter
->validateVariant( $variant );
3552 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3554 * @param $text string
3557 public function armourMath( $text ) {
3558 return $this->mConverter
->armourMath( $text );
3562 * Perform output conversion on a string, and encode for safe HTML output.
3563 * @param $text String text to be converted
3564 * @param $isTitle Bool whether this conversion is for the article title
3566 * @todo this should get integrated somewhere sane
3568 public function convertHtml( $text, $isTitle = false ) {
3569 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3573 * @param $key string
3576 public function convertCategoryKey( $key ) {
3577 return $this->mConverter
->convertCategoryKey( $key );
3581 * Get the list of variants supported by this language
3582 * see sample implementation in LanguageZh.php
3584 * @return array an array of language codes
3586 public function getVariants() {
3587 return $this->mConverter
->getVariants();
3593 public function getPreferredVariant() {
3594 return $this->mConverter
->getPreferredVariant();
3600 public function getDefaultVariant() {
3601 return $this->mConverter
->getDefaultVariant();
3607 public function getURLVariant() {
3608 return $this->mConverter
->getURLVariant();
3612 * If a language supports multiple variants, it is
3613 * possible that non-existing link in one variant
3614 * actually exists in another variant. this function
3615 * tries to find it. See e.g. LanguageZh.php
3617 * @param $link String: the name of the link
3618 * @param $nt Mixed: the title object of the link
3619 * @param $ignoreOtherCond Boolean: to disable other conditions when
3620 * we need to transclude a template or update a category's link
3621 * @return null the input parameters may be modified upon return
3623 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3624 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3628 * If a language supports multiple variants, converts text
3629 * into an array of all possible variants of the text:
3630 * 'variant' => text in that variant
3632 * @deprecated since 1.17 Use autoConvertToAllVariants()
3634 * @param $text string
3638 public function convertLinkToAllVariants( $text ) {
3639 return $this->mConverter
->convertLinkToAllVariants( $text );
3643 * returns language specific options used by User::getPageRenderHash()
3644 * for example, the preferred language variant
3648 function getExtraHashOptions() {
3649 return $this->mConverter
->getExtraHashOptions();
3653 * For languages that support multiple variants, the title of an
3654 * article may be displayed differently in different variants. this
3655 * function returns the apporiate title defined in the body of the article.
3659 public function getParsedTitle() {
3660 return $this->mConverter
->getParsedTitle();
3664 * Enclose a string with the "no conversion" tag. This is used by
3665 * various functions in the Parser
3667 * @param $text String: text to be tagged for no conversion
3668 * @param $noParse bool
3669 * @return string the tagged text
3671 public function markNoConversion( $text, $noParse = false ) {
3672 return $this->mConverter
->markNoConversion( $text, $noParse );
3676 * A regular expression to match legal word-trailing characters
3677 * which should be merged onto a link of the form [[foo]]bar.
3681 public function linkTrail() {
3682 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3688 function getLangObj() {
3693 * Get the RFC 3066 code for this language object
3695 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3696 * htmlspecialchars() or similar
3700 public function getCode() {
3701 return $this->mCode
;
3705 * Get the code in Bcp47 format which we can use
3706 * inside of html lang="" tags.
3708 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3709 * htmlspecialchars() or similar.
3714 public function getHtmlCode() {
3715 if ( is_null( $this->mHtmlCode
) ) {
3716 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3718 return $this->mHtmlCode
;
3722 * @param $code string
3724 public function setCode( $code ) {
3725 $this->mCode
= $code;
3726 // Ensure we don't leave an incorrect html code lying around
3727 $this->mHtmlCode
= null;
3731 * Get the name of a file for a certain language code
3732 * @param $prefix string Prepend this to the filename
3733 * @param $code string Language code
3734 * @param $suffix string Append this to the filename
3735 * @throws MWException
3736 * @return string $prefix . $mangledCode . $suffix
3738 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3739 // Protect against path traversal
3740 if ( !Language
::isValidCode( $code )
3741 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3743 throw new MWException( "Invalid language code \"$code\"" );
3746 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3750 * Get the language code from a file name. Inverse of getFileName()
3751 * @param $filename string $prefix . $languageCode . $suffix
3752 * @param $prefix string Prefix before the language code
3753 * @param $suffix string Suffix after the language code
3754 * @return string Language code, or false if $prefix or $suffix isn't found
3756 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3758 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3759 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3760 if ( !count( $m ) ) {
3763 return str_replace( '_', '-', strtolower( $m[1] ) );
3767 * @param $code string
3770 public static function getMessagesFileName( $code ) {
3772 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3773 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3778 * @param $code string
3781 public static function getClassFileName( $code ) {
3783 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3787 * Get the first fallback for a given language.
3789 * @param $code string
3791 * @return bool|string
3793 public static function getFallbackFor( $code ) {
3794 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3797 $fallbacks = self
::getFallbacksFor( $code );
3798 $first = array_shift( $fallbacks );
3804 * Get the ordered list of fallback languages.
3807 * @param $code string Language code
3810 public static function getFallbacksFor( $code ) {
3811 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3814 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3815 $v = array_map( 'trim', explode( ',', $v ) );
3816 if ( $v[count( $v ) - 1] !== 'en' ) {
3824 * Get all messages for a given language
3825 * WARNING: this may take a long time. If you just need all message *keys*
3826 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3828 * @param $code string
3832 public static function getMessagesFor( $code ) {
3833 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3837 * Get a message for a given language
3839 * @param $key string
3840 * @param $code string
3844 public static function getMessageFor( $key, $code ) {
3845 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3849 * Get all message keys for a given language. This is a faster alternative to
3850 * array_keys( Language::getMessagesFor( $code ) )
3853 * @param $code string Language code
3854 * @return array of message keys (strings)
3856 public static function getMessageKeysFor( $code ) {
3857 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3864 function fixVariableInNamespace( $talk ) {
3865 if ( strpos( $talk, '$1' ) === false ) {
3869 global $wgMetaNamespace;
3870 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3872 # Allow grammar transformations
3873 # Allowing full message-style parsing would make simple requests
3874 # such as action=raw much more expensive than they need to be.
3875 # This will hopefully cover most cases.
3876 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3877 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3878 return str_replace( ' ', '_', $talk );
3885 function replaceGrammarInNamespace( $m ) {
3886 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3890 * @throws MWException
3893 static function getCaseMaps() {
3894 static $wikiUpperChars, $wikiLowerChars;
3895 if ( isset( $wikiUpperChars ) ) {
3896 return array( $wikiUpperChars, $wikiLowerChars );
3899 wfProfileIn( __METHOD__
);
3900 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3901 if ( $arr === false ) {
3902 throw new MWException(
3903 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3905 $wikiUpperChars = $arr['wikiUpperChars'];
3906 $wikiLowerChars = $arr['wikiLowerChars'];
3907 wfProfileOut( __METHOD__
);
3908 return array( $wikiUpperChars, $wikiLowerChars );
3912 * Decode an expiry (block, protection, etc) which has come from the DB
3914 * @todo FIXME: why are we returnings DBMS-dependent strings???
3916 * @param $expiry String: Database expiry String
3917 * @param $format Bool|Int true to process using language functions, or TS_ constant
3918 * to return the expiry in a given timestamp
3922 public function formatExpiry( $expiry, $format = true ) {
3923 static $infinity, $infinityMsg;
3924 if ( $infinity === null ) {
3925 $infinityMsg = wfMessage( 'infiniteblock' );
3926 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3929 if ( $expiry == '' ||
$expiry == $infinity ) {
3930 return $format === true
3934 return $format === true
3935 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3936 : wfTimestamp( $format, $expiry );
3942 * @param $seconds int|float
3943 * @param $format Array Optional
3944 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3945 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3946 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3947 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3950 function formatTimePeriod( $seconds, $format = array() ) {
3951 if ( !is_array( $format ) ) {
3952 $format = array( 'avoid' => $format ); // For backwards compatibility
3954 if ( !isset( $format['avoid'] ) ) {
3955 $format['avoid'] = false;
3957 if ( !isset( $format['noabbrevs' ] ) ) {
3958 $format['noabbrevs'] = false;
3960 $secondsMsg = wfMessage(
3961 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3962 $minutesMsg = wfMessage(
3963 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3964 $hoursMsg = wfMessage(
3965 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3966 $daysMsg = wfMessage(
3967 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3969 if ( round( $seconds * 10 ) < 100 ) {
3970 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3971 $s = $secondsMsg->params( $s )->text();
3972 } elseif ( round( $seconds ) < 60 ) {
3973 $s = $this->formatNum( round( $seconds ) );
3974 $s = $secondsMsg->params( $s )->text();
3975 } elseif ( round( $seconds ) < 3600 ) {
3976 $minutes = floor( $seconds / 60 );
3977 $secondsPart = round( fmod( $seconds, 60 ) );
3978 if ( $secondsPart == 60 ) {
3982 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3984 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3985 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3986 $hours = floor( $seconds / 3600 );
3987 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3988 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3989 if ( $secondsPart == 60 ) {
3993 if ( $minutes == 60 ) {
3997 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3999 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4000 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4001 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4004 $days = floor( $seconds / 86400 );
4005 if ( $format['avoid'] === 'avoidminutes' ) {
4006 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4007 if ( $hours == 24 ) {
4011 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4013 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4014 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4015 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4016 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4017 if ( $minutes == 60 ) {
4021 if ( $hours == 24 ) {
4025 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4027 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4029 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4031 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4033 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4040 * Format a bitrate for output, using an appropriate
4041 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4043 * This use base 1000. For base 1024 use formatSize(), for another base
4044 * see formatComputingNumbers()
4049 function formatBitrate( $bps ) {
4050 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4054 * @param $size int Size of the unit
4055 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4056 * @param $messageKey string Message key to be uesd
4059 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4061 return str_replace( '$1', $this->formatNum( $size ),
4062 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4065 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4068 $maxIndex = count( $sizes ) - 1;
4069 while ( $size >= $boundary && $index < $maxIndex ) {
4074 // For small sizes no decimal places necessary
4077 // For MB and bigger two decimal places are smarter
4080 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4082 $size = round( $size, $round );
4083 $text = $this->getMessageFromDB( $msg );
4084 return str_replace( '$1', $this->formatNum( $size ), $text );
4088 * Format a size in bytes for output, using an appropriate
4089 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4091 * This method use base 1024. For base 1000 use formatBitrate(), for
4092 * another base see formatComputingNumbers()
4094 * @param $size int Size to format
4095 * @return string Plain text (not HTML)
4097 function formatSize( $size ) {
4098 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4102 * Make a list item, used by various special pages
4104 * @param $page String Page link
4105 * @param $details String Text between brackets
4106 * @param $oppositedm Boolean Add the direction mark opposite to your
4107 * language, to display text properly
4110 function specialList( $page, $details, $oppositedm = true ) {
4111 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4112 $this->getDirMark();
4113 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4114 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4115 return $page . $details;
4119 * Generate (prev x| next x) (20|50|100...) type links for paging
4121 * @param $title Title object to link
4122 * @param $offset Integer offset parameter
4123 * @param $limit Integer limit parameter
4124 * @param $query array|String optional URL query parameter string
4125 * @param $atend Bool optional param for specified if this is the last page
4128 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4129 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4131 # Make 'previous' link
4132 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4133 if ( $offset > 0 ) {
4134 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4135 $query, $prev, 'prevn-title', 'mw-prevlink' );
4137 $plink = htmlspecialchars( $prev );
4141 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4143 $nlink = htmlspecialchars( $next );
4145 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4146 $query, $next, 'prevn-title', 'mw-nextlink' );
4149 # Make links to set number of items per page
4150 $numLinks = array();
4151 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4152 $numLinks[] = $this->numLink( $title, $offset, $num,
4153 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4156 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4157 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4161 * Helper function for viewPrevNext() that generates links
4163 * @param $title Title object to link
4164 * @param $offset Integer offset parameter
4165 * @param $limit Integer limit parameter
4166 * @param $query Array extra query parameters
4167 * @param $link String text to use for the link; will be escaped
4168 * @param $tooltipMsg String name of the message to use as tooltip
4169 * @param $class String value of the "class" attribute of the link
4170 * @return String HTML fragment
4172 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4173 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4174 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4175 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4176 'title' => $tooltip, 'class' => $class ), $link );
4180 * Get the conversion rule title, if any.
4184 public function getConvRuleTitle() {
4185 return $this->mConverter
->getConvRuleTitle();