3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
37 function __construct( $langobj ) { $this->mLang
= $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang
->getCode() ); }
43 function getPreferredVariant() { return $this->mLang
->getCode(); }
44 function getDefaultVariant() { return $this->mLang
->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
57 * Internationalisation code
63 * @var LanguageConverter
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
77 * ReplacementArray object caches
79 var $transformData = array();
82 * @var LocalisationCache
84 static public $dataCache;
86 static public $mLangObjCache = array();
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
146 static public $durationIntervals = array(
147 'millennia' => 31557600000,
148 'centuries' => 3155760000,
149 'decades' => 315576000,
150 'years' => 31557600, // 86400 * 365.25
159 * Get a cached language object for a given language code
160 * @param $code String
163 static function factory( $code ) {
164 if ( !isset( self
::$mLangObjCache[$code] ) ) {
165 if ( count( self
::$mLangObjCache ) > 10 ) {
166 // Don't keep a billion objects around, that's stupid.
167 self
::$mLangObjCache = array();
169 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
171 return self
::$mLangObjCache[$code];
175 * Create a language object for a given language code
176 * @param $code String
177 * @throws MWException
180 protected static function newFromCode( $code ) {
181 // Protect against path traversal below
182 if ( !Language
::isValidCode( $code )
183 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
185 throw new MWException( "Invalid language code \"$code\"" );
188 if ( !Language
::isValidBuiltInCode( $code ) ) {
189 // It's not possible to customise this code with class files, so
190 // just return a Language object. This is to support uselang= hacks.
191 $lang = new Language
;
192 $lang->setCode( $code );
196 // Check if there is a language class for the code
197 $class = self
::classFromCode( $code );
198 self
::preloadLanguageClass( $class );
199 if ( MWInit
::classExists( $class ) ) {
204 // Keep trying the fallback list until we find an existing class
205 $fallbacks = Language
::getFallbacksFor( $code );
206 foreach ( $fallbacks as $fallbackCode ) {
207 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
208 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
211 $class = self
::classFromCode( $fallbackCode );
212 self
::preloadLanguageClass( $class );
213 if ( MWInit
::classExists( $class ) ) {
214 $lang = Language
::newFromCode( $fallbackCode );
215 $lang->setCode( $code );
220 throw new MWException( "Invalid fallback sequence for language '$code'" );
224 * Returns true if a language code string is of a valid form, whether or
225 * not it exists. This includes codes which are used solely for
226 * customisation via the MediaWiki namespace.
228 * @param $code string
232 public static function isValidCode( $code ) {
234 strcspn( $code, ":/\\\000" ) === strlen( $code )
235 && !preg_match( Title
::getTitleInvalidRegex(), $code );
239 * Returns true if a language code is of a valid form for the purposes of
240 * internal customisation of MediaWiki, via Messages*.php.
242 * @param $code string
247 public static function isValidBuiltInCode( $code ) {
249 if( !is_string($code) ) {
250 $type = gettype( $code );
251 if( $type === 'object' ) {
252 $addmsg = " of class " . get_class( $code );
256 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
259 return preg_match( '/^[a-z0-9-]+$/i', $code );
264 * @return String Name of the language class
266 public static function classFromCode( $code ) {
267 if ( $code == 'en' ) {
270 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
275 * Includes language class files
277 * @param $class string Name of the language class
279 public static function preloadLanguageClass( $class ) {
282 if ( $class === 'Language' ) {
286 if ( !defined( 'MW_COMPILED' ) ) {
287 // Preload base classes to work around APC/PHP5 bug
288 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
289 include_once( "$IP/languages/classes/$class.deps.php" );
291 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
292 include_once( "$IP/languages/classes/$class.php" );
298 * Get the LocalisationCache instance
300 * @return LocalisationCache
302 public static function getLocalisationCache() {
303 if ( is_null( self
::$dataCache ) ) {
304 global $wgLocalisationCacheConf;
305 $class = $wgLocalisationCacheConf['class'];
306 self
::$dataCache = new $class( $wgLocalisationCacheConf );
308 return self
::$dataCache;
311 function __construct() {
312 $this->mConverter
= new FakeConverter( $this );
313 // Set the code to the name of the descendant
314 if ( get_class( $this ) == 'Language' ) {
317 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
319 self
::getLocalisationCache();
323 * Reduce memory usage
325 function __destruct() {
326 foreach ( $this as $name => $value ) {
327 unset( $this->$name );
332 * Hook which will be called if this is the content language.
333 * Descendants can use this to register hook functions or modify globals
335 function initContLang() { }
338 * Same as getFallbacksFor for current language.
340 * @deprecated in 1.19
342 function getFallbackLanguageCode() {
343 wfDeprecated( __METHOD__
);
344 return self
::getFallbackFor( $this->mCode
);
351 function getFallbackLanguages() {
352 return self
::getFallbacksFor( $this->mCode
);
356 * Exports $wgBookstoreListEn
359 function getBookstoreList() {
360 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
366 public function getNamespaces() {
367 if ( is_null( $this->namespaceNames
) ) {
368 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
370 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
371 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
373 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
375 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
376 if ( $wgMetaNamespaceTalk ) {
377 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
379 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
380 $this->namespaceNames
[NS_PROJECT_TALK
] =
381 $this->fixVariableInNamespace( $talk );
384 # Sometimes a language will be localised but not actually exist on this wiki.
385 foreach ( $this->namespaceNames
as $key => $text ) {
386 if ( !isset( $validNamespaces[$key] ) ) {
387 unset( $this->namespaceNames
[$key] );
391 # The above mixing may leave namespaces out of canonical order.
392 # Re-order by namespace ID number...
393 ksort( $this->namespaceNames
);
395 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
397 return $this->namespaceNames
;
401 * Arbitrarily set all of the namespace names at once. Mainly used for testing
402 * @param $namespaces Array of namespaces (id => name)
404 public function setNamespaces( array $namespaces ) {
405 $this->namespaceNames
= $namespaces;
406 $this->mNamespaceIds
= null;
410 * Resets all of the namespace caches. Mainly used for testing
412 public function resetNamespaces( ) {
413 $this->namespaceNames
= null;
414 $this->mNamespaceIds
= null;
415 $this->namespaceAliases
= null;
419 * A convenience function that returns the same thing as
420 * getNamespaces() except with the array values changed to ' '
421 * where it found '_', useful for producing output to be displayed
422 * e.g. in <select> forms.
426 function getFormattedNamespaces() {
427 $ns = $this->getNamespaces();
428 foreach ( $ns as $k => $v ) {
429 $ns[$k] = strtr( $v, '_', ' ' );
435 * Get a namespace value by key
437 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
438 * echo $mw_ns; // prints 'MediaWiki'
441 * @param $index Int: the array key of the namespace to return
442 * @return mixed, string if the namespace value exists, otherwise false
444 function getNsText( $index ) {
445 $ns = $this->getNamespaces();
446 return isset( $ns[$index] ) ?
$ns[$index] : false;
450 * A convenience function that returns the same thing as
451 * getNsText() except with '_' changed to ' ', useful for
454 * @param $index string
458 function getFormattedNsText( $index ) {
459 $ns = $this->getNsText( $index );
460 return strtr( $ns, '_', ' ' );
464 * Returns gender-dependent namespace alias if available.
465 * @param $index Int: namespace index
466 * @param $gender String: gender key (male, female... )
470 function getGenderNsText( $index, $gender ) {
471 global $wgExtraGenderNamespaces;
473 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
474 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
478 * Whether this language makes distinguishes genders for example in
483 function needsGenderDistinction() {
484 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
485 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
486 // $wgExtraGenderNamespaces overrides everything
488 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
489 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
490 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
493 // Check what is in i18n files
494 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
495 return count( $aliases ) > 0;
500 * Get a namespace key by value, case insensitive.
501 * Only matches namespace names for the current language, not the
502 * canonical ones defined in Namespace.php.
504 * @param $text String
505 * @return mixed An integer if $text is a valid value otherwise false
507 function getLocalNsIndex( $text ) {
508 $lctext = $this->lc( $text );
509 $ids = $this->getNamespaceIds();
510 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
516 function getNamespaceAliases() {
517 if ( is_null( $this->namespaceAliases
) ) {
518 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
522 foreach ( $aliases as $name => $index ) {
523 if ( $index === NS_PROJECT_TALK
) {
524 unset( $aliases[$name] );
525 $name = $this->fixVariableInNamespace( $name );
526 $aliases[$name] = $index;
531 global $wgExtraGenderNamespaces;
532 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
533 foreach ( $genders as $index => $forms ) {
534 foreach ( $forms as $alias ) {
535 $aliases[$alias] = $index;
539 $this->namespaceAliases
= $aliases;
541 return $this->namespaceAliases
;
547 function getNamespaceIds() {
548 if ( is_null( $this->mNamespaceIds
) ) {
549 global $wgNamespaceAliases;
550 # Put namespace names and aliases into a hashtable.
551 # If this is too slow, then we should arrange it so that it is done
552 # before caching. The catch is that at pre-cache time, the above
553 # class-specific fixup hasn't been done.
554 $this->mNamespaceIds
= array();
555 foreach ( $this->getNamespaces() as $index => $name ) {
556 $this->mNamespaceIds
[$this->lc( $name )] = $index;
558 foreach ( $this->getNamespaceAliases() as $name => $index ) {
559 $this->mNamespaceIds
[$this->lc( $name )] = $index;
561 if ( $wgNamespaceAliases ) {
562 foreach ( $wgNamespaceAliases as $name => $index ) {
563 $this->mNamespaceIds
[$this->lc( $name )] = $index;
567 return $this->mNamespaceIds
;
571 * Get a namespace key by value, case insensitive. Canonical namespace
572 * names override custom ones defined for the current language.
574 * @param $text String
575 * @return mixed An integer if $text is a valid value otherwise false
577 function getNsIndex( $text ) {
578 $lctext = $this->lc( $text );
579 $ns = MWNamespace
::getCanonicalIndex( $lctext );
580 if ( $ns !== null ) {
583 $ids = $this->getNamespaceIds();
584 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
588 * short names for language variants used for language conversion links.
590 * @param $code String
591 * @param $usemsg bool Use the "variantname-xyz" message if it exists
594 function getVariantname( $code, $usemsg = true ) {
595 $msg = "variantname-$code";
596 if ( $usemsg && wfMessage( $msg )->exists() ) {
597 return $this->getMessageFromDB( $msg );
599 $name = self
::fetchLanguageName( $code );
601 return $name; # if it's defined as a language name, show that
603 # otherwise, output the language code
609 * @param $name string
612 function specialPage( $name ) {
613 $aliases = $this->getSpecialPageAliases();
614 if ( isset( $aliases[$name][0] ) ) {
615 $name = $aliases[$name][0];
617 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
623 function getQuickbarSettings() {
625 $this->getMessage( 'qbsettings-none' ),
626 $this->getMessage( 'qbsettings-fixedleft' ),
627 $this->getMessage( 'qbsettings-fixedright' ),
628 $this->getMessage( 'qbsettings-floatingleft' ),
629 $this->getMessage( 'qbsettings-floatingright' ),
630 $this->getMessage( 'qbsettings-directionality' )
637 function getDatePreferences() {
638 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
644 function getDateFormats() {
645 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
649 * @return array|string
651 function getDefaultDateFormat() {
652 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
653 if ( $df === 'dmy or mdy' ) {
654 global $wgAmericanDates;
655 return $wgAmericanDates ?
'mdy' : 'dmy';
664 function getDatePreferenceMigrationMap() {
665 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
672 function getImageFile( $image ) {
673 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
679 function getExtraUserToggles() {
680 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
687 function getUserToggle( $tog ) {
688 return $this->getMessageFromDB( "tog-$tog" );
692 * Get native language names, indexed by code.
693 * Only those defined in MediaWiki, no other data like CLDR.
694 * If $customisedOnly is true, only returns codes with a messages file
696 * @param $customisedOnly bool
699 * @deprecated in 1.20, use fetchLanguageNames()
701 public static function getLanguageNames( $customisedOnly = false ) {
702 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
706 * Get translated language names. This is done on best effort and
707 * by default this is exactly the same as Language::getLanguageNames.
708 * The CLDR extension provides translated names.
709 * @param $code String Language code.
710 * @return Array language code => language name
712 * @deprecated in 1.20, use fetchLanguageNames()
714 public static function getTranslatedLanguageNames( $code ) {
715 return self
::fetchLanguageNames( $code, 'all' );
719 * Get an array of language names, indexed by code.
720 * @param $inLanguage null|string: Code of language in which to return the names
721 * Use null for autonyms (native names)
722 * @param $include string:
723 * 'all' all available languages
724 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
725 * 'mwfile' only if the language is in 'mw' *and* has a message file
726 * @return array: language code => language name
729 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
730 global $wgExtraLanguageNames;
731 static $coreLanguageNames;
733 if ( $coreLanguageNames === null ) {
734 include( MWInit
::compiledPath( 'languages/Names.php' ) );
740 # TODO: also include when $inLanguage is null, when this code is more efficient
741 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
744 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
745 foreach ( $mwNames as $mwCode => $mwName ) {
746 # - Prefer own MediaWiki native name when not using the hook
747 # TODO: prefer it always to make it consistent, but casing is different in CLDR
748 # - For other names just add if not added through the hook
749 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
750 $names[$mwCode] = $mwName;
754 if ( $include === 'all' ) {
759 $coreCodes = array_keys( $mwNames );
760 foreach( $coreCodes as $coreCode ) {
761 $returnMw[$coreCode] = $names[$coreCode];
764 if( $include === 'mwfile' ) {
765 $namesMwFile = array();
766 # We do this using a foreach over the codes instead of a directory
767 # loop so that messages files in extensions will work correctly.
768 foreach ( $returnMw as $code => $value ) {
769 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
770 $namesMwFile[$code] = $names[$code];
775 # 'mw' option; default if it's not one of the other two options (all/mwfile)
780 * @param $code string: The code of the language for which to get the name
781 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
782 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
783 * @return string: Language name or empty
786 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
787 $array = self
::fetchLanguageNames( $inLanguage, $include );
788 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
792 * Get a message from the MediaWiki namespace.
794 * @param $msg String: message name
797 function getMessageFromDB( $msg ) {
798 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
802 * Get the native language name of $code.
803 * Only if defined in MediaWiki, no other data like CLDR.
804 * @param $code string
806 * @deprecated in 1.20, use fetchLanguageName()
808 function getLanguageName( $code ) {
809 return self
::fetchLanguageName( $code );
816 function getMonthName( $key ) {
817 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
823 function getMonthNamesArray() {
824 $monthNames = array( '' );
825 for ( $i = 1; $i < 13; $i++
) {
826 $monthNames[] = $this->getMonthName( $i );
835 function getMonthNameGen( $key ) {
836 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
843 function getMonthAbbreviation( $key ) {
844 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
850 function getMonthAbbreviationsArray() {
851 $monthNames = array( '' );
852 for ( $i = 1; $i < 13; $i++
) {
853 $monthNames[] = $this->getMonthAbbreviation( $i );
862 function getWeekdayName( $key ) {
863 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
870 function getWeekdayAbbreviation( $key ) {
871 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
878 function getIranianCalendarMonthName( $key ) {
879 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
886 function getHebrewCalendarMonthName( $key ) {
887 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
894 function getHebrewCalendarMonthNameGen( $key ) {
895 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
902 function getHijriCalendarMonthName( $key ) {
903 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
907 * This is a workalike of PHP's date() function, but with better
908 * internationalisation, a reduced set of format characters, and a better
911 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
912 * PHP manual for definitions. There are a number of extensions, which
915 * xn Do not translate digits of the next numeric format character
916 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
917 * xr Use roman numerals for the next numeric format character
918 * xh Use hebrew numerals for the next numeric format character
920 * xg Genitive month name
922 * xij j (day number) in Iranian calendar
923 * xiF F (month name) in Iranian calendar
924 * xin n (month number) in Iranian calendar
925 * xiy y (two digit year) in Iranian calendar
926 * xiY Y (full year) in Iranian calendar
928 * xjj j (day number) in Hebrew calendar
929 * xjF F (month name) in Hebrew calendar
930 * xjt t (days in month) in Hebrew calendar
931 * xjx xg (genitive month name) in Hebrew calendar
932 * xjn n (month number) in Hebrew calendar
933 * xjY Y (full year) in Hebrew calendar
935 * xmj j (day number) in Hijri calendar
936 * xmF F (month name) in Hijri calendar
937 * xmn n (month number) in Hijri calendar
938 * xmY Y (full year) in Hijri calendar
940 * xkY Y (full year) in Thai solar calendar. Months and days are
941 * identical to the Gregorian calendar
942 * xoY Y (full year) in Minguo calendar or Juche year.
943 * Months and days are identical to the
945 * xtY Y (full year) in Japanese nengo. Months and days are
946 * identical to the Gregorian calendar
948 * Characters enclosed in double quotes will be considered literal (with
949 * the quotes themselves removed). Unmatched quotes will be considered
950 * literal quotes. Example:
952 * "The month is" F => The month is January
955 * Backslash escaping is also supported.
957 * Input timestamp is assumed to be pre-normalized to the desired local
960 * @param $format String
961 * @param $ts String: 14-character timestamp
964 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
968 function sprintfDate( $format, $ts ) {
981 for ( $p = 0; $p < strlen( $format ); $p++
) {
984 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
985 $code .= $format[++
$p];
988 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
989 $code .= $format[++
$p];
1000 $rawToggle = !$rawToggle;
1009 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1012 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1013 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1016 $num = substr( $ts, 6, 2 );
1019 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1020 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1023 $num = intval( substr( $ts, 6, 2 ) );
1027 $iranian = self
::tsToIranian( $ts );
1033 $hijri = self
::tsToHijri( $ts );
1039 $hebrew = self
::tsToHebrew( $ts );
1045 $unix = wfTimestamp( TS_UNIX
, $ts );
1047 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1051 $unix = wfTimestamp( TS_UNIX
, $ts );
1053 $w = gmdate( 'w', $unix );
1058 $unix = wfTimestamp( TS_UNIX
, $ts );
1060 $num = gmdate( 'w', $unix );
1064 $unix = wfTimestamp( TS_UNIX
, $ts );
1066 $num = gmdate( 'z', $unix );
1070 $unix = wfTimestamp( TS_UNIX
, $ts );
1072 $num = gmdate( 'W', $unix );
1075 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1079 $iranian = self
::tsToIranian( $ts );
1081 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1085 $hijri = self
::tsToHijri( $ts );
1087 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1091 $hebrew = self
::tsToHebrew( $ts );
1093 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1096 $num = substr( $ts, 4, 2 );
1099 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1102 $num = intval( substr( $ts, 4, 2 ) );
1106 $iranian = self
::tsToIranian( $ts );
1112 $hijri = self
::tsToHijri ( $ts );
1118 $hebrew = self
::tsToHebrew( $ts );
1124 $unix = wfTimestamp( TS_UNIX
, $ts );
1126 $num = gmdate( 't', $unix );
1130 $hebrew = self
::tsToHebrew( $ts );
1136 $unix = wfTimestamp( TS_UNIX
, $ts );
1138 $num = gmdate( 'L', $unix );
1142 $unix = wfTimestamp( TS_UNIX
, $ts );
1144 $num = gmdate( 'o', $unix );
1147 $num = substr( $ts, 0, 4 );
1151 $iranian = self
::tsToIranian( $ts );
1157 $hijri = self
::tsToHijri( $ts );
1163 $hebrew = self
::tsToHebrew( $ts );
1169 $thai = self
::tsToYear( $ts, 'thai' );
1175 $minguo = self
::tsToYear( $ts, 'minguo' );
1181 $tenno = self
::tsToYear( $ts, 'tenno' );
1186 $num = substr( $ts, 2, 2 );
1190 $iranian = self
::tsToIranian( $ts );
1192 $num = substr( $iranian[0], -2 );
1195 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1198 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1201 $h = substr( $ts, 8, 2 );
1202 $num = $h %
12 ?
$h %
12 : 12;
1205 $num = intval( substr( $ts, 8, 2 ) );
1208 $h = substr( $ts, 8, 2 );
1209 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1212 $num = substr( $ts, 8, 2 );
1215 $num = substr( $ts, 10, 2 );
1218 $num = substr( $ts, 12, 2 );
1222 $unix = wfTimestamp( TS_UNIX
, $ts );
1224 $s .= gmdate( 'c', $unix );
1228 $unix = wfTimestamp( TS_UNIX
, $ts );
1230 $s .= gmdate( 'r', $unix );
1234 $unix = wfTimestamp( TS_UNIX
, $ts );
1239 # Backslash escaping
1240 if ( $p < strlen( $format ) - 1 ) {
1241 $s .= $format[++
$p];
1248 if ( $p < strlen( $format ) - 1 ) {
1249 $endQuote = strpos( $format, '"', $p +
1 );
1250 if ( $endQuote === false ) {
1251 # No terminating quote, assume literal "
1254 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1258 # Quote at end of string, assume literal "
1265 if ( $num !== false ) {
1266 if ( $rawToggle ||
$raw ) {
1269 } elseif ( $roman ) {
1270 $s .= self
::romanNumeral( $num );
1272 } elseif ( $hebrewNum ) {
1273 $s .= self
::hebrewNumeral( $num );
1276 $s .= $this->formatNum( $num, true );
1283 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1284 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1287 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1288 * Gregorian dates to Iranian dates. Originally written in C, it
1289 * is released under the terms of GNU Lesser General Public
1290 * License. Conversion to PHP was performed by Niklas Laxström.
1292 * Link: http://www.farsiweb.info/jalali/jalali.c
1298 private static function tsToIranian( $ts ) {
1299 $gy = substr( $ts, 0, 4 ) -1600;
1300 $gm = substr( $ts, 4, 2 ) -1;
1301 $gd = substr( $ts, 6, 2 ) -1;
1303 # Days passed from the beginning (including leap years)
1305 +
floor( ( $gy +
3 ) / 4 )
1306 - floor( ( $gy +
99 ) / 100 )
1307 +
floor( ( $gy +
399 ) / 400 );
1309 // Add days of the past months of this year
1310 for ( $i = 0; $i < $gm; $i++
) {
1311 $gDayNo +
= self
::$GREG_DAYS[$i];
1315 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1319 // Days passed in current month
1320 $gDayNo +
= (int)$gd;
1322 $jDayNo = $gDayNo - 79;
1324 $jNp = floor( $jDayNo / 12053 );
1327 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1330 if ( $jDayNo >= 366 ) {
1331 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1332 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1335 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1336 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1342 return array( $jy, $jm, $jd );
1346 * Converting Gregorian dates to Hijri dates.
1348 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1350 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1356 private static function tsToHijri( $ts ) {
1357 $year = substr( $ts, 0, 4 );
1358 $month = substr( $ts, 4, 2 );
1359 $day = substr( $ts, 6, 2 );
1367 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1368 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1371 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1372 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1373 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1376 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1377 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1380 $zl = $zjd -1948440 +
10632;
1381 $zn = (int)( ( $zl - 1 ) / 10631 );
1382 $zl = $zl - 10631 * $zn +
354;
1383 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1384 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1385 $zm = (int)( ( 24 * $zl ) / 709 );
1386 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1387 $zy = 30 * $zn +
$zj - 30;
1389 return array( $zy, $zm, $zd );
1393 * Converting Gregorian dates to Hebrew dates.
1395 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1396 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1397 * to translate the relevant functions into PHP and release them under
1400 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1401 * and Adar II is 14. In a non-leap year, Adar is 6.
1407 private static function tsToHebrew( $ts ) {
1409 $year = substr( $ts, 0, 4 );
1410 $month = substr( $ts, 4, 2 );
1411 $day = substr( $ts, 6, 2 );
1413 # Calculate Hebrew year
1414 $hebrewYear = $year +
3760;
1416 # Month number when September = 1, August = 12
1418 if ( $month > 12 ) {
1425 # Calculate day of year from 1 September
1427 for ( $i = 1; $i < $month; $i++
) {
1431 # Check if the year is leap
1432 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1435 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1442 # Calculate the start of the Hebrew year
1443 $start = self
::hebrewYearStart( $hebrewYear );
1445 # Calculate next year's start
1446 if ( $dayOfYear <= $start ) {
1447 # Day is before the start of the year - it is the previous year
1449 $nextStart = $start;
1453 # Add days since previous year's 1 September
1455 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1459 # Start of the new (previous) year
1460 $start = self
::hebrewYearStart( $hebrewYear );
1463 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1466 # Calculate Hebrew day of year
1467 $hebrewDayOfYear = $dayOfYear - $start;
1469 # Difference between year's days
1470 $diff = $nextStart - $start;
1471 # Add 12 (or 13 for leap years) days to ignore the difference between
1472 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1473 # difference is only about the year type
1474 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1480 # Check the year pattern, and is leap year
1481 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1482 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1483 # and non-leap years
1484 $yearPattern = $diff %
30;
1485 # Check if leap year
1486 $isLeap = $diff >= 30;
1488 # Calculate day in the month from number of day in the Hebrew year
1489 # Don't check Adar - if the day is not in Adar, we will stop before;
1490 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1491 $hebrewDay = $hebrewDayOfYear;
1494 while ( $hebrewMonth <= 12 ) {
1495 # Calculate days in this month
1496 if ( $isLeap && $hebrewMonth == 6 ) {
1497 # Adar in a leap year
1499 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1501 if ( $hebrewDay <= $days ) {
1505 # Subtract the days of Adar I
1506 $hebrewDay -= $days;
1509 if ( $hebrewDay <= $days ) {
1515 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1516 # Cheshvan in a complete year (otherwise as the rule below)
1518 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1519 # Kislev in an incomplete year (otherwise as the rule below)
1522 # Odd months have 30 days, even have 29
1523 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1525 if ( $hebrewDay <= $days ) {
1526 # In the current month
1529 # Subtract the days of the current month
1530 $hebrewDay -= $days;
1531 # Try in the next month
1536 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1540 * This calculates the Hebrew year start, as days since 1 September.
1541 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1542 * Used for Hebrew date.
1548 private static function hebrewYearStart( $year ) {
1549 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1550 $b = intval( ( $year - 1 ) %
4 );
1551 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1555 $Mar = intval( $m );
1561 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1562 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1564 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1566 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1570 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1575 * Algorithm to convert Gregorian dates to Thai solar dates,
1576 * Minguo dates or Minguo dates.
1578 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1579 * http://en.wikipedia.org/wiki/Minguo_calendar
1580 * http://en.wikipedia.org/wiki/Japanese_era_name
1582 * @param $ts String: 14-character timestamp
1583 * @param $cName String: calender name
1584 * @return Array: converted year, month, day
1586 private static function tsToYear( $ts, $cName ) {
1587 $gy = substr( $ts, 0, 4 );
1588 $gm = substr( $ts, 4, 2 );
1589 $gd = substr( $ts, 6, 2 );
1591 if ( !strcmp( $cName, 'thai' ) ) {
1593 # Add 543 years to the Gregorian calendar
1594 # Months and days are identical
1595 $gy_offset = $gy +
543;
1596 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1598 # Deduct 1911 years from the Gregorian calendar
1599 # Months and days are identical
1600 $gy_offset = $gy - 1911;
1601 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1602 # Nengō dates up to Meiji period
1603 # Deduct years from the Gregorian calendar
1604 # depending on the nengo periods
1605 # Months and days are identical
1606 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1608 $gy_gannen = $gy - 1868 +
1;
1609 $gy_offset = $gy_gannen;
1610 if ( $gy_gannen == 1 ) {
1613 $gy_offset = '明治' . $gy_offset;
1615 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1616 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1617 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1618 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1619 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1623 $gy_gannen = $gy - 1912 +
1;
1624 $gy_offset = $gy_gannen;
1625 if ( $gy_gannen == 1 ) {
1628 $gy_offset = '大正' . $gy_offset;
1630 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1631 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1632 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1636 $gy_gannen = $gy - 1926 +
1;
1637 $gy_offset = $gy_gannen;
1638 if ( $gy_gannen == 1 ) {
1641 $gy_offset = '昭和' . $gy_offset;
1644 $gy_gannen = $gy - 1989 +
1;
1645 $gy_offset = $gy_gannen;
1646 if ( $gy_gannen == 1 ) {
1649 $gy_offset = '平成' . $gy_offset;
1655 return array( $gy_offset, $gm, $gd );
1659 * Roman number formatting up to 3000
1665 static function romanNumeral( $num ) {
1666 static $table = array(
1667 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1668 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1669 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1670 array( '', 'M', 'MM', 'MMM' )
1673 $num = intval( $num );
1674 if ( $num > 3000 ||
$num <= 0 ) {
1679 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1680 if ( $num >= $pow10 ) {
1681 $s .= $table[$i][(int)floor( $num / $pow10 )];
1683 $num = $num %
$pow10;
1689 * Hebrew Gematria number formatting up to 9999
1695 static function hebrewNumeral( $num ) {
1696 static $table = array(
1697 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1698 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1699 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1700 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1703 $num = intval( $num );
1704 if ( $num > 9999 ||
$num <= 0 ) {
1709 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1710 if ( $num >= $pow10 ) {
1711 if ( $num == 15 ||
$num == 16 ) {
1712 $s .= $table[0][9] . $table[0][$num - 9];
1715 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1716 if ( $pow10 == 1000 ) {
1721 $num = $num %
$pow10;
1723 if ( strlen( $s ) == 2 ) {
1726 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1727 $str .= substr( $s, strlen( $s ) - 2, 2 );
1729 $start = substr( $str, 0, strlen( $str ) - 2 );
1730 $end = substr( $str, strlen( $str ) - 2 );
1733 $str = $start . 'ך';
1736 $str = $start . 'ם';
1739 $str = $start . 'ן';
1742 $str = $start . 'ף';
1745 $str = $start . 'ץ';
1752 * Used by date() and time() to adjust the time output.
1754 * @param $ts Int the time in date('YmdHis') format
1755 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1756 * get user timecorrection setting)
1759 function userAdjust( $ts, $tz = false ) {
1760 global $wgUser, $wgLocalTZoffset;
1762 if ( $tz === false ) {
1763 $tz = $wgUser->getOption( 'timecorrection' );
1766 $data = explode( '|', $tz, 3 );
1768 if ( $data[0] == 'ZoneInfo' ) {
1769 wfSuppressWarnings();
1770 $userTZ = timezone_open( $data[2] );
1771 wfRestoreWarnings();
1772 if ( $userTZ !== false ) {
1773 $date = date_create( $ts, timezone_open( 'UTC' ) );
1774 date_timezone_set( $date, $userTZ );
1775 $date = date_format( $date, 'YmdHis' );
1778 # Unrecognized timezone, default to 'Offset' with the stored offset.
1779 $data[0] = 'Offset';
1783 if ( $data[0] == 'System' ||
$tz == '' ) {
1784 # Global offset in minutes.
1785 if ( isset( $wgLocalTZoffset ) ) {
1786 $minDiff = $wgLocalTZoffset;
1788 } elseif ( $data[0] == 'Offset' ) {
1789 $minDiff = intval( $data[1] );
1791 $data = explode( ':', $tz );
1792 if ( count( $data ) == 2 ) {
1793 $data[0] = intval( $data[0] );
1794 $data[1] = intval( $data[1] );
1795 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1796 if ( $data[0] < 0 ) {
1797 $minDiff = -$minDiff;
1800 $minDiff = intval( $data[0] ) * 60;
1804 # No difference ? Return time unchanged
1805 if ( 0 == $minDiff ) {
1809 wfSuppressWarnings(); // E_STRICT system time bitching
1810 # Generate an adjusted date; take advantage of the fact that mktime
1811 # will normalize out-of-range values so we don't have to split $minDiff
1812 # into hours and minutes.
1814 (int)substr( $ts, 8, 2 ) ), # Hours
1815 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1816 (int)substr( $ts, 12, 2 ), # Seconds
1817 (int)substr( $ts, 4, 2 ), # Month
1818 (int)substr( $ts, 6, 2 ), # Day
1819 (int)substr( $ts, 0, 4 ) ); # Year
1821 $date = date( 'YmdHis', $t );
1822 wfRestoreWarnings();
1828 * This is meant to be used by time(), date(), and timeanddate() to get
1829 * the date preference they're supposed to use, it should be used in
1833 * function timeanddate([...], $format = true) {
1834 * $datePreference = $this->dateFormat($format);
1839 * @param $usePrefs Mixed: if true, the user's preference is used
1840 * if false, the site/language default is used
1841 * if int/string, assumed to be a format.
1844 function dateFormat( $usePrefs = true ) {
1847 if ( is_bool( $usePrefs ) ) {
1849 $datePreference = $wgUser->getDatePreference();
1851 $datePreference = (string)User
::getDefaultOption( 'date' );
1854 $datePreference = (string)$usePrefs;
1858 if ( $datePreference == '' ) {
1862 return $datePreference;
1866 * Get a format string for a given type and preference
1867 * @param $type string May be date, time or both
1868 * @param $pref string The format name as it appears in Messages*.php
1872 function getDateFormatString( $type, $pref ) {
1873 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1874 if ( $pref == 'default' ) {
1875 $pref = $this->getDefaultDateFormat();
1876 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1878 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1879 if ( is_null( $df ) ) {
1880 $pref = $this->getDefaultDateFormat();
1881 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1884 $this->dateFormatStrings
[$type][$pref] = $df;
1886 return $this->dateFormatStrings
[$type][$pref];
1890 * @param $ts Mixed: the time format which needs to be turned into a
1891 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1892 * @param $adj Bool: whether to adjust the time output according to the
1893 * user configured offset ($timecorrection)
1894 * @param $format Mixed: true to use user's date format preference
1895 * @param $timecorrection String|bool the time offset as returned by
1896 * validateTimeZone() in Special:Preferences
1899 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1900 $ts = wfTimestamp( TS_MW
, $ts );
1902 $ts = $this->userAdjust( $ts, $timecorrection );
1904 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1905 return $this->sprintfDate( $df, $ts );
1909 * @param $ts Mixed: the time format which needs to be turned into a
1910 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1911 * @param $adj Bool: whether to adjust the time output according to the
1912 * user configured offset ($timecorrection)
1913 * @param $format Mixed: true to use user's date format preference
1914 * @param $timecorrection String|bool the time offset as returned by
1915 * validateTimeZone() in Special:Preferences
1918 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1919 $ts = wfTimestamp( TS_MW
, $ts );
1921 $ts = $this->userAdjust( $ts, $timecorrection );
1923 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1924 return $this->sprintfDate( $df, $ts );
1928 * @param $ts Mixed: the time format which needs to be turned into a
1929 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1930 * @param $adj Bool: whether to adjust the time output according to the
1931 * user configured offset ($timecorrection)
1932 * @param $format Mixed: what format to return, if it's false output the
1933 * default one (default true)
1934 * @param $timecorrection String|bool the time offset as returned by
1935 * validateTimeZone() in Special:Preferences
1938 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1939 $ts = wfTimestamp( TS_MW
, $ts );
1941 $ts = $this->userAdjust( $ts, $timecorrection );
1943 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1944 return $this->sprintfDate( $df, $ts );
1948 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1952 * @param integer $seconds The amount of seconds.
1953 * @param array $chosenIntervals The intervals to enable.
1957 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1958 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1960 $segments = array();
1962 foreach ( $intervals as $intervalName => $intervalValue ) {
1963 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1964 $segments[] = $message->inLanguage( $this )->escaped();
1967 return $this->listToText( $segments );
1971 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1972 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1976 * @param integer $seconds The amount of seconds.
1977 * @param array $chosenIntervals The intervals to enable.
1981 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1982 if ( empty( $chosenIntervals ) ) {
1983 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1986 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
1987 $sortedNames = array_keys( $intervals );
1988 $smallestInterval = array_pop( $sortedNames );
1990 $segments = array();
1992 foreach ( $intervals as $name => $length ) {
1993 $value = floor( $seconds / $length );
1995 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
1996 $seconds -= $value * $length;
1997 $segments[$name] = $value;
2005 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2007 * @param $type String: can be 'date', 'time' or 'both'
2008 * @param $ts Mixed: the time format which needs to be turned into a
2009 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2010 * @param $user User object used to get preferences for timezone and format
2011 * @param $options Array, can contain the following keys:
2012 * - 'timecorrection': time correction, can have the following values:
2013 * - true: use user's preference
2014 * - false: don't use time correction
2015 * - integer: value of time correction in minutes
2016 * - 'format': format to use, can have the following values:
2017 * - true: use user's preference
2018 * - false: use default preference
2019 * - string: format to use
2023 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2024 $ts = wfTimestamp( TS_MW
, $ts );
2025 $options +
= array( 'timecorrection' => true, 'format' => true );
2026 if ( $options['timecorrection'] !== false ) {
2027 if ( $options['timecorrection'] === true ) {
2028 $offset = $user->getOption( 'timecorrection' );
2030 $offset = $options['timecorrection'];
2032 $ts = $this->userAdjust( $ts, $offset );
2034 if ( $options['format'] === true ) {
2035 $format = $user->getDatePreference();
2037 $format = $options['format'];
2039 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2040 return $this->sprintfDate( $df, $ts );
2044 * Get the formatted date for the given timestamp and formatted for
2047 * @param $ts Mixed: the time format which needs to be turned into a
2048 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2049 * @param $user User object used to get preferences for timezone and format
2050 * @param $options Array, can contain the following keys:
2051 * - 'timecorrection': time correction, can have the following values:
2052 * - true: use user's preference
2053 * - false: don't use time correction
2054 * - integer: value of time correction in minutes
2055 * - 'format': format to use, can have the following values:
2056 * - true: use user's preference
2057 * - false: use default preference
2058 * - string: format to use
2062 public function userDate( $ts, User
$user, array $options = array() ) {
2063 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2067 * Get the formatted time for the given timestamp and formatted for
2070 * @param $ts Mixed: the time format which needs to be turned into a
2071 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2072 * @param $user User object used to get preferences for timezone and format
2073 * @param $options Array, can contain the following keys:
2074 * - 'timecorrection': time correction, can have the following values:
2075 * - true: use user's preference
2076 * - false: don't use time correction
2077 * - integer: value of time correction in minutes
2078 * - 'format': format to use, can have the following values:
2079 * - true: use user's preference
2080 * - false: use default preference
2081 * - string: format to use
2085 public function userTime( $ts, User
$user, array $options = array() ) {
2086 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2090 * Get the formatted date and time for the given timestamp and formatted for
2093 * @param $ts Mixed: the time format which needs to be turned into a
2094 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2095 * @param $user User object used to get preferences for timezone and format
2096 * @param $options Array, can contain the following keys:
2097 * - 'timecorrection': time correction, can have the following values:
2098 * - true: use user's preference
2099 * - false: don't use time correction
2100 * - integer: value of time correction in minutes
2101 * - 'format': format to use, can have the following values:
2102 * - true: use user's preference
2103 * - false: use default preference
2104 * - string: format to use
2108 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2109 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2113 * @param $key string
2114 * @return array|null
2116 function getMessage( $key ) {
2117 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2123 function getAllMessages() {
2124 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2133 function iconv( $in, $out, $string ) {
2134 # This is a wrapper for iconv in all languages except esperanto,
2135 # which does some nasty x-conversions beforehand
2137 # Even with //IGNORE iconv can whine about illegal characters in
2138 # *input* string. We just ignore those too.
2139 # REF: http://bugs.php.net/bug.php?id=37166
2140 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2141 wfSuppressWarnings();
2142 $text = iconv( $in, $out . '//IGNORE', $string );
2143 wfRestoreWarnings();
2147 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2150 * @param $matches array
2151 * @return mixed|string
2153 function ucwordbreaksCallbackAscii( $matches ) {
2154 return $this->ucfirst( $matches[1] );
2158 * @param $matches array
2161 function ucwordbreaksCallbackMB( $matches ) {
2162 return mb_strtoupper( $matches[0] );
2166 * @param $matches array
2169 function ucCallback( $matches ) {
2170 list( $wikiUpperChars ) = self
::getCaseMaps();
2171 return strtr( $matches[1], $wikiUpperChars );
2175 * @param $matches array
2178 function lcCallback( $matches ) {
2179 list( , $wikiLowerChars ) = self
::getCaseMaps();
2180 return strtr( $matches[1], $wikiLowerChars );
2184 * @param $matches array
2187 function ucwordsCallbackMB( $matches ) {
2188 return mb_strtoupper( $matches[0] );
2192 * @param $matches array
2195 function ucwordsCallbackWiki( $matches ) {
2196 list( $wikiUpperChars ) = self
::getCaseMaps();
2197 return strtr( $matches[0], $wikiUpperChars );
2201 * Make a string's first character uppercase
2203 * @param $str string
2207 function ucfirst( $str ) {
2209 if ( $o < 96 ) { // if already uppercase...
2211 } elseif ( $o < 128 ) {
2212 return ucfirst( $str ); // use PHP's ucfirst()
2214 // fall back to more complex logic in case of multibyte strings
2215 return $this->uc( $str, true );
2220 * Convert a string to uppercase
2222 * @param $str string
2223 * @param $first bool
2227 function uc( $str, $first = false ) {
2228 if ( function_exists( 'mb_strtoupper' ) ) {
2230 if ( $this->isMultibyte( $str ) ) {
2231 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2233 return ucfirst( $str );
2236 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2239 if ( $this->isMultibyte( $str ) ) {
2240 $x = $first ?
'^' : '';
2241 return preg_replace_callback(
2242 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2243 array( $this, 'ucCallback' ),
2247 return $first ?
ucfirst( $str ) : strtoupper( $str );
2253 * @param $str string
2254 * @return mixed|string
2256 function lcfirst( $str ) {
2259 return strval( $str );
2260 } elseif ( $o >= 128 ) {
2261 return $this->lc( $str, true );
2262 } elseif ( $o > 96 ) {
2265 $str[0] = strtolower( $str[0] );
2271 * @param $str string
2272 * @param $first bool
2273 * @return mixed|string
2275 function lc( $str, $first = false ) {
2276 if ( function_exists( 'mb_strtolower' ) ) {
2278 if ( $this->isMultibyte( $str ) ) {
2279 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2281 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2284 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2287 if ( $this->isMultibyte( $str ) ) {
2288 $x = $first ?
'^' : '';
2289 return preg_replace_callback(
2290 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2291 array( $this, 'lcCallback' ),
2295 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2301 * @param $str string
2304 function isMultibyte( $str ) {
2305 return (bool)preg_match( '/[\x80-\xff]/', $str );
2309 * @param $str string
2310 * @return mixed|string
2312 function ucwords( $str ) {
2313 if ( $this->isMultibyte( $str ) ) {
2314 $str = $this->lc( $str );
2316 // regexp to find first letter in each word (i.e. after each space)
2317 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2319 // function to use to capitalize a single char
2320 if ( function_exists( 'mb_strtoupper' ) ) {
2321 return preg_replace_callback(
2323 array( $this, 'ucwordsCallbackMB' ),
2327 return preg_replace_callback(
2329 array( $this, 'ucwordsCallbackWiki' ),
2334 return ucwords( strtolower( $str ) );
2339 * capitalize words at word breaks
2341 * @param $str string
2344 function ucwordbreaks( $str ) {
2345 if ( $this->isMultibyte( $str ) ) {
2346 $str = $this->lc( $str );
2348 // since \b doesn't work for UTF-8, we explicitely define word break chars
2349 $breaks = "[ \-\(\)\}\{\.,\?!]";
2351 // find first letter after word break
2352 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2354 if ( function_exists( 'mb_strtoupper' ) ) {
2355 return preg_replace_callback(
2357 array( $this, 'ucwordbreaksCallbackMB' ),
2361 return preg_replace_callback(
2363 array( $this, 'ucwordsCallbackWiki' ),
2368 return preg_replace_callback(
2369 '/\b([\w\x80-\xff]+)\b/',
2370 array( $this, 'ucwordbreaksCallbackAscii' ),
2377 * Return a case-folded representation of $s
2379 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2380 * and $s2 are the same except for the case of their characters. It is not
2381 * necessary for the value returned to make sense when displayed.
2383 * Do *not* perform any other normalisation in this function. If a caller
2384 * uses this function when it should be using a more general normalisation
2385 * function, then fix the caller.
2391 function caseFold( $s ) {
2392 return $this->uc( $s );
2399 function checkTitleEncoding( $s ) {
2400 if ( is_array( $s ) ) {
2401 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2403 # Check for non-UTF-8 URLs
2404 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2409 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2410 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2415 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2421 function fallback8bitEncoding() {
2422 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2426 * Most writing systems use whitespace to break up words.
2427 * Some languages such as Chinese don't conventionally do this,
2428 * which requires special handling when breaking up words for
2433 function hasWordBreaks() {
2438 * Some languages such as Chinese require word segmentation,
2439 * Specify such segmentation when overridden in derived class.
2441 * @param $string String
2444 function segmentByWord( $string ) {
2449 * Some languages have special punctuation need to be normalized.
2450 * Make such changes here.
2452 * @param $string String
2455 function normalizeForSearch( $string ) {
2456 return self
::convertDoubleWidth( $string );
2460 * convert double-width roman characters to single-width.
2461 * range: ff00-ff5f ~= 0020-007f
2463 * @param $string string
2467 protected static function convertDoubleWidth( $string ) {
2468 static $full = null;
2469 static $half = null;
2471 if ( $full === null ) {
2472 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2473 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2474 $full = str_split( $fullWidth, 3 );
2475 $half = str_split( $halfWidth );
2478 $string = str_replace( $full, $half, $string );
2483 * @param $string string
2484 * @param $pattern string
2487 protected static function insertSpace( $string, $pattern ) {
2488 $string = preg_replace( $pattern, " $1 ", $string );
2489 $string = preg_replace( '/ +/', ' ', $string );
2494 * @param $termsArray array
2497 function convertForSearchResult( $termsArray ) {
2498 # some languages, e.g. Chinese, need to do a conversion
2499 # in order for search results to be displayed correctly
2504 * Get the first character of a string.
2509 function firstChar( $s ) {
2512 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2513 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2518 if ( isset( $matches[1] ) ) {
2519 if ( strlen( $matches[1] ) != 3 ) {
2523 // Break down Hangul syllables to grab the first jamo
2524 $code = utf8ToCodepoint( $matches[1] );
2525 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2527 } elseif ( $code < 0xb098 ) {
2528 return "\xe3\x84\xb1";
2529 } elseif ( $code < 0xb2e4 ) {
2530 return "\xe3\x84\xb4";
2531 } elseif ( $code < 0xb77c ) {
2532 return "\xe3\x84\xb7";
2533 } elseif ( $code < 0xb9c8 ) {
2534 return "\xe3\x84\xb9";
2535 } elseif ( $code < 0xbc14 ) {
2536 return "\xe3\x85\x81";
2537 } elseif ( $code < 0xc0ac ) {
2538 return "\xe3\x85\x82";
2539 } elseif ( $code < 0xc544 ) {
2540 return "\xe3\x85\x85";
2541 } elseif ( $code < 0xc790 ) {
2542 return "\xe3\x85\x87";
2543 } elseif ( $code < 0xcc28 ) {
2544 return "\xe3\x85\x88";
2545 } elseif ( $code < 0xce74 ) {
2546 return "\xe3\x85\x8a";
2547 } elseif ( $code < 0xd0c0 ) {
2548 return "\xe3\x85\x8b";
2549 } elseif ( $code < 0xd30c ) {
2550 return "\xe3\x85\x8c";
2551 } elseif ( $code < 0xd558 ) {
2552 return "\xe3\x85\x8d";
2554 return "\xe3\x85\x8e";
2561 function initEncoding() {
2562 # Some languages may have an alternate char encoding option
2563 # (Esperanto X-coding, Japanese furigana conversion, etc)
2564 # If this language is used as the primary content language,
2565 # an override to the defaults can be set here on startup.
2572 function recodeForEdit( $s ) {
2573 # For some languages we'll want to explicitly specify
2574 # which characters make it into the edit box raw
2575 # or are converted in some way or another.
2576 global $wgEditEncoding;
2577 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2580 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2588 function recodeInput( $s ) {
2589 # Take the previous into account.
2590 global $wgEditEncoding;
2591 if ( $wgEditEncoding != '' ) {
2592 $enc = $wgEditEncoding;
2596 if ( $enc == 'UTF-8' ) {
2599 return $this->iconv( $enc, 'UTF-8', $s );
2604 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2605 * also cleans up certain backwards-compatible sequences, converting them
2606 * to the modern Unicode equivalent.
2608 * This is language-specific for performance reasons only.
2614 function normalize( $s ) {
2615 global $wgAllUnicodeFixes;
2616 $s = UtfNormal
::cleanUp( $s );
2617 if ( $wgAllUnicodeFixes ) {
2618 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2619 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2626 * Transform a string using serialized data stored in the given file (which
2627 * must be in the serialized subdirectory of $IP). The file contains pairs
2628 * mapping source characters to destination characters.
2630 * The data is cached in process memory. This will go faster if you have the
2631 * FastStringSearch extension.
2633 * @param $file string
2634 * @param $string string
2636 * @throws MWException
2639 function transformUsingPairFile( $file, $string ) {
2640 if ( !isset( $this->transformData
[$file] ) ) {
2641 $data = wfGetPrecompiledData( $file );
2642 if ( $data === false ) {
2643 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2645 $this->transformData
[$file] = new ReplacementArray( $data );
2647 return $this->transformData
[$file]->replace( $string );
2651 * For right-to-left language support
2656 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2660 * Return the correct HTML 'dir' attribute value for this language.
2664 return $this->isRTL() ?
'rtl' : 'ltr';
2668 * Return 'left' or 'right' as appropriate alignment for line-start
2669 * for this language's text direction.
2671 * Should be equivalent to CSS3 'start' text-align value....
2675 function alignStart() {
2676 return $this->isRTL() ?
'right' : 'left';
2680 * Return 'right' or 'left' as appropriate alignment for line-end
2681 * for this language's text direction.
2683 * Should be equivalent to CSS3 'end' text-align value....
2687 function alignEnd() {
2688 return $this->isRTL() ?
'left' : 'right';
2692 * A hidden direction mark (LRM or RLM), depending on the language direction.
2693 * Unlike getDirMark(), this function returns the character as an HTML entity.
2694 * This function should be used when the output is guaranteed to be HTML,
2695 * because it makes the output HTML source code more readable. When
2696 * the output is plain text or can be escaped, getDirMark() should be used.
2698 * @param $opposite Boolean Get the direction mark opposite to your language
2701 function getDirMarkEntity( $opposite = false ) {
2702 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2703 return $this->isRTL() ?
'‏' : '‎';
2707 * A hidden direction mark (LRM or RLM), depending on the language direction.
2708 * This function produces them as invisible Unicode characters and
2709 * the output may be hard to read and debug, so it should only be used
2710 * when the output is plain text or can be escaped. When the output is
2711 * HTML, use getDirMarkEntity() instead.
2713 * @param $opposite Boolean Get the direction mark opposite to your language
2716 function getDirMark( $opposite = false ) {
2717 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2718 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2719 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2720 return $this->isRTL() ?
$rlm : $lrm;
2726 function capitalizeAllNouns() {
2727 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2731 * An arrow, depending on the language direction.
2733 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2736 function getArrow( $direction = 'forwards' ) {
2737 switch ( $direction ) {
2739 return $this->isRTL() ?
'←' : '→';
2741 return $this->isRTL() ?
'→' : '←';
2754 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2758 function linkPrefixExtension() {
2759 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2765 function getMagicWords() {
2766 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2769 protected function doMagicHook() {
2770 if ( $this->mMagicHookDone
) {
2773 $this->mMagicHookDone
= true;
2774 wfProfileIn( 'LanguageGetMagic' );
2775 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2776 wfProfileOut( 'LanguageGetMagic' );
2780 * Fill a MagicWord object with data from here
2784 function getMagic( $mw ) {
2785 $this->doMagicHook();
2787 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2788 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2790 $magicWords = $this->getMagicWords();
2791 if ( isset( $magicWords[$mw->mId
] ) ) {
2792 $rawEntry = $magicWords[$mw->mId
];
2798 if ( !is_array( $rawEntry ) ) {
2799 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2801 $mw->mCaseSensitive
= $rawEntry[0];
2802 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2807 * Add magic words to the extension array
2809 * @param $newWords array
2811 function addMagicWordsByLang( $newWords ) {
2812 $fallbackChain = $this->getFallbackLanguages();
2813 $fallbackChain = array_reverse( $fallbackChain );
2814 foreach ( $fallbackChain as $code ) {
2815 if ( isset( $newWords[$code] ) ) {
2816 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2822 * Get special page names, as an associative array
2823 * case folded alias => real name
2825 function getSpecialPageAliases() {
2826 // Cache aliases because it may be slow to load them
2827 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2829 $this->mExtendedSpecialPageAliases
=
2830 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2831 wfRunHooks( 'LanguageGetSpecialPageAliases',
2832 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2835 return $this->mExtendedSpecialPageAliases
;
2839 * Italic is unsuitable for some languages
2841 * @param $text String: the text to be emphasized.
2844 function emphasize( $text ) {
2845 return "<em>$text</em>";
2849 * Normally we output all numbers in plain en_US style, that is
2850 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2851 * point twohundredthirtyfive. However this is not suitable for all
2852 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2853 * Icelandic just want to use commas instead of dots, and dots instead
2854 * of commas like "293.291,235".
2856 * An example of this function being called:
2858 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2861 * See LanguageGu.php for the Gujarati implementation and
2862 * $separatorTransformTable on MessageIs.php for
2863 * the , => . and . => , implementation.
2865 * @todo check if it's viable to use localeconv() for the decimal
2867 * @param $number Mixed: the string to be formatted, should be an integer
2868 * or a floating point number.
2869 * @param $nocommafy Bool: set to true for special numbers like dates
2872 public function formatNum( $number, $nocommafy = false ) {
2873 global $wgTranslateNumerals;
2874 if ( !$nocommafy ) {
2875 $number = $this->commafy( $number );
2876 $s = $this->separatorTransformTable();
2878 $number = strtr( $number, $s );
2882 if ( $wgTranslateNumerals ) {
2883 $s = $this->digitTransformTable();
2885 $number = strtr( $number, $s );
2893 * @param $number string
2896 function parseFormattedNumber( $number ) {
2897 $s = $this->digitTransformTable();
2899 $number = strtr( $number, array_flip( $s ) );
2902 $s = $this->separatorTransformTable();
2904 $number = strtr( $number, array_flip( $s ) );
2907 $number = strtr( $number, array( ',' => '' ) );
2912 * Adds commas to a given number
2917 function commafy( $_ ) {
2918 $digitGroupingPattern = $this->digitGroupingPattern();
2919 if ( $_ === null ) {
2923 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2924 // default grouping is at thousands, use the same for ###,###,### pattern too.
2925 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2927 // Ref: http://cldr.unicode.org/translation/number-patterns
2929 if ( intval( $_ ) < 0 ) {
2930 // For negative numbers apply the algorithm like positive number and add sign.
2932 $_ = substr( $_, 1 );
2934 $numberpart = array();
2935 $decimalpart = array();
2936 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2937 preg_match( "/\d+/", $_, $numberpart );
2938 preg_match( "/\.\d*/", $_, $decimalpart );
2939 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2940 if ( $groupedNumber === $_ ) {
2941 // the string does not have any number part. Eg: .12345
2942 return $sign . $groupedNumber;
2944 $start = $end = strlen( $numberpart[0] );
2945 while ( $start > 0 ) {
2946 $match = $matches[0][$numMatches -1] ;
2947 $matchLen = strlen( $match );
2948 $start = $end - $matchLen;
2952 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2954 if ( $numMatches > 1 ) {
2955 // use the last pattern for the rest of the number
2959 $groupedNumber = "," . $groupedNumber;
2962 return $sign . $groupedNumber;
2968 function digitGroupingPattern() {
2969 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2975 function digitTransformTable() {
2976 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2982 function separatorTransformTable() {
2983 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2987 * Take a list of strings and build a locale-friendly comma-separated
2988 * list, using the local comma-separator message.
2989 * The last two strings are chained with an "and".
2994 function listToText( array $l ) {
2996 $m = count( $l ) - 1;
2998 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3000 for ( $i = $m; $i >= 0; $i-- ) {
3003 } elseif ( $i == $m - 1 ) {
3004 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3006 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3014 * Take a list of strings and build a locale-friendly comma-separated
3015 * list, using the local comma-separator message.
3016 * @param $list array of strings to put in a comma list
3019 function commaList( array $list ) {
3023 array( 'parsemag', 'escapenoentities', 'language' => $this )
3030 * Take a list of strings and build a locale-friendly semicolon-separated
3031 * list, using the local semicolon-separator message.
3032 * @param $list array of strings to put in a semicolon list
3035 function semicolonList( array $list ) {
3038 'semicolon-separator',
3039 array( 'parsemag', 'escapenoentities', 'language' => $this )
3046 * Same as commaList, but separate it with the pipe instead.
3047 * @param $list array of strings to put in a pipe list
3050 function pipeList( array $list ) {
3054 array( 'escapenoentities', 'language' => $this )
3061 * Truncate a string to a specified length in bytes, appending an optional
3062 * string (e.g. for ellipses)
3064 * The database offers limited byte lengths for some columns in the database;
3065 * multi-byte character sets mean we need to ensure that only whole characters
3066 * are included, otherwise broken characters can be passed to the user
3068 * If $length is negative, the string will be truncated from the beginning
3070 * @param $string String to truncate
3071 * @param $length Int: maximum length (including ellipses)
3072 * @param $ellipsis String to append to the truncated text
3073 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3074 * $adjustLength was introduced in 1.18, before that behaved as if false.
3077 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3078 # Use the localized ellipsis character
3079 if ( $ellipsis == '...' ) {
3080 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3082 # Check if there is no need to truncate
3083 if ( $length == 0 ) {
3084 return $ellipsis; // convention
3085 } elseif ( strlen( $string ) <= abs( $length ) ) {
3086 return $string; // no need to truncate
3088 $stringOriginal = $string;
3089 # If ellipsis length is >= $length then we can't apply $adjustLength
3090 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3091 $string = $ellipsis; // this can be slightly unexpected
3092 # Otherwise, truncate and add ellipsis...
3094 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3095 if ( $length > 0 ) {
3096 $length -= $eLength;
3097 $string = substr( $string, 0, $length ); // xyz...
3098 $string = $this->removeBadCharLast( $string );
3099 $string = $string . $ellipsis;
3101 $length +
= $eLength;
3102 $string = substr( $string, $length ); // ...xyz
3103 $string = $this->removeBadCharFirst( $string );
3104 $string = $ellipsis . $string;
3107 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3108 # This check is *not* redundant if $adjustLength, due to the single case where
3109 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3110 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3113 return $stringOriginal;
3118 * Remove bytes that represent an incomplete Unicode character
3119 * at the end of string (e.g. bytes of the char are missing)
3121 * @param $string String
3124 protected function removeBadCharLast( $string ) {
3125 if ( $string != '' ) {
3126 $char = ord( $string[strlen( $string ) - 1] );
3128 if ( $char >= 0xc0 ) {
3129 # We got the first byte only of a multibyte char; remove it.
3130 $string = substr( $string, 0, -1 );
3131 } elseif ( $char >= 0x80 &&
3132 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3133 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3135 # We chopped in the middle of a character; remove it
3143 * Remove bytes that represent an incomplete Unicode character
3144 * at the start of string (e.g. bytes of the char are missing)
3146 * @param $string String
3149 protected function removeBadCharFirst( $string ) {
3150 if ( $string != '' ) {
3151 $char = ord( $string[0] );
3152 if ( $char >= 0x80 && $char < 0xc0 ) {
3153 # We chopped in the middle of a character; remove the whole thing
3154 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3161 * Truncate a string of valid HTML to a specified length in bytes,
3162 * appending an optional string (e.g. for ellipses), and return valid HTML
3164 * This is only intended for styled/linked text, such as HTML with
3165 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3166 * Also, this will not detect things like "display:none" CSS.
3168 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3170 * @param string $text HTML string to truncate
3171 * @param int $length (zero/positive) Maximum length (including ellipses)
3172 * @param string $ellipsis String to append to the truncated text
3175 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3176 # Use the localized ellipsis character
3177 if ( $ellipsis == '...' ) {
3178 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3180 # Check if there is clearly no need to truncate
3181 if ( $length <= 0 ) {
3182 return $ellipsis; // no text shown, nothing to format (convention)
3183 } elseif ( strlen( $text ) <= $length ) {
3184 return $text; // string short enough even *with* HTML (short-circuit)
3187 $dispLen = 0; // innerHTML legth so far
3188 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3189 $tagType = 0; // 0-open, 1-close
3190 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3191 $entityState = 0; // 0-not entity, 1-entity
3192 $tag = $ret = ''; // accumulated tag name, accumulated result string
3193 $openTags = array(); // open tag stack
3194 $maybeState = null; // possible truncation state
3196 $textLen = strlen( $text );
3197 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3198 for ( $pos = 0; true; ++
$pos ) {
3199 # Consider truncation once the display length has reached the maximim.
3200 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3201 # Check that we're not in the middle of a bracket/entity...
3202 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3203 if ( !$testingEllipsis ) {
3204 $testingEllipsis = true;
3205 # Save where we are; we will truncate here unless there turn out to
3206 # be so few remaining characters that truncation is not necessary.
3207 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3208 $maybeState = array( $ret, $openTags ); // save state
3210 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3211 # String in fact does need truncation, the truncation point was OK.
3212 list( $ret, $openTags ) = $maybeState; // reload state
3213 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3214 $ret .= $ellipsis; // add ellipsis
3218 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3220 # Read the next char...
3222 $lastCh = $pos ?
$text[$pos - 1] : '';
3223 $ret .= $ch; // add to result string
3225 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3226 $entityState = 0; // for bad HTML
3227 $bracketState = 1; // tag started (checking for backslash)
3228 } elseif ( $ch == '>' ) {
3229 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3230 $entityState = 0; // for bad HTML
3231 $bracketState = 0; // out of brackets
3232 } elseif ( $bracketState == 1 ) {
3234 $tagType = 1; // close tag (e.g. "</span>")
3236 $tagType = 0; // open tag (e.g. "<span>")
3239 $bracketState = 2; // building tag name
3240 } elseif ( $bracketState == 2 ) {
3244 // Name found (e.g. "<a href=..."), add on tag attributes...
3245 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3247 } elseif ( $bracketState == 0 ) {
3248 if ( $entityState ) {
3251 $dispLen++
; // entity is one displayed char
3254 if ( $neLength == 0 && !$maybeState ) {
3255 // Save state without $ch. We want to *hit* the first
3256 // display char (to get tags) but not *use* it if truncating.
3257 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3260 $entityState = 1; // entity found, (e.g. " ")
3262 $dispLen++
; // this char is displayed
3263 // Add the next $max display text chars after this in one swoop...
3264 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3265 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3266 $dispLen +
= $skipped;
3272 // Close the last tag if left unclosed by bad HTML
3273 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3274 while ( count( $openTags ) > 0 ) {
3275 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3281 * truncateHtml() helper function
3282 * like strcspn() but adds the skipped chars to $ret
3291 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3292 if ( $len === null ) {
3293 $len = -1; // -1 means "no limit" for strcspn
3294 } elseif ( $len < 0 ) {
3298 if ( $start < strlen( $text ) ) {
3299 $skipCount = strcspn( $text, $search, $start, $len );
3300 $ret .= substr( $text, $start, $skipCount );
3306 * truncateHtml() helper function
3307 * (a) push or pop $tag from $openTags as needed
3308 * (b) clear $tag value
3309 * @param &$tag string Current HTML tag name we are looking at
3310 * @param $tagType int (0-open tag, 1-close tag)
3311 * @param $lastCh string Character before the '>' that ended this tag
3312 * @param &$openTags array Open tag stack (not accounting for $tag)
3314 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3315 $tag = ltrim( $tag );
3317 if ( $tagType == 0 && $lastCh != '/' ) {
3318 $openTags[] = $tag; // tag opened (didn't close itself)
3319 } elseif ( $tagType == 1 ) {
3320 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3321 array_pop( $openTags ); // tag closed
3329 * Grammatical transformations, needed for inflected languages
3330 * Invoked by putting {{grammar:case|word}} in a message
3332 * @param $word string
3333 * @param $case string
3336 function convertGrammar( $word, $case ) {
3337 global $wgGrammarForms;
3338 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3339 return $wgGrammarForms[$this->getCode()][$case][$word];
3344 * Get the grammar forms for the content language
3345 * @return array of grammar forms
3348 function getGrammarForms() {
3349 global $wgGrammarForms;
3350 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3351 return $wgGrammarForms[$this->getCode()];
3356 * Provides an alternative text depending on specified gender.
3357 * Usage {{gender:username|masculine|feminine|neutral}}.
3358 * username is optional, in which case the gender of current user is used,
3359 * but only in (some) interface messages; otherwise default gender is used.
3361 * If no forms are given, an empty string is returned. If only one form is
3362 * given, it will be returned unconditionally. These details are implied by
3363 * the caller and cannot be overridden in subclasses.
3365 * If more than one form is given, the default is to use the neutral one
3366 * if it is specified, and to use the masculine one otherwise. These
3367 * details can be overridden in subclasses.
3369 * @param $gender string
3370 * @param $forms array
3374 function gender( $gender, $forms ) {
3375 if ( !count( $forms ) ) {
3378 $forms = $this->preConvertPlural( $forms, 2 );
3379 if ( $gender === 'male' ) {
3382 if ( $gender === 'female' ) {
3385 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3389 * Plural form transformations, needed for some languages.
3390 * For example, there are 3 form of plural in Russian and Polish,
3391 * depending on "count mod 10". See [[w:Plural]]
3392 * For English it is pretty simple.
3394 * Invoked by putting {{plural:count|wordform1|wordform2}}
3395 * or {{plural:count|wordform1|wordform2|wordform3}}
3397 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3399 * @param $count Integer: non-localized number
3400 * @param $forms Array: different plural forms
3401 * @return string Correct form of plural for $count in this language
3403 function convertPlural( $count, $forms ) {
3404 if ( !count( $forms ) ) {
3407 $forms = $this->preConvertPlural( $forms, 2 );
3409 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3413 * Checks that convertPlural was given an array and pads it to requested
3414 * amount of forms by copying the last one.
3416 * @param $count Integer: How many forms should there be at least
3417 * @param $forms Array of forms given to convertPlural
3418 * @return array Padded array of forms or an exception if not an array
3420 protected function preConvertPlural( /* Array */ $forms, $count ) {
3421 while ( count( $forms ) < $count ) {
3422 $forms[] = $forms[count( $forms ) - 1];
3428 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3429 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3430 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3431 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3434 * @param $str String: the validated block duration in English
3435 * @return string Somehow translated block duration
3436 * @see LanguageFi.php for example implementation
3438 function translateBlockExpiry( $str ) {
3439 $duration = SpecialBlock
::getSuggestedDurations( $this );
3440 foreach ( $duration as $show => $value ) {
3441 if ( strcmp( $str, $value ) == 0 ) {
3442 return htmlspecialchars( trim( $show ) );
3446 // Since usually only infinite or indefinite is only on list, so try
3447 // equivalents if still here.
3448 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3449 if ( in_array( $str, $indefs ) ) {
3450 foreach ( $indefs as $val ) {
3451 $show = array_search( $val, $duration, true );
3452 if ( $show !== false ) {
3453 return htmlspecialchars( trim( $show ) );
3457 // If all else fails, return the original string.
3462 * languages like Chinese need to be segmented in order for the diff
3465 * @param $text String
3468 public function segmentForDiff( $text ) {
3473 * and unsegment to show the result
3475 * @param $text String
3478 public function unsegmentForDiff( $text ) {
3483 * Return the LanguageConverter used in the Language
3486 * @return LanguageConverter
3488 public function getConverter() {
3489 return $this->mConverter
;
3493 * convert text to all supported variants
3495 * @param $text string
3498 public function autoConvertToAllVariants( $text ) {
3499 return $this->mConverter
->autoConvertToAllVariants( $text );
3503 * convert text to different variants of a language.
3505 * @param $text string
3508 public function convert( $text ) {
3509 return $this->mConverter
->convert( $text );
3513 * Convert a Title object to a string in the preferred variant
3515 * @param $title Title
3518 public function convertTitle( $title ) {
3519 return $this->mConverter
->convertTitle( $title );
3523 * Check if this is a language with variants
3527 public function hasVariants() {
3528 return sizeof( $this->getVariants() ) > 1;
3532 * Check if the language has the specific variant
3535 * @param $variant string
3538 public function hasVariant( $variant ) {
3539 return (bool)$this->mConverter
->validateVariant( $variant );
3543 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3545 * @param $text string
3548 public function armourMath( $text ) {
3549 return $this->mConverter
->armourMath( $text );
3553 * Perform output conversion on a string, and encode for safe HTML output.
3554 * @param $text String text to be converted
3555 * @param $isTitle Bool whether this conversion is for the article title
3557 * @todo this should get integrated somewhere sane
3559 public function convertHtml( $text, $isTitle = false ) {
3560 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3564 * @param $key string
3567 public function convertCategoryKey( $key ) {
3568 return $this->mConverter
->convertCategoryKey( $key );
3572 * Get the list of variants supported by this language
3573 * see sample implementation in LanguageZh.php
3575 * @return array an array of language codes
3577 public function getVariants() {
3578 return $this->mConverter
->getVariants();
3584 public function getPreferredVariant() {
3585 return $this->mConverter
->getPreferredVariant();
3591 public function getDefaultVariant() {
3592 return $this->mConverter
->getDefaultVariant();
3598 public function getURLVariant() {
3599 return $this->mConverter
->getURLVariant();
3603 * If a language supports multiple variants, it is
3604 * possible that non-existing link in one variant
3605 * actually exists in another variant. this function
3606 * tries to find it. See e.g. LanguageZh.php
3608 * @param $link String: the name of the link
3609 * @param $nt Mixed: the title object of the link
3610 * @param $ignoreOtherCond Boolean: to disable other conditions when
3611 * we need to transclude a template or update a category's link
3612 * @return null the input parameters may be modified upon return
3614 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3615 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3619 * If a language supports multiple variants, converts text
3620 * into an array of all possible variants of the text:
3621 * 'variant' => text in that variant
3623 * @deprecated since 1.17 Use autoConvertToAllVariants()
3625 * @param $text string
3629 public function convertLinkToAllVariants( $text ) {
3630 return $this->mConverter
->convertLinkToAllVariants( $text );
3634 * returns language specific options used by User::getPageRenderHash()
3635 * for example, the preferred language variant
3639 function getExtraHashOptions() {
3640 return $this->mConverter
->getExtraHashOptions();
3644 * For languages that support multiple variants, the title of an
3645 * article may be displayed differently in different variants. this
3646 * function returns the apporiate title defined in the body of the article.
3650 public function getParsedTitle() {
3651 return $this->mConverter
->getParsedTitle();
3655 * Enclose a string with the "no conversion" tag. This is used by
3656 * various functions in the Parser
3658 * @param $text String: text to be tagged for no conversion
3659 * @param $noParse bool
3660 * @return string the tagged text
3662 public function markNoConversion( $text, $noParse = false ) {
3663 return $this->mConverter
->markNoConversion( $text, $noParse );
3667 * A regular expression to match legal word-trailing characters
3668 * which should be merged onto a link of the form [[foo]]bar.
3672 public function linkTrail() {
3673 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3679 function getLangObj() {
3684 * Get the RFC 3066 code for this language object
3688 public function getCode() {
3689 return $this->mCode
;
3693 * Get the code in Bcp47 format which we can use
3694 * inside of html lang="" tags.
3698 public function getHtmlCode() {
3699 if ( is_null( $this->mHtmlCode
) ) {
3700 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3702 return $this->mHtmlCode
;
3706 * @param $code string
3708 public function setCode( $code ) {
3709 $this->mCode
= $code;
3710 // Ensure we don't leave an incorrect html code lying around
3711 $this->mHtmlCode
= null;
3715 * Get the name of a file for a certain language code
3716 * @param $prefix string Prepend this to the filename
3717 * @param $code string Language code
3718 * @param $suffix string Append this to the filename
3719 * @throws MWException
3720 * @return string $prefix . $mangledCode . $suffix
3722 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3723 // Protect against path traversal
3724 if ( !Language
::isValidCode( $code )
3725 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3727 throw new MWException( "Invalid language code \"$code\"" );
3730 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3734 * Get the language code from a file name. Inverse of getFileName()
3735 * @param $filename string $prefix . $languageCode . $suffix
3736 * @param $prefix string Prefix before the language code
3737 * @param $suffix string Suffix after the language code
3738 * @return string Language code, or false if $prefix or $suffix isn't found
3740 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3742 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3743 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3744 if ( !count( $m ) ) {
3747 return str_replace( '_', '-', strtolower( $m[1] ) );
3751 * @param $code string
3754 public static function getMessagesFileName( $code ) {
3756 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3757 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3762 * @param $code string
3765 public static function getClassFileName( $code ) {
3767 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3771 * Get the first fallback for a given language.
3773 * @param $code string
3775 * @return bool|string
3777 public static function getFallbackFor( $code ) {
3778 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3781 $fallbacks = self
::getFallbacksFor( $code );
3782 $first = array_shift( $fallbacks );
3788 * Get the ordered list of fallback languages.
3791 * @param $code string Language code
3794 public static function getFallbacksFor( $code ) {
3795 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3798 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3799 $v = array_map( 'trim', explode( ',', $v ) );
3800 if ( $v[count( $v ) - 1] !== 'en' ) {
3808 * Get all messages for a given language
3809 * WARNING: this may take a long time. If you just need all message *keys*
3810 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3812 * @param $code string
3816 public static function getMessagesFor( $code ) {
3817 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3821 * Get a message for a given language
3823 * @param $key string
3824 * @param $code string
3828 public static function getMessageFor( $key, $code ) {
3829 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3833 * Get all message keys for a given language. This is a faster alternative to
3834 * array_keys( Language::getMessagesFor( $code ) )
3837 * @param $code string Language code
3838 * @return array of message keys (strings)
3840 public static function getMessageKeysFor( $code ) {
3841 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3848 function fixVariableInNamespace( $talk ) {
3849 if ( strpos( $talk, '$1' ) === false ) {
3853 global $wgMetaNamespace;
3854 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3856 # Allow grammar transformations
3857 # Allowing full message-style parsing would make simple requests
3858 # such as action=raw much more expensive than they need to be.
3859 # This will hopefully cover most cases.
3860 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3861 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3862 return str_replace( ' ', '_', $talk );
3869 function replaceGrammarInNamespace( $m ) {
3870 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3874 * @throws MWException
3877 static function getCaseMaps() {
3878 static $wikiUpperChars, $wikiLowerChars;
3879 if ( isset( $wikiUpperChars ) ) {
3880 return array( $wikiUpperChars, $wikiLowerChars );
3883 wfProfileIn( __METHOD__
);
3884 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3885 if ( $arr === false ) {
3886 throw new MWException(
3887 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3889 $wikiUpperChars = $arr['wikiUpperChars'];
3890 $wikiLowerChars = $arr['wikiLowerChars'];
3891 wfProfileOut( __METHOD__
);
3892 return array( $wikiUpperChars, $wikiLowerChars );
3896 * Decode an expiry (block, protection, etc) which has come from the DB
3898 * @FIXME: why are we returnings DBMS-dependent strings???
3900 * @param $expiry String: Database expiry String
3901 * @param $format Bool|Int true to process using language functions, or TS_ constant
3902 * to return the expiry in a given timestamp
3905 public function formatExpiry( $expiry, $format = true ) {
3906 static $infinity, $infinityMsg;
3907 if ( $infinity === null ) {
3908 $infinityMsg = wfMessage( 'infiniteblock' );
3909 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3912 if ( $expiry == '' ||
$expiry == $infinity ) {
3913 return $format === true
3917 return $format === true
3918 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3919 : wfTimestamp( $format, $expiry );
3925 * @param $seconds int|float
3926 * @param $format Array Optional
3927 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3928 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3929 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3930 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3933 function formatTimePeriod( $seconds, $format = array() ) {
3934 if ( !is_array( $format ) ) {
3935 $format = array( 'avoid' => $format ); // For backwards compatibility
3937 if ( !isset( $format['avoid'] ) ) {
3938 $format['avoid'] = false;
3940 if ( !isset( $format['noabbrevs' ] ) ) {
3941 $format['noabbrevs'] = false;
3943 $secondsMsg = wfMessage(
3944 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3945 $minutesMsg = wfMessage(
3946 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3947 $hoursMsg = wfMessage(
3948 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3949 $daysMsg = wfMessage(
3950 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3952 if ( round( $seconds * 10 ) < 100 ) {
3953 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3954 $s = $secondsMsg->params( $s )->text();
3955 } elseif ( round( $seconds ) < 60 ) {
3956 $s = $this->formatNum( round( $seconds ) );
3957 $s = $secondsMsg->params( $s )->text();
3958 } elseif ( round( $seconds ) < 3600 ) {
3959 $minutes = floor( $seconds / 60 );
3960 $secondsPart = round( fmod( $seconds, 60 ) );
3961 if ( $secondsPart == 60 ) {
3965 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3967 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3968 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3969 $hours = floor( $seconds / 3600 );
3970 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3971 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3972 if ( $secondsPart == 60 ) {
3976 if ( $minutes == 60 ) {
3980 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3982 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3983 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3984 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3987 $days = floor( $seconds / 86400 );
3988 if ( $format['avoid'] === 'avoidminutes' ) {
3989 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3990 if ( $hours == 24 ) {
3994 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3996 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3997 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3998 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3999 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4000 if ( $minutes == 60 ) {
4004 if ( $hours == 24 ) {
4008 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4010 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4012 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4014 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4016 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4023 * Format a bitrate for output, using an appropriate
4024 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4026 * This use base 1000. For base 1024 use formatSize(), for another base
4027 * see formatComputingNumbers()
4032 function formatBitrate( $bps ) {
4033 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4037 * @param $size int Size of the unit
4038 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4039 * @param $messageKey string Message key to be uesd
4042 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4044 return str_replace( '$1', $this->formatNum( $size ),
4045 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4048 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4051 $maxIndex = count( $sizes ) - 1;
4052 while ( $size >= $boundary && $index < $maxIndex ) {
4057 // For small sizes no decimal places necessary
4060 // For MB and bigger two decimal places are smarter
4063 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4065 $size = round( $size, $round );
4066 $text = $this->getMessageFromDB( $msg );
4067 return str_replace( '$1', $this->formatNum( $size ), $text );
4071 * Format a size in bytes for output, using an appropriate
4072 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4074 * This method use base 1024. For base 1000 use formatBitrate(), for
4075 * another base see formatComputingNumbers()
4077 * @param $size int Size to format
4078 * @return string Plain text (not HTML)
4080 function formatSize( $size ) {
4081 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4085 * Make a list item, used by various special pages
4087 * @param $page String Page link
4088 * @param $details String Text between brackets
4089 * @param $oppositedm Boolean Add the direction mark opposite to your
4090 * language, to display text properly
4093 function specialList( $page, $details, $oppositedm = true ) {
4094 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4095 $this->getDirMark();
4096 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4097 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4098 return $page . $details;
4102 * Generate (prev x| next x) (20|50|100...) type links for paging
4104 * @param $title Title object to link
4105 * @param $offset Integer offset parameter
4106 * @param $limit Integer limit parameter
4107 * @param $query String optional URL query parameter string
4108 * @param $atend Bool optional param for specified if this is the last page
4111 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4112 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4114 # Make 'previous' link
4115 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4116 if ( $offset > 0 ) {
4117 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4118 $query, $prev, 'prevn-title', 'mw-prevlink' );
4120 $plink = htmlspecialchars( $prev );
4124 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4126 $nlink = htmlspecialchars( $next );
4128 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4129 $query, $next, 'prevn-title', 'mw-nextlink' );
4132 # Make links to set number of items per page
4133 $numLinks = array();
4134 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4135 $numLinks[] = $this->numLink( $title, $offset, $num,
4136 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4139 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4140 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4144 * Helper function for viewPrevNext() that generates links
4146 * @param $title Title object to link
4147 * @param $offset Integer offset parameter
4148 * @param $limit Integer limit parameter
4149 * @param $query Array extra query parameters
4150 * @param $link String text to use for the link; will be escaped
4151 * @param $tooltipMsg String name of the message to use as tooltip
4152 * @param $class String value of the "class" attribute of the link
4153 * @return String HTML fragment
4155 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4156 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4157 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4158 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4159 'title' => $tooltip, 'class' => $class ), $link );
4163 * Get the conversion rule title, if any.
4167 public function getConvRuleTitle() {
4168 return $this->mConverter
->getConvRuleTitle();