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 mb_internal_encoding( 'UTF-8' );
25 * a fake language converter
35 function __construct( $langobj ) { $this->mLang
= $langobj; }
36 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
37 function convert( $t ) { return $t; }
38 function convertTo( $text, $variant ) { return $text; }
39 function convertTitle( $t ) { return $t->getPrefixedText(); }
40 function getVariants() { return array( $this->mLang
->getCode() ); }
41 function getPreferredVariant() { return $this->mLang
->getCode(); }
42 function getDefaultVariant() { return $this->mLang
->getCode(); }
43 function getURLVariant() { return ''; }
44 function getConvRuleTitle() { return false; }
45 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
46 function getExtraHashOptions() { return ''; }
47 function getParsedTitle() { return ''; }
48 function markNoConversion( $text, $noParse = false ) { return $text; }
49 function convertCategoryKey( $key ) { return $key; }
50 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
51 function armourMath( $text ) { return $text; }
55 * Internationalisation code
61 * @var LanguageConverter
65 var $mVariants, $mCode, $mLoaded = false;
66 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 private $mHtmlCode = null;
69 var $dateFormatStrings = array();
70 var $mExtendedSpecialPageAliases;
72 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
75 * ReplacementArray object caches
77 var $transformData = array();
80 * @var LocalisationCache
82 static public $dataCache;
84 static public $mLangObjCache = array();
86 static public $mWeekdayMsgs = array(
87 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
91 static public $mWeekdayAbbrevMsgs = array(
92 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
95 static public $mMonthMsgs = array(
96 'january', 'february', 'march', 'april', 'may_long', 'june',
97 'july', 'august', 'september', 'october', 'november',
100 static public $mMonthGenMsgs = array(
101 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
102 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
105 static public $mMonthAbbrevMsgs = array(
106 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
107 'sep', 'oct', 'nov', 'dec'
110 static public $mIranianCalendarMonthMsgs = array(
111 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
112 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
113 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
114 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
117 static public $mHebrewCalendarMonthMsgs = array(
118 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
119 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
120 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
121 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
122 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
125 static public $mHebrewCalendarMonthGenMsgs = array(
126 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
127 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
128 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
129 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
130 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
133 static public $mHijriCalendarMonthMsgs = array(
134 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
135 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
136 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
137 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
144 static public $durationIntervals = array(
145 'millennia' => 31557600000,
146 'centuries' => 3155760000,
147 'decades' => 315576000,
148 'years' => 31557600, // 86400 * 365.25
157 * Get a cached language object for a given language code
158 * @param $code String
161 static function factory( $code ) {
162 if ( !isset( self
::$mLangObjCache[$code] ) ) {
163 if ( count( self
::$mLangObjCache ) > 10 ) {
164 // Don't keep a billion objects around, that's stupid.
165 self
::$mLangObjCache = array();
167 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
169 return self
::$mLangObjCache[$code];
173 * Create a language object for a given language code
174 * @param $code String
175 * @throws MWException
178 protected static function newFromCode( $code ) {
179 // Protect against path traversal below
180 if ( !Language
::isValidCode( $code )
181 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
183 throw new MWException( "Invalid language code \"$code\"" );
186 if ( !Language
::isValidBuiltInCode( $code ) ) {
187 // It's not possible to customise this code with class files, so
188 // just return a Language object. This is to support uselang= hacks.
189 $lang = new Language
;
190 $lang->setCode( $code );
194 // Check if there is a language class for the code
195 $class = self
::classFromCode( $code );
196 self
::preloadLanguageClass( $class );
197 if ( MWInit
::classExists( $class ) ) {
202 // Keep trying the fallback list until we find an existing class
203 $fallbacks = Language
::getFallbacksFor( $code );
204 foreach ( $fallbacks as $fallbackCode ) {
205 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
206 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
209 $class = self
::classFromCode( $fallbackCode );
210 self
::preloadLanguageClass( $class );
211 if ( MWInit
::classExists( $class ) ) {
212 $lang = Language
::newFromCode( $fallbackCode );
213 $lang->setCode( $code );
218 throw new MWException( "Invalid fallback sequence for language '$code'" );
222 * Returns true if a language code string is of a valid form, whether or
223 * not it exists. This includes codes which are used solely for
224 * customisation via the MediaWiki namespace.
226 * @param $code string
230 public static function isValidCode( $code ) {
232 strcspn( $code, ":/\\\000" ) === strlen( $code )
233 && !preg_match( Title
::getTitleInvalidRegex(), $code );
237 * Returns true if a language code is of a valid form for the purposes of
238 * internal customisation of MediaWiki, via Messages*.php.
240 * @param $code string
245 public static function isValidBuiltInCode( $code ) {
247 if( !is_string($code) ) {
248 $type = gettype( $code );
249 if( $type === 'object' ) {
250 $addmsg = " of class " . get_class( $code );
254 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
257 return preg_match( '/^[a-z0-9-]+$/i', $code );
262 * @return String Name of the language class
264 public static function classFromCode( $code ) {
265 if ( $code == 'en' ) {
268 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
273 * Includes language class files
275 * @param $class string Name of the language class
277 public static function preloadLanguageClass( $class ) {
280 if ( $class === 'Language' ) {
284 if ( !defined( 'MW_COMPILED' ) ) {
285 // Preload base classes to work around APC/PHP5 bug
286 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
287 include_once( "$IP/languages/classes/$class.deps.php" );
289 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
290 include_once( "$IP/languages/classes/$class.php" );
296 * Get the LocalisationCache instance
298 * @return LocalisationCache
300 public static function getLocalisationCache() {
301 if ( is_null( self
::$dataCache ) ) {
302 global $wgLocalisationCacheConf;
303 $class = $wgLocalisationCacheConf['class'];
304 self
::$dataCache = new $class( $wgLocalisationCacheConf );
306 return self
::$dataCache;
309 function __construct() {
310 $this->mConverter
= new FakeConverter( $this );
311 // Set the code to the name of the descendant
312 if ( get_class( $this ) == 'Language' ) {
315 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
317 self
::getLocalisationCache();
321 * Reduce memory usage
323 function __destruct() {
324 foreach ( $this as $name => $value ) {
325 unset( $this->$name );
330 * Hook which will be called if this is the content language.
331 * Descendants can use this to register hook functions or modify globals
333 function initContLang() { }
336 * Same as getFallbacksFor for current language.
338 * @deprecated in 1.19
340 function getFallbackLanguageCode() {
341 wfDeprecated( __METHOD__
);
342 return self
::getFallbackFor( $this->mCode
);
349 function getFallbackLanguages() {
350 return self
::getFallbacksFor( $this->mCode
);
354 * Exports $wgBookstoreListEn
357 function getBookstoreList() {
358 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
364 public function getNamespaces() {
365 if ( is_null( $this->namespaceNames
) ) {
366 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
368 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
369 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
371 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
373 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
374 if ( $wgMetaNamespaceTalk ) {
375 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
377 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
378 $this->namespaceNames
[NS_PROJECT_TALK
] =
379 $this->fixVariableInNamespace( $talk );
382 # Sometimes a language will be localised but not actually exist on this wiki.
383 foreach ( $this->namespaceNames
as $key => $text ) {
384 if ( !isset( $validNamespaces[$key] ) ) {
385 unset( $this->namespaceNames
[$key] );
389 # The above mixing may leave namespaces out of canonical order.
390 # Re-order by namespace ID number...
391 ksort( $this->namespaceNames
);
393 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
395 return $this->namespaceNames
;
399 * Arbitrarily set all of the namespace names at once. Mainly used for testing
400 * @param $namespaces Array of namespaces (id => name)
402 public function setNamespaces( array $namespaces ) {
403 $this->namespaceNames
= $namespaces;
407 * A convenience function that returns the same thing as
408 * getNamespaces() except with the array values changed to ' '
409 * where it found '_', useful for producing output to be displayed
410 * e.g. in <select> forms.
414 function getFormattedNamespaces() {
415 $ns = $this->getNamespaces();
416 foreach ( $ns as $k => $v ) {
417 $ns[$k] = strtr( $v, '_', ' ' );
423 * Get a namespace value by key
425 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
426 * echo $mw_ns; // prints 'MediaWiki'
429 * @param $index Int: the array key of the namespace to return
430 * @return mixed, string if the namespace value exists, otherwise false
432 function getNsText( $index ) {
433 $ns = $this->getNamespaces();
434 return isset( $ns[$index] ) ?
$ns[$index] : false;
438 * A convenience function that returns the same thing as
439 * getNsText() except with '_' changed to ' ', useful for
442 * @param $index string
446 function getFormattedNsText( $index ) {
447 $ns = $this->getNsText( $index );
448 return strtr( $ns, '_', ' ' );
452 * Returns gender-dependent namespace alias if available.
453 * @param $index Int: namespace index
454 * @param $gender String: gender key (male, female... )
458 function getGenderNsText( $index, $gender ) {
459 global $wgExtraGenderNamespaces;
461 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
462 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
466 * Whether this language makes distinguishes genders for example in
471 function needsGenderDistinction() {
472 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
473 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
474 // $wgExtraGenderNamespaces overrides everything
476 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
477 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
478 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
481 // Check what is in i18n files
482 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
483 return count( $aliases ) > 0;
488 * Get a namespace key by value, case insensitive.
489 * Only matches namespace names for the current language, not the
490 * canonical ones defined in Namespace.php.
492 * @param $text String
493 * @return mixed An integer if $text is a valid value otherwise false
495 function getLocalNsIndex( $text ) {
496 $lctext = $this->lc( $text );
497 $ids = $this->getNamespaceIds();
498 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
504 function getNamespaceAliases() {
505 if ( is_null( $this->namespaceAliases
) ) {
506 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
510 foreach ( $aliases as $name => $index ) {
511 if ( $index === NS_PROJECT_TALK
) {
512 unset( $aliases[$name] );
513 $name = $this->fixVariableInNamespace( $name );
514 $aliases[$name] = $index;
519 global $wgExtraGenderNamespaces;
520 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
521 foreach ( $genders as $index => $forms ) {
522 foreach ( $forms as $alias ) {
523 $aliases[$alias] = $index;
527 $this->namespaceAliases
= $aliases;
529 return $this->namespaceAliases
;
535 function getNamespaceIds() {
536 if ( is_null( $this->mNamespaceIds
) ) {
537 global $wgNamespaceAliases;
538 # Put namespace names and aliases into a hashtable.
539 # If this is too slow, then we should arrange it so that it is done
540 # before caching. The catch is that at pre-cache time, the above
541 # class-specific fixup hasn't been done.
542 $this->mNamespaceIds
= array();
543 foreach ( $this->getNamespaces() as $index => $name ) {
544 $this->mNamespaceIds
[$this->lc( $name )] = $index;
546 foreach ( $this->getNamespaceAliases() as $name => $index ) {
547 $this->mNamespaceIds
[$this->lc( $name )] = $index;
549 if ( $wgNamespaceAliases ) {
550 foreach ( $wgNamespaceAliases as $name => $index ) {
551 $this->mNamespaceIds
[$this->lc( $name )] = $index;
555 return $this->mNamespaceIds
;
559 * Get a namespace key by value, case insensitive. Canonical namespace
560 * names override custom ones defined for the current language.
562 * @param $text String
563 * @return mixed An integer if $text is a valid value otherwise false
565 function getNsIndex( $text ) {
566 $lctext = $this->lc( $text );
567 $ns = MWNamespace
::getCanonicalIndex( $lctext );
568 if ( $ns !== null ) {
571 $ids = $this->getNamespaceIds();
572 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
576 * short names for language variants used for language conversion links.
578 * @param $code String
579 * @param $usemsg bool Use the "variantname-xyz" message if it exists
582 function getVariantname( $code, $usemsg = true ) {
583 $msg = "variantname-$code";
584 if ( $usemsg && wfMessage( $msg )->exists() ) {
585 return $this->getMessageFromDB( $msg );
587 $name = self
::fetchLanguageName( $code );
589 return $name; # if it's defined as a language name, show that
591 # otherwise, output the language code
597 * @param $name string
600 function specialPage( $name ) {
601 $aliases = $this->getSpecialPageAliases();
602 if ( isset( $aliases[$name][0] ) ) {
603 $name = $aliases[$name][0];
605 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
611 function getQuickbarSettings() {
613 $this->getMessage( 'qbsettings-none' ),
614 $this->getMessage( 'qbsettings-fixedleft' ),
615 $this->getMessage( 'qbsettings-fixedright' ),
616 $this->getMessage( 'qbsettings-floatingleft' ),
617 $this->getMessage( 'qbsettings-floatingright' ),
618 $this->getMessage( 'qbsettings-directionality' )
625 function getDatePreferences() {
626 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
632 function getDateFormats() {
633 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
637 * @return array|string
639 function getDefaultDateFormat() {
640 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
641 if ( $df === 'dmy or mdy' ) {
642 global $wgAmericanDates;
643 return $wgAmericanDates ?
'mdy' : 'dmy';
652 function getDatePreferenceMigrationMap() {
653 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
660 function getImageFile( $image ) {
661 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
667 function getExtraUserToggles() {
668 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
675 function getUserToggle( $tog ) {
676 return $this->getMessageFromDB( "tog-$tog" );
680 * Get native language names, indexed by code.
681 * Only those defined in MediaWiki, no other data like CLDR.
682 * If $customisedOnly is true, only returns codes with a messages file
684 * @param $customisedOnly bool
687 * @deprecated in 1.20, use fetchLanguageNames()
689 public static function getLanguageNames( $customisedOnly = false ) {
690 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
694 * Get translated language names. This is done on best effort and
695 * by default this is exactly the same as Language::getLanguageNames.
696 * The CLDR extension provides translated names.
697 * @param $code String Language code.
698 * @return Array language code => language name
700 * @deprecated in 1.20, use fetchLanguageNames()
702 public static function getTranslatedLanguageNames( $code ) {
703 return self
::fetchLanguageNames( $code, 'all' );
707 * Get an array of language names, indexed by code.
708 * @param $inLanguage null|string: Code of language in which to return the names
709 * Use null for autonyms (native names)
710 * @param $include string:
711 * 'all' all available languages
712 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
713 * 'mwfile' only if the language is in 'mw' *and* has a message file
714 * @return array: language code => language name
717 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
718 global $wgExtraLanguageNames;
719 static $coreLanguageNames;
721 if ( $coreLanguageNames === null ) {
722 include( MWInit
::compiledPath( 'languages/Names.php' ) );
728 # TODO: also include when $inLanguage is null, when this code is more efficient
729 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
732 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
733 foreach ( $mwNames as $mwCode => $mwName ) {
734 # - Prefer own MediaWiki native name when not using the hook
735 # TODO: prefer it always to make it consistent, but casing is different in CLDR
736 # - For other names just add if not added through the hook
737 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
738 $names[$mwCode] = $mwName;
742 if ( $include === 'all' ) {
747 $coreCodes = array_keys( $mwNames );
748 foreach( $coreCodes as $coreCode ) {
749 $returnMw[$coreCode] = $names[$coreCode];
752 if( $include === 'mwfile' ) {
753 $namesMwFile = array();
754 # We do this using a foreach over the codes instead of a directory
755 # loop so that messages files in extensions will work correctly.
756 foreach ( $returnMw as $code => $value ) {
757 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
758 $namesMwFile[$code] = $names[$code];
763 # 'mw' option; default if it's not one of the other two options (all/mwfile)
768 * @param $code string: The code of the language for which to get the name
769 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
770 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
771 * @return string: Language name or empty
774 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
775 $array = self
::fetchLanguageNames( $inLanguage, $include );
776 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
780 * Get a message from the MediaWiki namespace.
782 * @param $msg String: message name
785 function getMessageFromDB( $msg ) {
786 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
790 * Get the native language name of $code.
791 * Only if defined in MediaWiki, no other data like CLDR.
792 * @param $code string
794 * @deprecated in 1.20, use fetchLanguageName()
796 function getLanguageName( $code ) {
797 return self
::fetchLanguageName( $code );
804 function getMonthName( $key ) {
805 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
811 function getMonthNamesArray() {
812 $monthNames = array( '' );
813 for ( $i = 1; $i < 13; $i++
) {
814 $monthNames[] = $this->getMonthName( $i );
823 function getMonthNameGen( $key ) {
824 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
831 function getMonthAbbreviation( $key ) {
832 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
838 function getMonthAbbreviationsArray() {
839 $monthNames = array( '' );
840 for ( $i = 1; $i < 13; $i++
) {
841 $monthNames[] = $this->getMonthAbbreviation( $i );
850 function getWeekdayName( $key ) {
851 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
858 function getWeekdayAbbreviation( $key ) {
859 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
866 function getIranianCalendarMonthName( $key ) {
867 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
874 function getHebrewCalendarMonthName( $key ) {
875 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
882 function getHebrewCalendarMonthNameGen( $key ) {
883 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
890 function getHijriCalendarMonthName( $key ) {
891 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
895 * This is a workalike of PHP's date() function, but with better
896 * internationalisation, a reduced set of format characters, and a better
899 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
900 * PHP manual for definitions. There are a number of extensions, which
903 * xn Do not translate digits of the next numeric format character
904 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
905 * xr Use roman numerals for the next numeric format character
906 * xh Use hebrew numerals for the next numeric format character
908 * xg Genitive month name
910 * xij j (day number) in Iranian calendar
911 * xiF F (month name) in Iranian calendar
912 * xin n (month number) in Iranian calendar
913 * xiy y (two digit year) in Iranian calendar
914 * xiY Y (full year) in Iranian calendar
916 * xjj j (day number) in Hebrew calendar
917 * xjF F (month name) in Hebrew calendar
918 * xjt t (days in month) in Hebrew calendar
919 * xjx xg (genitive month name) in Hebrew calendar
920 * xjn n (month number) in Hebrew calendar
921 * xjY Y (full year) in Hebrew calendar
923 * xmj j (day number) in Hijri calendar
924 * xmF F (month name) in Hijri calendar
925 * xmn n (month number) in Hijri calendar
926 * xmY Y (full year) in Hijri calendar
928 * xkY Y (full year) in Thai solar calendar. Months and days are
929 * identical to the Gregorian calendar
930 * xoY Y (full year) in Minguo calendar or Juche year.
931 * Months and days are identical to the
933 * xtY Y (full year) in Japanese nengo. Months and days are
934 * identical to the Gregorian calendar
936 * Characters enclosed in double quotes will be considered literal (with
937 * the quotes themselves removed). Unmatched quotes will be considered
938 * literal quotes. Example:
940 * "The month is" F => The month is January
943 * Backslash escaping is also supported.
945 * Input timestamp is assumed to be pre-normalized to the desired local
948 * @param $format String
949 * @param $ts String: 14-character timestamp
952 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
956 function sprintfDate( $format, $ts ) {
969 for ( $p = 0; $p < strlen( $format ); $p++
) {
972 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
973 $code .= $format[++
$p];
976 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
977 $code .= $format[++
$p];
988 $rawToggle = !$rawToggle;
997 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1000 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1001 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1004 $num = substr( $ts, 6, 2 );
1007 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1008 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1011 $num = intval( substr( $ts, 6, 2 ) );
1015 $iranian = self
::tsToIranian( $ts );
1021 $hijri = self
::tsToHijri( $ts );
1027 $hebrew = self
::tsToHebrew( $ts );
1033 $unix = wfTimestamp( TS_UNIX
, $ts );
1035 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1039 $unix = wfTimestamp( TS_UNIX
, $ts );
1041 $w = gmdate( 'w', $unix );
1046 $unix = wfTimestamp( TS_UNIX
, $ts );
1048 $num = gmdate( 'w', $unix );
1052 $unix = wfTimestamp( TS_UNIX
, $ts );
1054 $num = gmdate( 'z', $unix );
1058 $unix = wfTimestamp( TS_UNIX
, $ts );
1060 $num = gmdate( 'W', $unix );
1063 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1067 $iranian = self
::tsToIranian( $ts );
1069 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1073 $hijri = self
::tsToHijri( $ts );
1075 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1079 $hebrew = self
::tsToHebrew( $ts );
1081 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1084 $num = substr( $ts, 4, 2 );
1087 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1090 $num = intval( substr( $ts, 4, 2 ) );
1094 $iranian = self
::tsToIranian( $ts );
1100 $hijri = self
::tsToHijri ( $ts );
1106 $hebrew = self
::tsToHebrew( $ts );
1112 $unix = wfTimestamp( TS_UNIX
, $ts );
1114 $num = gmdate( 't', $unix );
1118 $hebrew = self
::tsToHebrew( $ts );
1124 $unix = wfTimestamp( TS_UNIX
, $ts );
1126 $num = gmdate( 'L', $unix );
1130 $unix = wfTimestamp( TS_UNIX
, $ts );
1132 $num = gmdate( 'o', $unix );
1135 $num = substr( $ts, 0, 4 );
1139 $iranian = self
::tsToIranian( $ts );
1145 $hijri = self
::tsToHijri( $ts );
1151 $hebrew = self
::tsToHebrew( $ts );
1157 $thai = self
::tsToYear( $ts, 'thai' );
1163 $minguo = self
::tsToYear( $ts, 'minguo' );
1169 $tenno = self
::tsToYear( $ts, 'tenno' );
1174 $num = substr( $ts, 2, 2 );
1178 $iranian = self
::tsToIranian( $ts );
1180 $num = substr( $iranian[0], -2 );
1183 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1186 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1189 $h = substr( $ts, 8, 2 );
1190 $num = $h %
12 ?
$h %
12 : 12;
1193 $num = intval( substr( $ts, 8, 2 ) );
1196 $h = substr( $ts, 8, 2 );
1197 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1200 $num = substr( $ts, 8, 2 );
1203 $num = substr( $ts, 10, 2 );
1206 $num = substr( $ts, 12, 2 );
1210 $unix = wfTimestamp( TS_UNIX
, $ts );
1212 $s .= gmdate( 'c', $unix );
1216 $unix = wfTimestamp( TS_UNIX
, $ts );
1218 $s .= gmdate( 'r', $unix );
1222 $unix = wfTimestamp( TS_UNIX
, $ts );
1227 # Backslash escaping
1228 if ( $p < strlen( $format ) - 1 ) {
1229 $s .= $format[++
$p];
1236 if ( $p < strlen( $format ) - 1 ) {
1237 $endQuote = strpos( $format, '"', $p +
1 );
1238 if ( $endQuote === false ) {
1239 # No terminating quote, assume literal "
1242 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1246 # Quote at end of string, assume literal "
1253 if ( $num !== false ) {
1254 if ( $rawToggle ||
$raw ) {
1257 } elseif ( $roman ) {
1258 $s .= self
::romanNumeral( $num );
1260 } elseif ( $hebrewNum ) {
1261 $s .= self
::hebrewNumeral( $num );
1264 $s .= $this->formatNum( $num, true );
1271 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1272 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1275 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1276 * Gregorian dates to Iranian dates. Originally written in C, it
1277 * is released under the terms of GNU Lesser General Public
1278 * License. Conversion to PHP was performed by Niklas Laxström.
1280 * Link: http://www.farsiweb.info/jalali/jalali.c
1286 private static function tsToIranian( $ts ) {
1287 $gy = substr( $ts, 0, 4 ) -1600;
1288 $gm = substr( $ts, 4, 2 ) -1;
1289 $gd = substr( $ts, 6, 2 ) -1;
1291 # Days passed from the beginning (including leap years)
1293 +
floor( ( $gy +
3 ) / 4 )
1294 - floor( ( $gy +
99 ) / 100 )
1295 +
floor( ( $gy +
399 ) / 400 );
1297 // Add days of the past months of this year
1298 for ( $i = 0; $i < $gm; $i++
) {
1299 $gDayNo +
= self
::$GREG_DAYS[$i];
1303 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1307 // Days passed in current month
1308 $gDayNo +
= (int)$gd;
1310 $jDayNo = $gDayNo - 79;
1312 $jNp = floor( $jDayNo / 12053 );
1315 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1318 if ( $jDayNo >= 366 ) {
1319 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1320 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1323 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1324 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1330 return array( $jy, $jm, $jd );
1334 * Converting Gregorian dates to Hijri dates.
1336 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1338 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1344 private static function tsToHijri( $ts ) {
1345 $year = substr( $ts, 0, 4 );
1346 $month = substr( $ts, 4, 2 );
1347 $day = substr( $ts, 6, 2 );
1355 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1356 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1359 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1360 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1361 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1364 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1365 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1368 $zl = $zjd -1948440 +
10632;
1369 $zn = (int)( ( $zl - 1 ) / 10631 );
1370 $zl = $zl - 10631 * $zn +
354;
1371 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1372 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1373 $zm = (int)( ( 24 * $zl ) / 709 );
1374 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1375 $zy = 30 * $zn +
$zj - 30;
1377 return array( $zy, $zm, $zd );
1381 * Converting Gregorian dates to Hebrew dates.
1383 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1384 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1385 * to translate the relevant functions into PHP and release them under
1388 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1389 * and Adar II is 14. In a non-leap year, Adar is 6.
1395 private static function tsToHebrew( $ts ) {
1397 $year = substr( $ts, 0, 4 );
1398 $month = substr( $ts, 4, 2 );
1399 $day = substr( $ts, 6, 2 );
1401 # Calculate Hebrew year
1402 $hebrewYear = $year +
3760;
1404 # Month number when September = 1, August = 12
1406 if ( $month > 12 ) {
1413 # Calculate day of year from 1 September
1415 for ( $i = 1; $i < $month; $i++
) {
1419 # Check if the year is leap
1420 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1423 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1430 # Calculate the start of the Hebrew year
1431 $start = self
::hebrewYearStart( $hebrewYear );
1433 # Calculate next year's start
1434 if ( $dayOfYear <= $start ) {
1435 # Day is before the start of the year - it is the previous year
1437 $nextStart = $start;
1441 # Add days since previous year's 1 September
1443 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1447 # Start of the new (previous) year
1448 $start = self
::hebrewYearStart( $hebrewYear );
1451 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1454 # Calculate Hebrew day of year
1455 $hebrewDayOfYear = $dayOfYear - $start;
1457 # Difference between year's days
1458 $diff = $nextStart - $start;
1459 # Add 12 (or 13 for leap years) days to ignore the difference between
1460 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1461 # difference is only about the year type
1462 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1468 # Check the year pattern, and is leap year
1469 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1470 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1471 # and non-leap years
1472 $yearPattern = $diff %
30;
1473 # Check if leap year
1474 $isLeap = $diff >= 30;
1476 # Calculate day in the month from number of day in the Hebrew year
1477 # Don't check Adar - if the day is not in Adar, we will stop before;
1478 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1479 $hebrewDay = $hebrewDayOfYear;
1482 while ( $hebrewMonth <= 12 ) {
1483 # Calculate days in this month
1484 if ( $isLeap && $hebrewMonth == 6 ) {
1485 # Adar in a leap year
1487 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1489 if ( $hebrewDay <= $days ) {
1493 # Subtract the days of Adar I
1494 $hebrewDay -= $days;
1497 if ( $hebrewDay <= $days ) {
1503 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1504 # Cheshvan in a complete year (otherwise as the rule below)
1506 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1507 # Kislev in an incomplete year (otherwise as the rule below)
1510 # Odd months have 30 days, even have 29
1511 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1513 if ( $hebrewDay <= $days ) {
1514 # In the current month
1517 # Subtract the days of the current month
1518 $hebrewDay -= $days;
1519 # Try in the next month
1524 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1528 * This calculates the Hebrew year start, as days since 1 September.
1529 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1530 * Used for Hebrew date.
1536 private static function hebrewYearStart( $year ) {
1537 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1538 $b = intval( ( $year - 1 ) %
4 );
1539 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1543 $Mar = intval( $m );
1549 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1550 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1552 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1554 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1558 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1563 * Algorithm to convert Gregorian dates to Thai solar dates,
1564 * Minguo dates or Minguo dates.
1566 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1567 * http://en.wikipedia.org/wiki/Minguo_calendar
1568 * http://en.wikipedia.org/wiki/Japanese_era_name
1570 * @param $ts String: 14-character timestamp
1571 * @param $cName String: calender name
1572 * @return Array: converted year, month, day
1574 private static function tsToYear( $ts, $cName ) {
1575 $gy = substr( $ts, 0, 4 );
1576 $gm = substr( $ts, 4, 2 );
1577 $gd = substr( $ts, 6, 2 );
1579 if ( !strcmp( $cName, 'thai' ) ) {
1581 # Add 543 years to the Gregorian calendar
1582 # Months and days are identical
1583 $gy_offset = $gy +
543;
1584 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1586 # Deduct 1911 years from the Gregorian calendar
1587 # Months and days are identical
1588 $gy_offset = $gy - 1911;
1589 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1590 # Nengō dates up to Meiji period
1591 # Deduct years from the Gregorian calendar
1592 # depending on the nengo periods
1593 # Months and days are identical
1594 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1596 $gy_gannen = $gy - 1868 +
1;
1597 $gy_offset = $gy_gannen;
1598 if ( $gy_gannen == 1 ) {
1601 $gy_offset = '明治' . $gy_offset;
1603 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1604 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1605 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1606 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1607 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1611 $gy_gannen = $gy - 1912 +
1;
1612 $gy_offset = $gy_gannen;
1613 if ( $gy_gannen == 1 ) {
1616 $gy_offset = '大正' . $gy_offset;
1618 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1619 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1620 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1624 $gy_gannen = $gy - 1926 +
1;
1625 $gy_offset = $gy_gannen;
1626 if ( $gy_gannen == 1 ) {
1629 $gy_offset = '昭和' . $gy_offset;
1632 $gy_gannen = $gy - 1989 +
1;
1633 $gy_offset = $gy_gannen;
1634 if ( $gy_gannen == 1 ) {
1637 $gy_offset = '平成' . $gy_offset;
1643 return array( $gy_offset, $gm, $gd );
1647 * Roman number formatting up to 3000
1653 static function romanNumeral( $num ) {
1654 static $table = array(
1655 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1656 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1657 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1658 array( '', 'M', 'MM', 'MMM' )
1661 $num = intval( $num );
1662 if ( $num > 3000 ||
$num <= 0 ) {
1667 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1668 if ( $num >= $pow10 ) {
1669 $s .= $table[$i][(int)floor( $num / $pow10 )];
1671 $num = $num %
$pow10;
1677 * Hebrew Gematria number formatting up to 9999
1683 static function hebrewNumeral( $num ) {
1684 static $table = array(
1685 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1686 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1687 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1688 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1691 $num = intval( $num );
1692 if ( $num > 9999 ||
$num <= 0 ) {
1697 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1698 if ( $num >= $pow10 ) {
1699 if ( $num == 15 ||
$num == 16 ) {
1700 $s .= $table[0][9] . $table[0][$num - 9];
1703 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1704 if ( $pow10 == 1000 ) {
1709 $num = $num %
$pow10;
1711 if ( strlen( $s ) == 2 ) {
1714 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1715 $str .= substr( $s, strlen( $s ) - 2, 2 );
1717 $start = substr( $str, 0, strlen( $str ) - 2 );
1718 $end = substr( $str, strlen( $str ) - 2 );
1721 $str = $start . 'ך';
1724 $str = $start . 'ם';
1727 $str = $start . 'ן';
1730 $str = $start . 'ף';
1733 $str = $start . 'ץ';
1740 * Used by date() and time() to adjust the time output.
1742 * @param $ts Int the time in date('YmdHis') format
1743 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1744 * get user timecorrection setting)
1747 function userAdjust( $ts, $tz = false ) {
1748 global $wgUser, $wgLocalTZoffset;
1750 if ( $tz === false ) {
1751 $tz = $wgUser->getOption( 'timecorrection' );
1754 $data = explode( '|', $tz, 3 );
1756 if ( $data[0] == 'ZoneInfo' ) {
1757 wfSuppressWarnings();
1758 $userTZ = timezone_open( $data[2] );
1759 wfRestoreWarnings();
1760 if ( $userTZ !== false ) {
1761 $date = date_create( $ts, timezone_open( 'UTC' ) );
1762 date_timezone_set( $date, $userTZ );
1763 $date = date_format( $date, 'YmdHis' );
1766 # Unrecognized timezone, default to 'Offset' with the stored offset.
1767 $data[0] = 'Offset';
1771 if ( $data[0] == 'System' ||
$tz == '' ) {
1772 # Global offset in minutes.
1773 if ( isset( $wgLocalTZoffset ) ) {
1774 $minDiff = $wgLocalTZoffset;
1776 } elseif ( $data[0] == 'Offset' ) {
1777 $minDiff = intval( $data[1] );
1779 $data = explode( ':', $tz );
1780 if ( count( $data ) == 2 ) {
1781 $data[0] = intval( $data[0] );
1782 $data[1] = intval( $data[1] );
1783 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1784 if ( $data[0] < 0 ) {
1785 $minDiff = -$minDiff;
1788 $minDiff = intval( $data[0] ) * 60;
1792 # No difference ? Return time unchanged
1793 if ( 0 == $minDiff ) {
1797 wfSuppressWarnings(); // E_STRICT system time bitching
1798 # Generate an adjusted date; take advantage of the fact that mktime
1799 # will normalize out-of-range values so we don't have to split $minDiff
1800 # into hours and minutes.
1802 (int)substr( $ts, 8, 2 ) ), # Hours
1803 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1804 (int)substr( $ts, 12, 2 ), # Seconds
1805 (int)substr( $ts, 4, 2 ), # Month
1806 (int)substr( $ts, 6, 2 ), # Day
1807 (int)substr( $ts, 0, 4 ) ); # Year
1809 $date = date( 'YmdHis', $t );
1810 wfRestoreWarnings();
1816 * This is meant to be used by time(), date(), and timeanddate() to get
1817 * the date preference they're supposed to use, it should be used in
1821 * function timeanddate([...], $format = true) {
1822 * $datePreference = $this->dateFormat($format);
1827 * @param $usePrefs Mixed: if true, the user's preference is used
1828 * if false, the site/language default is used
1829 * if int/string, assumed to be a format.
1832 function dateFormat( $usePrefs = true ) {
1835 if ( is_bool( $usePrefs ) ) {
1837 $datePreference = $wgUser->getDatePreference();
1839 $datePreference = (string)User
::getDefaultOption( 'date' );
1842 $datePreference = (string)$usePrefs;
1846 if ( $datePreference == '' ) {
1850 return $datePreference;
1854 * Get a format string for a given type and preference
1855 * @param $type string May be date, time or both
1856 * @param $pref string The format name as it appears in Messages*.php
1860 function getDateFormatString( $type, $pref ) {
1861 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1862 if ( $pref == 'default' ) {
1863 $pref = $this->getDefaultDateFormat();
1864 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1866 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1867 if ( is_null( $df ) ) {
1868 $pref = $this->getDefaultDateFormat();
1869 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1872 $this->dateFormatStrings
[$type][$pref] = $df;
1874 return $this->dateFormatStrings
[$type][$pref];
1878 * @param $ts Mixed: the time format which needs to be turned into a
1879 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1880 * @param $adj Bool: whether to adjust the time output according to the
1881 * user configured offset ($timecorrection)
1882 * @param $format Mixed: true to use user's date format preference
1883 * @param $timecorrection String|bool the time offset as returned by
1884 * validateTimeZone() in Special:Preferences
1887 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1888 $ts = wfTimestamp( TS_MW
, $ts );
1890 $ts = $this->userAdjust( $ts, $timecorrection );
1892 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1893 return $this->sprintfDate( $df, $ts );
1897 * @param $ts Mixed: the time format which needs to be turned into a
1898 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1899 * @param $adj Bool: whether to adjust the time output according to the
1900 * user configured offset ($timecorrection)
1901 * @param $format Mixed: true to use user's date format preference
1902 * @param $timecorrection String|bool the time offset as returned by
1903 * validateTimeZone() in Special:Preferences
1906 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1907 $ts = wfTimestamp( TS_MW
, $ts );
1909 $ts = $this->userAdjust( $ts, $timecorrection );
1911 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1912 return $this->sprintfDate( $df, $ts );
1916 * @param $ts Mixed: the time format which needs to be turned into a
1917 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1918 * @param $adj Bool: whether to adjust the time output according to the
1919 * user configured offset ($timecorrection)
1920 * @param $format Mixed: what format to return, if it's false output the
1921 * default one (default true)
1922 * @param $timecorrection String|bool the time offset as returned by
1923 * validateTimeZone() in Special:Preferences
1926 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1927 $ts = wfTimestamp( TS_MW
, $ts );
1929 $ts = $this->userAdjust( $ts, $timecorrection );
1931 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1932 return $this->sprintfDate( $df, $ts );
1936 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1940 * @param integer $seconds The amount of seconds.
1941 * @param array $chosenIntervals The intervals to enable.
1945 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1946 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1948 $segments = array();
1950 foreach ( $intervals as $intervalName => $intervalValue ) {
1951 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1952 $segments[] = $message->inLanguage( $this )->escaped();
1955 return $this->listToText( $segments );
1959 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1960 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1964 * @param integer $seconds The amount of seconds.
1965 * @param array $chosenIntervals The intervals to enable.
1969 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1970 if ( empty( $chosenIntervals ) ) {
1971 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1974 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
1975 $sortedNames = array_keys( $intervals );
1976 $smallestInterval = array_pop( $sortedNames );
1978 $segments = array();
1980 foreach ( $intervals as $name => $length ) {
1981 $value = floor( $seconds / $length );
1983 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
1984 $seconds -= $value * $length;
1985 $segments[$name] = $value;
1993 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1995 * @param $type String: can be 'date', 'time' or 'both'
1996 * @param $ts Mixed: the time format which needs to be turned into a
1997 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1998 * @param $user User object used to get preferences for timezone and format
1999 * @param $options Array, can contain the following keys:
2000 * - 'timecorrection': time correction, can have the following values:
2001 * - true: use user's preference
2002 * - false: don't use time correction
2003 * - integer: value of time correction in minutes
2004 * - 'format': format to use, can have the following values:
2005 * - true: use user's preference
2006 * - false: use default preference
2007 * - string: format to use
2011 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2012 $ts = wfTimestamp( TS_MW
, $ts );
2013 $options +
= array( 'timecorrection' => true, 'format' => true );
2014 if ( $options['timecorrection'] !== false ) {
2015 if ( $options['timecorrection'] === true ) {
2016 $offset = $user->getOption( 'timecorrection' );
2018 $offset = $options['timecorrection'];
2020 $ts = $this->userAdjust( $ts, $offset );
2022 if ( $options['format'] === true ) {
2023 $format = $user->getDatePreference();
2025 $format = $options['format'];
2027 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2028 return $this->sprintfDate( $df, $ts );
2032 * Get the formatted date for the given timestamp and formatted for
2035 * @param $ts Mixed: the time format which needs to be turned into a
2036 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2037 * @param $user User object used to get preferences for timezone and format
2038 * @param $options Array, can contain the following keys:
2039 * - 'timecorrection': time correction, can have the following values:
2040 * - true: use user's preference
2041 * - false: don't use time correction
2042 * - integer: value of time correction in minutes
2043 * - 'format': format to use, can have the following values:
2044 * - true: use user's preference
2045 * - false: use default preference
2046 * - string: format to use
2050 public function userDate( $ts, User
$user, array $options = array() ) {
2051 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2055 * Get the formatted time for the given timestamp and formatted for
2058 * @param $ts Mixed: the time format which needs to be turned into a
2059 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2060 * @param $user User object used to get preferences for timezone and format
2061 * @param $options Array, can contain the following keys:
2062 * - 'timecorrection': time correction, can have the following values:
2063 * - true: use user's preference
2064 * - false: don't use time correction
2065 * - integer: value of time correction in minutes
2066 * - 'format': format to use, can have the following values:
2067 * - true: use user's preference
2068 * - false: use default preference
2069 * - string: format to use
2073 public function userTime( $ts, User
$user, array $options = array() ) {
2074 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2078 * Get the formatted date and time for the given timestamp and formatted for
2081 * @param $ts Mixed: the time format which needs to be turned into a
2082 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2083 * @param $user User object used to get preferences for timezone and format
2084 * @param $options Array, can contain the following keys:
2085 * - 'timecorrection': time correction, can have the following values:
2086 * - true: use user's preference
2087 * - false: don't use time correction
2088 * - integer: value of time correction in minutes
2089 * - 'format': format to use, can have the following values:
2090 * - true: use user's preference
2091 * - false: use default preference
2092 * - string: format to use
2096 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2097 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2101 * @param $key string
2102 * @return array|null
2104 function getMessage( $key ) {
2105 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2111 function getAllMessages() {
2112 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2121 function iconv( $in, $out, $string ) {
2122 # This is a wrapper for iconv in all languages except esperanto,
2123 # which does some nasty x-conversions beforehand
2125 # Even with //IGNORE iconv can whine about illegal characters in
2126 # *input* string. We just ignore those too.
2127 # REF: http://bugs.php.net/bug.php?id=37166
2128 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2129 wfSuppressWarnings();
2130 $text = iconv( $in, $out . '//IGNORE', $string );
2131 wfRestoreWarnings();
2135 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2138 * @param $matches array
2139 * @return mixed|string
2141 function ucwordbreaksCallbackAscii( $matches ) {
2142 return $this->ucfirst( $matches[1] );
2146 * @param $matches array
2149 function ucwordbreaksCallbackMB( $matches ) {
2150 return mb_strtoupper( $matches[0] );
2154 * @param $matches array
2157 function ucwordsCallbackMB( $matches ) {
2158 return mb_strtoupper( $matches[0] );
2162 * Make a string's first character uppercase
2164 * @param $str string
2168 function ucfirst( $str ) {
2170 if ( $o < 96 ) { // if already uppercase...
2172 } elseif ( $o < 128 ) {
2173 return ucfirst( $str ); // use PHP's ucfirst()
2175 // fall back to more complex logic in case of multibyte strings
2176 return $this->uc( $str, true );
2181 * Convert a string to uppercase
2183 * @param $str string
2184 * @param $first bool
2188 function uc( $str, $first = false ) {
2190 if ( $this->isMultibyte( $str ) ) {
2191 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2193 return ucfirst( $str );
2196 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2201 * @param $str string
2202 * @return mixed|string
2204 function lcfirst( $str ) {
2207 return strval( $str );
2208 } elseif ( $o >= 128 ) {
2209 return $this->lc( $str, true );
2210 } elseif ( $o > 96 ) {
2213 $str[0] = strtolower( $str[0] );
2219 * @param $str string
2220 * @param $first bool
2221 * @return mixed|string
2223 function lc( $str, $first = false ) {
2225 if ( $this->isMultibyte( $str ) ) {
2226 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2228 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2231 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2236 * @param $str string
2239 function isMultibyte( $str ) {
2240 return (bool)preg_match( '/[\x80-\xff]/', $str );
2244 * @param $str string
2245 * @return mixed|string
2247 function ucwords( $str ) {
2248 if ( $this->isMultibyte( $str ) ) {
2249 $str = $this->lc( $str );
2251 // regexp to find first letter in each word (i.e. after each space)
2252 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2254 // function to use to capitalize a single char
2255 return preg_replace_callback(
2257 array( $this, 'ucwordsCallbackMB' ),
2261 return ucwords( strtolower( $str ) );
2266 * capitalize words at word breaks
2268 * @param $str string
2271 function ucwordbreaks( $str ) {
2272 if ( $this->isMultibyte( $str ) ) {
2273 $str = $this->lc( $str );
2275 // since \b doesn't work for UTF-8, we explicitely define word break chars
2276 $breaks = "[ \-\(\)\}\{\.,\?!]";
2278 // find first letter after word break
2279 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2281 return preg_replace_callback(
2283 array( $this, 'ucwordbreaksCallbackMB' ),
2287 return preg_replace_callback(
2288 '/\b([\w\x80-\xff]+)\b/',
2289 array( $this, 'ucwordbreaksCallbackAscii' ),
2296 * Return a case-folded representation of $s
2298 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2299 * and $s2 are the same except for the case of their characters. It is not
2300 * necessary for the value returned to make sense when displayed.
2302 * Do *not* perform any other normalisation in this function. If a caller
2303 * uses this function when it should be using a more general normalisation
2304 * function, then fix the caller.
2310 function caseFold( $s ) {
2311 return $this->uc( $s );
2318 function checkTitleEncoding( $s ) {
2319 if ( is_array( $s ) ) {
2320 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2322 # Check for non-UTF-8 URLs
2323 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2328 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2329 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2334 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2340 function fallback8bitEncoding() {
2341 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2345 * Most writing systems use whitespace to break up words.
2346 * Some languages such as Chinese don't conventionally do this,
2347 * which requires special handling when breaking up words for
2352 function hasWordBreaks() {
2357 * Some languages such as Chinese require word segmentation,
2358 * Specify such segmentation when overridden in derived class.
2360 * @param $string String
2363 function segmentByWord( $string ) {
2368 * Some languages have special punctuation need to be normalized.
2369 * Make such changes here.
2371 * @param $string String
2374 function normalizeForSearch( $string ) {
2375 return self
::convertDoubleWidth( $string );
2379 * convert double-width roman characters to single-width.
2380 * range: ff00-ff5f ~= 0020-007f
2382 * @param $string string
2386 protected static function convertDoubleWidth( $string ) {
2387 static $full = null;
2388 static $half = null;
2390 if ( $full === null ) {
2391 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2392 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2393 $full = str_split( $fullWidth, 3 );
2394 $half = str_split( $halfWidth );
2397 $string = str_replace( $full, $half, $string );
2402 * @param $string string
2403 * @param $pattern string
2406 protected static function insertSpace( $string, $pattern ) {
2407 $string = preg_replace( $pattern, " $1 ", $string );
2408 $string = preg_replace( '/ +/', ' ', $string );
2413 * @param $termsArray array
2416 function convertForSearchResult( $termsArray ) {
2417 # some languages, e.g. Chinese, need to do a conversion
2418 # in order for search results to be displayed correctly
2423 * Get the first character of a string.
2428 function firstChar( $s ) {
2431 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2432 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2437 if ( isset( $matches[1] ) ) {
2438 if ( strlen( $matches[1] ) != 3 ) {
2442 // Break down Hangul syllables to grab the first jamo
2443 $code = utf8ToCodepoint( $matches[1] );
2444 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2446 } elseif ( $code < 0xb098 ) {
2447 return "\xe3\x84\xb1";
2448 } elseif ( $code < 0xb2e4 ) {
2449 return "\xe3\x84\xb4";
2450 } elseif ( $code < 0xb77c ) {
2451 return "\xe3\x84\xb7";
2452 } elseif ( $code < 0xb9c8 ) {
2453 return "\xe3\x84\xb9";
2454 } elseif ( $code < 0xbc14 ) {
2455 return "\xe3\x85\x81";
2456 } elseif ( $code < 0xc0ac ) {
2457 return "\xe3\x85\x82";
2458 } elseif ( $code < 0xc544 ) {
2459 return "\xe3\x85\x85";
2460 } elseif ( $code < 0xc790 ) {
2461 return "\xe3\x85\x87";
2462 } elseif ( $code < 0xcc28 ) {
2463 return "\xe3\x85\x88";
2464 } elseif ( $code < 0xce74 ) {
2465 return "\xe3\x85\x8a";
2466 } elseif ( $code < 0xd0c0 ) {
2467 return "\xe3\x85\x8b";
2468 } elseif ( $code < 0xd30c ) {
2469 return "\xe3\x85\x8c";
2470 } elseif ( $code < 0xd558 ) {
2471 return "\xe3\x85\x8d";
2473 return "\xe3\x85\x8e";
2480 function initEncoding() {
2481 # Some languages may have an alternate char encoding option
2482 # (Esperanto X-coding, Japanese furigana conversion, etc)
2483 # If this language is used as the primary content language,
2484 # an override to the defaults can be set here on startup.
2491 function recodeForEdit( $s ) {
2492 # For some languages we'll want to explicitly specify
2493 # which characters make it into the edit box raw
2494 # or are converted in some way or another.
2495 global $wgEditEncoding;
2496 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2499 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2507 function recodeInput( $s ) {
2508 # Take the previous into account.
2509 global $wgEditEncoding;
2510 if ( $wgEditEncoding != '' ) {
2511 $enc = $wgEditEncoding;
2515 if ( $enc == 'UTF-8' ) {
2518 return $this->iconv( $enc, 'UTF-8', $s );
2523 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2524 * also cleans up certain backwards-compatible sequences, converting them
2525 * to the modern Unicode equivalent.
2527 * This is language-specific for performance reasons only.
2533 function normalize( $s ) {
2534 global $wgAllUnicodeFixes;
2535 $s = UtfNormal
::cleanUp( $s );
2536 if ( $wgAllUnicodeFixes ) {
2537 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2538 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2545 * Transform a string using serialized data stored in the given file (which
2546 * must be in the serialized subdirectory of $IP). The file contains pairs
2547 * mapping source characters to destination characters.
2549 * The data is cached in process memory. This will go faster if you have the
2550 * FastStringSearch extension.
2552 * @param $file string
2553 * @param $string string
2555 * @throws MWException
2558 function transformUsingPairFile( $file, $string ) {
2559 if ( !isset( $this->transformData
[$file] ) ) {
2560 $data = wfGetPrecompiledData( $file );
2561 if ( $data === false ) {
2562 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2564 $this->transformData
[$file] = new ReplacementArray( $data );
2566 return $this->transformData
[$file]->replace( $string );
2570 * For right-to-left language support
2575 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2579 * Return the correct HTML 'dir' attribute value for this language.
2583 return $this->isRTL() ?
'rtl' : 'ltr';
2587 * Return 'left' or 'right' as appropriate alignment for line-start
2588 * for this language's text direction.
2590 * Should be equivalent to CSS3 'start' text-align value....
2594 function alignStart() {
2595 return $this->isRTL() ?
'right' : 'left';
2599 * Return 'right' or 'left' as appropriate alignment for line-end
2600 * for this language's text direction.
2602 * Should be equivalent to CSS3 'end' text-align value....
2606 function alignEnd() {
2607 return $this->isRTL() ?
'left' : 'right';
2611 * A hidden direction mark (LRM or RLM), depending on the language direction.
2612 * Unlike getDirMark(), this function returns the character as an HTML entity.
2613 * This function should be used when the output is guaranteed to be HTML,
2614 * because it makes the output HTML source code more readable. When
2615 * the output is plain text or can be escaped, getDirMark() should be used.
2617 * @param $opposite Boolean Get the direction mark opposite to your language
2620 function getDirMarkEntity( $opposite = false ) {
2621 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2622 return $this->isRTL() ?
'‏' : '‎';
2626 * A hidden direction mark (LRM or RLM), depending on the language direction.
2627 * This function produces them as invisible Unicode characters and
2628 * the output may be hard to read and debug, so it should only be used
2629 * when the output is plain text or can be escaped. When the output is
2630 * HTML, use getDirMarkEntity() instead.
2632 * @param $opposite Boolean Get the direction mark opposite to your language
2635 function getDirMark( $opposite = false ) {
2636 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2637 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2638 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2639 return $this->isRTL() ?
$rlm : $lrm;
2645 function capitalizeAllNouns() {
2646 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2650 * An arrow, depending on the language direction.
2652 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2655 function getArrow( $direction = 'forwards' ) {
2656 switch ( $direction ) {
2658 return $this->isRTL() ?
'←' : '→';
2660 return $this->isRTL() ?
'→' : '←';
2673 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2677 function linkPrefixExtension() {
2678 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2684 function getMagicWords() {
2685 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2688 protected function doMagicHook() {
2689 if ( $this->mMagicHookDone
) {
2692 $this->mMagicHookDone
= true;
2693 wfProfileIn( 'LanguageGetMagic' );
2694 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2695 wfProfileOut( 'LanguageGetMagic' );
2699 * Fill a MagicWord object with data from here
2703 function getMagic( $mw ) {
2704 $this->doMagicHook();
2706 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2707 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2709 $magicWords = $this->getMagicWords();
2710 if ( isset( $magicWords[$mw->mId
] ) ) {
2711 $rawEntry = $magicWords[$mw->mId
];
2717 if ( !is_array( $rawEntry ) ) {
2718 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2720 $mw->mCaseSensitive
= $rawEntry[0];
2721 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2726 * Add magic words to the extension array
2728 * @param $newWords array
2730 function addMagicWordsByLang( $newWords ) {
2731 $fallbackChain = $this->getFallbackLanguages();
2732 $fallbackChain = array_reverse( $fallbackChain );
2733 foreach ( $fallbackChain as $code ) {
2734 if ( isset( $newWords[$code] ) ) {
2735 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2741 * Get special page names, as an associative array
2742 * case folded alias => real name
2744 function getSpecialPageAliases() {
2745 // Cache aliases because it may be slow to load them
2746 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2748 $this->mExtendedSpecialPageAliases
=
2749 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2750 wfRunHooks( 'LanguageGetSpecialPageAliases',
2751 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2754 return $this->mExtendedSpecialPageAliases
;
2758 * Italic is unsuitable for some languages
2760 * @param $text String: the text to be emphasized.
2763 function emphasize( $text ) {
2764 return "<em>$text</em>";
2768 * Normally we output all numbers in plain en_US style, that is
2769 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2770 * point twohundredthirtyfive. However this is not suitable for all
2771 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2772 * Icelandic just want to use commas instead of dots, and dots instead
2773 * of commas like "293.291,235".
2775 * An example of this function being called:
2777 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2780 * See LanguageGu.php for the Gujarati implementation and
2781 * $separatorTransformTable on MessageIs.php for
2782 * the , => . and . => , implementation.
2784 * @todo check if it's viable to use localeconv() for the decimal
2786 * @param $number Mixed: the string to be formatted, should be an integer
2787 * or a floating point number.
2788 * @param $nocommafy Bool: set to true for special numbers like dates
2791 public function formatNum( $number, $nocommafy = false ) {
2792 global $wgTranslateNumerals;
2793 if ( !$nocommafy ) {
2794 $number = $this->commafy( $number );
2795 $s = $this->separatorTransformTable();
2797 $number = strtr( $number, $s );
2801 if ( $wgTranslateNumerals ) {
2802 $s = $this->digitTransformTable();
2804 $number = strtr( $number, $s );
2812 * @param $number string
2815 function parseFormattedNumber( $number ) {
2816 $s = $this->digitTransformTable();
2818 $number = strtr( $number, array_flip( $s ) );
2821 $s = $this->separatorTransformTable();
2823 $number = strtr( $number, array_flip( $s ) );
2826 $number = strtr( $number, array( ',' => '' ) );
2831 * Adds commas to a given number
2836 function commafy( $_ ) {
2837 $digitGroupingPattern = $this->digitGroupingPattern();
2838 if ( $_ === null ) {
2842 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2843 // default grouping is at thousands, use the same for ###,###,### pattern too.
2844 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2846 // Ref: http://cldr.unicode.org/translation/number-patterns
2848 if ( intval( $_ ) < 0 ) {
2849 // For negative numbers apply the algorithm like positive number and add sign.
2851 $_ = substr( $_, 1 );
2853 $numberpart = array();
2854 $decimalpart = array();
2855 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2856 preg_match( "/\d+/", $_, $numberpart );
2857 preg_match( "/\.\d*/", $_, $decimalpart );
2858 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2859 if ( $groupedNumber === $_ ) {
2860 // the string does not have any number part. Eg: .12345
2861 return $sign . $groupedNumber;
2863 $start = $end = strlen( $numberpart[0] );
2864 while ( $start > 0 ) {
2865 $match = $matches[0][$numMatches -1] ;
2866 $matchLen = strlen( $match );
2867 $start = $end - $matchLen;
2871 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2873 if ( $numMatches > 1 ) {
2874 // use the last pattern for the rest of the number
2878 $groupedNumber = "," . $groupedNumber;
2881 return $sign . $groupedNumber;
2887 function digitGroupingPattern() {
2888 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2894 function digitTransformTable() {
2895 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2901 function separatorTransformTable() {
2902 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2906 * Take a list of strings and build a locale-friendly comma-separated
2907 * list, using the local comma-separator message.
2908 * The last two strings are chained with an "and".
2913 function listToText( array $l ) {
2915 $m = count( $l ) - 1;
2917 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2919 for ( $i = $m; $i >= 0; $i-- ) {
2922 } elseif ( $i == $m - 1 ) {
2923 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2925 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2933 * Take a list of strings and build a locale-friendly comma-separated
2934 * list, using the local comma-separator message.
2935 * @param $list array of strings to put in a comma list
2938 function commaList( array $list ) {
2942 array( 'parsemag', 'escapenoentities', 'language' => $this )
2949 * Take a list of strings and build a locale-friendly semicolon-separated
2950 * list, using the local semicolon-separator message.
2951 * @param $list array of strings to put in a semicolon list
2954 function semicolonList( array $list ) {
2957 'semicolon-separator',
2958 array( 'parsemag', 'escapenoentities', 'language' => $this )
2965 * Same as commaList, but separate it with the pipe instead.
2966 * @param $list array of strings to put in a pipe list
2969 function pipeList( array $list ) {
2973 array( 'escapenoentities', 'language' => $this )
2980 * Truncate a string to a specified length in bytes, appending an optional
2981 * string (e.g. for ellipses)
2983 * The database offers limited byte lengths for some columns in the database;
2984 * multi-byte character sets mean we need to ensure that only whole characters
2985 * are included, otherwise broken characters can be passed to the user
2987 * If $length is negative, the string will be truncated from the beginning
2989 * @param $string String to truncate
2990 * @param $length Int: maximum length (including ellipses)
2991 * @param $ellipsis String to append to the truncated text
2992 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2993 * $adjustLength was introduced in 1.18, before that behaved as if false.
2996 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2997 # Use the localized ellipsis character
2998 if ( $ellipsis == '...' ) {
2999 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3001 # Check if there is no need to truncate
3002 if ( $length == 0 ) {
3003 return $ellipsis; // convention
3004 } elseif ( strlen( $string ) <= abs( $length ) ) {
3005 return $string; // no need to truncate
3007 $stringOriginal = $string;
3008 # If ellipsis length is >= $length then we can't apply $adjustLength
3009 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3010 $string = $ellipsis; // this can be slightly unexpected
3011 # Otherwise, truncate and add ellipsis...
3013 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3014 if ( $length > 0 ) {
3015 $length -= $eLength;
3016 $string = substr( $string, 0, $length ); // xyz...
3017 $string = $this->removeBadCharLast( $string );
3018 $string = $string . $ellipsis;
3020 $length +
= $eLength;
3021 $string = substr( $string, $length ); // ...xyz
3022 $string = $this->removeBadCharFirst( $string );
3023 $string = $ellipsis . $string;
3026 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3027 # This check is *not* redundant if $adjustLength, due to the single case where
3028 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3029 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3032 return $stringOriginal;
3037 * Remove bytes that represent an incomplete Unicode character
3038 * at the end of string (e.g. bytes of the char are missing)
3040 * @param $string String
3043 protected function removeBadCharLast( $string ) {
3044 if ( $string != '' ) {
3045 $char = ord( $string[strlen( $string ) - 1] );
3047 if ( $char >= 0xc0 ) {
3048 # We got the first byte only of a multibyte char; remove it.
3049 $string = substr( $string, 0, -1 );
3050 } elseif ( $char >= 0x80 &&
3051 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3052 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3054 # We chopped in the middle of a character; remove it
3062 * Remove bytes that represent an incomplete Unicode character
3063 * at the start of string (e.g. bytes of the char are missing)
3065 * @param $string String
3068 protected function removeBadCharFirst( $string ) {
3069 if ( $string != '' ) {
3070 $char = ord( $string[0] );
3071 if ( $char >= 0x80 && $char < 0xc0 ) {
3072 # We chopped in the middle of a character; remove the whole thing
3073 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3080 * Truncate a string of valid HTML to a specified length in bytes,
3081 * appending an optional string (e.g. for ellipses), and return valid HTML
3083 * This is only intended for styled/linked text, such as HTML with
3084 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3085 * Also, this will not detect things like "display:none" CSS.
3087 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3089 * @param string $text HTML string to truncate
3090 * @param int $length (zero/positive) Maximum length (including ellipses)
3091 * @param string $ellipsis String to append to the truncated text
3094 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3095 # Use the localized ellipsis character
3096 if ( $ellipsis == '...' ) {
3097 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3099 # Check if there is clearly no need to truncate
3100 if ( $length <= 0 ) {
3101 return $ellipsis; // no text shown, nothing to format (convention)
3102 } elseif ( strlen( $text ) <= $length ) {
3103 return $text; // string short enough even *with* HTML (short-circuit)
3106 $dispLen = 0; // innerHTML legth so far
3107 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3108 $tagType = 0; // 0-open, 1-close
3109 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3110 $entityState = 0; // 0-not entity, 1-entity
3111 $tag = $ret = ''; // accumulated tag name, accumulated result string
3112 $openTags = array(); // open tag stack
3113 $maybeState = null; // possible truncation state
3115 $textLen = strlen( $text );
3116 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3117 for ( $pos = 0; true; ++
$pos ) {
3118 # Consider truncation once the display length has reached the maximim.
3119 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3120 # Check that we're not in the middle of a bracket/entity...
3121 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3122 if ( !$testingEllipsis ) {
3123 $testingEllipsis = true;
3124 # Save where we are; we will truncate here unless there turn out to
3125 # be so few remaining characters that truncation is not necessary.
3126 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3127 $maybeState = array( $ret, $openTags ); // save state
3129 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3130 # String in fact does need truncation, the truncation point was OK.
3131 list( $ret, $openTags ) = $maybeState; // reload state
3132 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3133 $ret .= $ellipsis; // add ellipsis
3137 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3139 # Read the next char...
3141 $lastCh = $pos ?
$text[$pos - 1] : '';
3142 $ret .= $ch; // add to result string
3144 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3145 $entityState = 0; // for bad HTML
3146 $bracketState = 1; // tag started (checking for backslash)
3147 } elseif ( $ch == '>' ) {
3148 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3149 $entityState = 0; // for bad HTML
3150 $bracketState = 0; // out of brackets
3151 } elseif ( $bracketState == 1 ) {
3153 $tagType = 1; // close tag (e.g. "</span>")
3155 $tagType = 0; // open tag (e.g. "<span>")
3158 $bracketState = 2; // building tag name
3159 } elseif ( $bracketState == 2 ) {
3163 // Name found (e.g. "<a href=..."), add on tag attributes...
3164 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3166 } elseif ( $bracketState == 0 ) {
3167 if ( $entityState ) {
3170 $dispLen++
; // entity is one displayed char
3173 if ( $neLength == 0 && !$maybeState ) {
3174 // Save state without $ch. We want to *hit* the first
3175 // display char (to get tags) but not *use* it if truncating.
3176 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3179 $entityState = 1; // entity found, (e.g. " ")
3181 $dispLen++
; // this char is displayed
3182 // Add the next $max display text chars after this in one swoop...
3183 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3184 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3185 $dispLen +
= $skipped;
3191 // Close the last tag if left unclosed by bad HTML
3192 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3193 while ( count( $openTags ) > 0 ) {
3194 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3200 * truncateHtml() helper function
3201 * like strcspn() but adds the skipped chars to $ret
3210 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3211 if ( $len === null ) {
3212 $len = -1; // -1 means "no limit" for strcspn
3213 } elseif ( $len < 0 ) {
3217 if ( $start < strlen( $text ) ) {
3218 $skipCount = strcspn( $text, $search, $start, $len );
3219 $ret .= substr( $text, $start, $skipCount );
3225 * truncateHtml() helper function
3226 * (a) push or pop $tag from $openTags as needed
3227 * (b) clear $tag value
3228 * @param &$tag string Current HTML tag name we are looking at
3229 * @param $tagType int (0-open tag, 1-close tag)
3230 * @param $lastCh string Character before the '>' that ended this tag
3231 * @param &$openTags array Open tag stack (not accounting for $tag)
3233 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3234 $tag = ltrim( $tag );
3236 if ( $tagType == 0 && $lastCh != '/' ) {
3237 $openTags[] = $tag; // tag opened (didn't close itself)
3238 } elseif ( $tagType == 1 ) {
3239 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3240 array_pop( $openTags ); // tag closed
3248 * Grammatical transformations, needed for inflected languages
3249 * Invoked by putting {{grammar:case|word}} in a message
3251 * @param $word string
3252 * @param $case string
3255 function convertGrammar( $word, $case ) {
3256 global $wgGrammarForms;
3257 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3258 return $wgGrammarForms[$this->getCode()][$case][$word];
3263 * Get the grammar forms for the content language
3264 * @return array of grammar forms
3267 function getGrammarForms() {
3268 global $wgGrammarForms;
3269 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3270 return $wgGrammarForms[$this->getCode()];
3275 * Provides an alternative text depending on specified gender.
3276 * Usage {{gender:username|masculine|feminine|neutral}}.
3277 * username is optional, in which case the gender of current user is used,
3278 * but only in (some) interface messages; otherwise default gender is used.
3280 * If no forms are given, an empty string is returned. If only one form is
3281 * given, it will be returned unconditionally. These details are implied by
3282 * the caller and cannot be overridden in subclasses.
3284 * If more than one form is given, the default is to use the neutral one
3285 * if it is specified, and to use the masculine one otherwise. These
3286 * details can be overridden in subclasses.
3288 * @param $gender string
3289 * @param $forms array
3293 function gender( $gender, $forms ) {
3294 if ( !count( $forms ) ) {
3297 $forms = $this->preConvertPlural( $forms, 2 );
3298 if ( $gender === 'male' ) {
3301 if ( $gender === 'female' ) {
3304 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3308 * Plural form transformations, needed for some languages.
3309 * For example, there are 3 form of plural in Russian and Polish,
3310 * depending on "count mod 10". See [[w:Plural]]
3311 * For English it is pretty simple.
3313 * Invoked by putting {{plural:count|wordform1|wordform2}}
3314 * or {{plural:count|wordform1|wordform2|wordform3}}
3316 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3318 * @param $count Integer: non-localized number
3319 * @param $forms Array: different plural forms
3320 * @return string Correct form of plural for $count in this language
3322 function convertPlural( $count, $forms ) {
3323 if ( !count( $forms ) ) {
3326 $forms = $this->preConvertPlural( $forms, 2 );
3328 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3332 * Checks that convertPlural was given an array and pads it to requested
3333 * amount of forms by copying the last one.
3335 * @param $count Integer: How many forms should there be at least
3336 * @param $forms Array of forms given to convertPlural
3337 * @return array Padded array of forms or an exception if not an array
3339 protected function preConvertPlural( /* Array */ $forms, $count ) {
3340 while ( count( $forms ) < $count ) {
3341 $forms[] = $forms[count( $forms ) - 1];
3347 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3348 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3349 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3350 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3353 * @param $str String: the validated block duration in English
3354 * @return string Somehow translated block duration
3355 * @see LanguageFi.php for example implementation
3357 function translateBlockExpiry( $str ) {
3358 $duration = SpecialBlock
::getSuggestedDurations( $this );
3359 foreach ( $duration as $show => $value ) {
3360 if ( strcmp( $str, $value ) == 0 ) {
3361 return htmlspecialchars( trim( $show ) );
3365 // Since usually only infinite or indefinite is only on list, so try
3366 // equivalents if still here.
3367 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3368 if ( in_array( $str, $indefs ) ) {
3369 foreach ( $indefs as $val ) {
3370 $show = array_search( $val, $duration, true );
3371 if ( $show !== false ) {
3372 return htmlspecialchars( trim( $show ) );
3376 // If all else fails, return the original string.
3381 * languages like Chinese need to be segmented in order for the diff
3384 * @param $text String
3387 public function segmentForDiff( $text ) {
3392 * and unsegment to show the result
3394 * @param $text String
3397 public function unsegmentForDiff( $text ) {
3402 * Return the LanguageConverter used in the Language
3405 * @return LanguageConverter
3407 public function getConverter() {
3408 return $this->mConverter
;
3412 * convert text to all supported variants
3414 * @param $text string
3417 public function autoConvertToAllVariants( $text ) {
3418 return $this->mConverter
->autoConvertToAllVariants( $text );
3422 * convert text to different variants of a language.
3424 * @param $text string
3427 public function convert( $text ) {
3428 return $this->mConverter
->convert( $text );
3432 * Convert a Title object to a string in the preferred variant
3434 * @param $title Title
3437 public function convertTitle( $title ) {
3438 return $this->mConverter
->convertTitle( $title );
3442 * Check if this is a language with variants
3446 public function hasVariants() {
3447 return sizeof( $this->getVariants() ) > 1;
3451 * Check if the language has the specific variant
3454 * @param $variant string
3457 public function hasVariant( $variant ) {
3458 return (bool)$this->mConverter
->validateVariant( $variant );
3462 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3464 * @param $text string
3467 public function armourMath( $text ) {
3468 return $this->mConverter
->armourMath( $text );
3472 * Perform output conversion on a string, and encode for safe HTML output.
3473 * @param $text String text to be converted
3474 * @param $isTitle Bool whether this conversion is for the article title
3476 * @todo this should get integrated somewhere sane
3478 public function convertHtml( $text, $isTitle = false ) {
3479 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3483 * @param $key string
3486 public function convertCategoryKey( $key ) {
3487 return $this->mConverter
->convertCategoryKey( $key );
3491 * Get the list of variants supported by this language
3492 * see sample implementation in LanguageZh.php
3494 * @return array an array of language codes
3496 public function getVariants() {
3497 return $this->mConverter
->getVariants();
3503 public function getPreferredVariant() {
3504 return $this->mConverter
->getPreferredVariant();
3510 public function getDefaultVariant() {
3511 return $this->mConverter
->getDefaultVariant();
3517 public function getURLVariant() {
3518 return $this->mConverter
->getURLVariant();
3522 * If a language supports multiple variants, it is
3523 * possible that non-existing link in one variant
3524 * actually exists in another variant. this function
3525 * tries to find it. See e.g. LanguageZh.php
3527 * @param $link String: the name of the link
3528 * @param $nt Mixed: the title object of the link
3529 * @param $ignoreOtherCond Boolean: to disable other conditions when
3530 * we need to transclude a template or update a category's link
3531 * @return null the input parameters may be modified upon return
3533 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3534 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3538 * If a language supports multiple variants, converts text
3539 * into an array of all possible variants of the text:
3540 * 'variant' => text in that variant
3542 * @deprecated since 1.17 Use autoConvertToAllVariants()
3544 * @param $text string
3548 public function convertLinkToAllVariants( $text ) {
3549 return $this->mConverter
->convertLinkToAllVariants( $text );
3553 * returns language specific options used by User::getPageRenderHash()
3554 * for example, the preferred language variant
3558 function getExtraHashOptions() {
3559 return $this->mConverter
->getExtraHashOptions();
3563 * For languages that support multiple variants, the title of an
3564 * article may be displayed differently in different variants. this
3565 * function returns the apporiate title defined in the body of the article.
3569 public function getParsedTitle() {
3570 return $this->mConverter
->getParsedTitle();
3574 * Enclose a string with the "no conversion" tag. This is used by
3575 * various functions in the Parser
3577 * @param $text String: text to be tagged for no conversion
3578 * @param $noParse bool
3579 * @return string the tagged text
3581 public function markNoConversion( $text, $noParse = false ) {
3582 return $this->mConverter
->markNoConversion( $text, $noParse );
3586 * A regular expression to match legal word-trailing characters
3587 * which should be merged onto a link of the form [[foo]]bar.
3591 public function linkTrail() {
3592 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3598 function getLangObj() {
3603 * Get the RFC 3066 code for this language object
3607 public function getCode() {
3608 return $this->mCode
;
3612 * Get the code in Bcp47 format which we can use
3613 * inside of html lang="" tags.
3617 public function getHtmlCode() {
3618 if ( is_null( $this->mHtmlCode
) ) {
3619 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3621 return $this->mHtmlCode
;
3625 * @param $code string
3627 public function setCode( $code ) {
3628 $this->mCode
= $code;
3629 // Ensure we don't leave an incorrect html code lying around
3630 $this->mHtmlCode
= null;
3634 * Get the name of a file for a certain language code
3635 * @param $prefix string Prepend this to the filename
3636 * @param $code string Language code
3637 * @param $suffix string Append this to the filename
3638 * @throws MWException
3639 * @return string $prefix . $mangledCode . $suffix
3641 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3642 // Protect against path traversal
3643 if ( !Language
::isValidCode( $code )
3644 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3646 throw new MWException( "Invalid language code \"$code\"" );
3649 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3653 * Get the language code from a file name. Inverse of getFileName()
3654 * @param $filename string $prefix . $languageCode . $suffix
3655 * @param $prefix string Prefix before the language code
3656 * @param $suffix string Suffix after the language code
3657 * @return string Language code, or false if $prefix or $suffix isn't found
3659 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3661 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3662 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3663 if ( !count( $m ) ) {
3666 return str_replace( '_', '-', strtolower( $m[1] ) );
3670 * @param $code string
3673 public static function getMessagesFileName( $code ) {
3675 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3676 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3681 * @param $code string
3684 public static function getClassFileName( $code ) {
3686 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3690 * Get the first fallback for a given language.
3692 * @param $code string
3694 * @return bool|string
3696 public static function getFallbackFor( $code ) {
3697 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3700 $fallbacks = self
::getFallbacksFor( $code );
3701 $first = array_shift( $fallbacks );
3707 * Get the ordered list of fallback languages.
3710 * @param $code string Language code
3713 public static function getFallbacksFor( $code ) {
3714 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3717 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3718 $v = array_map( 'trim', explode( ',', $v ) );
3719 if ( $v[count( $v ) - 1] !== 'en' ) {
3727 * Get all messages for a given language
3728 * WARNING: this may take a long time. If you just need all message *keys*
3729 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3731 * @param $code string
3735 public static function getMessagesFor( $code ) {
3736 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3740 * Get a message for a given language
3742 * @param $key string
3743 * @param $code string
3747 public static function getMessageFor( $key, $code ) {
3748 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3752 * Get all message keys for a given language. This is a faster alternative to
3753 * array_keys( Language::getMessagesFor( $code ) )
3756 * @param $code string Language code
3757 * @return array of message keys (strings)
3759 public static function getMessageKeysFor( $code ) {
3760 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3767 function fixVariableInNamespace( $talk ) {
3768 if ( strpos( $talk, '$1' ) === false ) {
3772 global $wgMetaNamespace;
3773 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3775 # Allow grammar transformations
3776 # Allowing full message-style parsing would make simple requests
3777 # such as action=raw much more expensive than they need to be.
3778 # This will hopefully cover most cases.
3779 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3780 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3781 return str_replace( ' ', '_', $talk );
3788 function replaceGrammarInNamespace( $m ) {
3789 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3793 * @throws MWException
3796 static function getCaseMaps() {
3797 static $wikiUpperChars, $wikiLowerChars;
3798 if ( isset( $wikiUpperChars ) ) {
3799 return array( $wikiUpperChars, $wikiLowerChars );
3802 wfProfileIn( __METHOD__
);
3803 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3804 if ( $arr === false ) {
3805 throw new MWException(
3806 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3808 $wikiUpperChars = $arr['wikiUpperChars'];
3809 $wikiLowerChars = $arr['wikiLowerChars'];
3810 wfProfileOut( __METHOD__
);
3811 return array( $wikiUpperChars, $wikiLowerChars );
3815 * Decode an expiry (block, protection, etc) which has come from the DB
3817 * @FIXME: why are we returnings DBMS-dependent strings???
3819 * @param $expiry String: Database expiry String
3820 * @param $format Bool|Int true to process using language functions, or TS_ constant
3821 * to return the expiry in a given timestamp
3824 public function formatExpiry( $expiry, $format = true ) {
3825 static $infinity, $infinityMsg;
3826 if ( $infinity === null ) {
3827 $infinityMsg = wfMessage( 'infiniteblock' );
3828 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3831 if ( $expiry == '' ||
$expiry == $infinity ) {
3832 return $format === true
3836 return $format === true
3837 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3838 : wfTimestamp( $format, $expiry );
3844 * @param $seconds int|float
3845 * @param $format Array Optional
3846 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3847 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3848 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3849 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3852 function formatTimePeriod( $seconds, $format = array() ) {
3853 if ( !is_array( $format ) ) {
3854 $format = array( 'avoid' => $format ); // For backwards compatibility
3856 if ( !isset( $format['avoid'] ) ) {
3857 $format['avoid'] = false;
3859 if ( !isset( $format['noabbrevs' ] ) ) {
3860 $format['noabbrevs'] = false;
3862 $secondsMsg = wfMessage(
3863 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3864 $minutesMsg = wfMessage(
3865 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3866 $hoursMsg = wfMessage(
3867 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3868 $daysMsg = wfMessage(
3869 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3871 if ( round( $seconds * 10 ) < 100 ) {
3872 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3873 $s = $secondsMsg->params( $s )->text();
3874 } elseif ( round( $seconds ) < 60 ) {
3875 $s = $this->formatNum( round( $seconds ) );
3876 $s = $secondsMsg->params( $s )->text();
3877 } elseif ( round( $seconds ) < 3600 ) {
3878 $minutes = floor( $seconds / 60 );
3879 $secondsPart = round( fmod( $seconds, 60 ) );
3880 if ( $secondsPart == 60 ) {
3884 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3886 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3887 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3888 $hours = floor( $seconds / 3600 );
3889 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3890 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3891 if ( $secondsPart == 60 ) {
3895 if ( $minutes == 60 ) {
3899 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3901 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3902 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3903 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3906 $days = floor( $seconds / 86400 );
3907 if ( $format['avoid'] === 'avoidminutes' ) {
3908 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3909 if ( $hours == 24 ) {
3913 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3915 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3916 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3917 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3918 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3919 if ( $minutes == 60 ) {
3923 if ( $hours == 24 ) {
3927 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3929 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3931 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3933 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3935 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3942 * Format a bitrate for output, using an appropriate
3943 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3945 * This use base 1000. For base 1024 use formatSize(), for another base
3946 * see formatComputingNumbers()
3951 function formatBitrate( $bps ) {
3952 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3956 * @param $size int Size of the unit
3957 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3958 * @param $messageKey string Message key to be uesd
3961 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3963 return str_replace( '$1', $this->formatNum( $size ),
3964 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3967 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3970 $maxIndex = count( $sizes ) - 1;
3971 while ( $size >= $boundary && $index < $maxIndex ) {
3976 // For small sizes no decimal places necessary
3979 // For MB and bigger two decimal places are smarter
3982 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3984 $size = round( $size, $round );
3985 $text = $this->getMessageFromDB( $msg );
3986 return str_replace( '$1', $this->formatNum( $size ), $text );
3990 * Format a size in bytes for output, using an appropriate
3991 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3993 * This method use base 1024. For base 1000 use formatBitrate(), for
3994 * another base see formatComputingNumbers()
3996 * @param $size int Size to format
3997 * @return string Plain text (not HTML)
3999 function formatSize( $size ) {
4000 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4004 * Make a list item, used by various special pages
4006 * @param $page String Page link
4007 * @param $details String Text between brackets
4008 * @param $oppositedm Boolean Add the direction mark opposite to your
4009 * language, to display text properly
4012 function specialList( $page, $details, $oppositedm = true ) {
4013 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4014 $this->getDirMark();
4015 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4016 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4017 return $page . $details;
4021 * Generate (prev x| next x) (20|50|100...) type links for paging
4023 * @param $title Title object to link
4024 * @param $offset Integer offset parameter
4025 * @param $limit Integer limit parameter
4026 * @param $query String optional URL query parameter string
4027 * @param $atend Bool optional param for specified if this is the last page
4030 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4031 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4033 # Make 'previous' link
4034 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4035 if ( $offset > 0 ) {
4036 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4037 $query, $prev, 'prevn-title', 'mw-prevlink' );
4039 $plink = htmlspecialchars( $prev );
4043 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4045 $nlink = htmlspecialchars( $next );
4047 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4048 $query, $next, 'prevn-title', 'mw-nextlink' );
4051 # Make links to set number of items per page
4052 $numLinks = array();
4053 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4054 $numLinks[] = $this->numLink( $title, $offset, $num,
4055 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4058 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4059 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4063 * Helper function for viewPrevNext() that generates links
4065 * @param $title Title object to link
4066 * @param $offset Integer offset parameter
4067 * @param $limit Integer limit parameter
4068 * @param $query Array extra query parameters
4069 * @param $link String text to use for the link; will be escaped
4070 * @param $tooltipMsg String name of the message to use as tooltip
4071 * @param $class String value of the "class" attribute of the link
4072 * @return String HTML fragment
4074 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4075 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4076 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4077 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4078 'title' => $tooltip, 'class' => $class ), $link );
4082 * Get the conversion rule title, if any.
4086 public function getConvRuleTitle() {
4087 return $this->mConverter
->getConvRuleTitle();