3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
37 function __construct( $langobj ) { $this->mLang
= $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang
->getCode() ); }
43 function getPreferredVariant() { return $this->mLang
->getCode(); }
44 function getDefaultVariant() { return $this->mLang
->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
57 * Internationalisation code
63 * @var LanguageConverter
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
77 * ReplacementArray object caches
79 var $transformData = array();
82 * @var LocalisationCache
84 static public $dataCache;
86 static public $mLangObjCache = array();
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
146 static public $durationIntervals = array(
147 'millennia' => 31557600000,
148 'centuries' => 3155760000,
149 'decades' => 315576000,
150 'years' => 31557600, // 86400 * 365.25
159 * Get a cached language object for a given language code
160 * @param $code String
163 static function factory( $code ) {
164 if ( !isset( self
::$mLangObjCache[$code] ) ) {
165 if ( count( self
::$mLangObjCache ) > 10 ) {
166 // Don't keep a billion objects around, that's stupid.
167 self
::$mLangObjCache = array();
169 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
171 return self
::$mLangObjCache[$code];
175 * Create a language object for a given language code
176 * @param $code String
177 * @throws MWException
180 protected static function newFromCode( $code ) {
181 // Protect against path traversal below
182 if ( !Language
::isValidCode( $code )
183 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
185 throw new MWException( "Invalid language code \"$code\"" );
188 if ( !Language
::isValidBuiltInCode( $code ) ) {
189 // It's not possible to customise this code with class files, so
190 // just return a Language object. This is to support uselang= hacks.
191 $lang = new Language
;
192 $lang->setCode( $code );
196 // Check if there is a language class for the code
197 $class = self
::classFromCode( $code );
198 self
::preloadLanguageClass( $class );
199 if ( MWInit
::classExists( $class ) ) {
204 // Keep trying the fallback list until we find an existing class
205 $fallbacks = Language
::getFallbacksFor( $code );
206 foreach ( $fallbacks as $fallbackCode ) {
207 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
208 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
211 $class = self
::classFromCode( $fallbackCode );
212 self
::preloadLanguageClass( $class );
213 if ( MWInit
::classExists( $class ) ) {
214 $lang = Language
::newFromCode( $fallbackCode );
215 $lang->setCode( $code );
220 throw new MWException( "Invalid fallback sequence for language '$code'" );
224 * Returns true if a language code string is of a valid form, whether or
225 * not it exists. This includes codes which are used solely for
226 * customisation via the MediaWiki namespace.
228 * @param $code string
232 public static function isValidCode( $code ) {
234 strcspn( $code, ":/\\\000" ) === strlen( $code )
235 && !preg_match( Title
::getTitleInvalidRegex(), $code );
239 * Returns true if a language code is of a valid form for the purposes of
240 * internal customisation of MediaWiki, via Messages*.php.
242 * @param $code string
247 public static function isValidBuiltInCode( $code ) {
248 return preg_match( '/^[a-z0-9-]+$/i', $code );
253 * @return String Name of the language class
255 public static function classFromCode( $code ) {
256 if ( $code == 'en' ) {
259 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
264 * Includes language class files
266 * @param $class string Name of the language class
268 public static function preloadLanguageClass( $class ) {
271 if ( $class === 'Language' ) {
275 if ( !defined( 'MW_COMPILED' ) ) {
276 // Preload base classes to work around APC/PHP5 bug
277 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
278 include_once( "$IP/languages/classes/$class.deps.php" );
280 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
281 include_once( "$IP/languages/classes/$class.php" );
287 * Get the LocalisationCache instance
289 * @return LocalisationCache
291 public static function getLocalisationCache() {
292 if ( is_null( self
::$dataCache ) ) {
293 global $wgLocalisationCacheConf;
294 $class = $wgLocalisationCacheConf['class'];
295 self
::$dataCache = new $class( $wgLocalisationCacheConf );
297 return self
::$dataCache;
300 function __construct() {
301 $this->mConverter
= new FakeConverter( $this );
302 // Set the code to the name of the descendant
303 if ( get_class( $this ) == 'Language' ) {
306 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
308 self
::getLocalisationCache();
312 * Reduce memory usage
314 function __destruct() {
315 foreach ( $this as $name => $value ) {
316 unset( $this->$name );
321 * Hook which will be called if this is the content language.
322 * Descendants can use this to register hook functions or modify globals
324 function initContLang() { }
327 * Same as getFallbacksFor for current language.
329 * @deprecated in 1.19
331 function getFallbackLanguageCode() {
332 wfDeprecated( __METHOD__
);
333 return self
::getFallbackFor( $this->mCode
);
340 function getFallbackLanguages() {
341 return self
::getFallbacksFor( $this->mCode
);
345 * Exports $wgBookstoreListEn
348 function getBookstoreList() {
349 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
355 public function getNamespaces() {
356 if ( is_null( $this->namespaceNames
) ) {
357 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
359 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
360 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
362 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
364 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
365 if ( $wgMetaNamespaceTalk ) {
366 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
368 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
369 $this->namespaceNames
[NS_PROJECT_TALK
] =
370 $this->fixVariableInNamespace( $talk );
373 # Sometimes a language will be localised but not actually exist on this wiki.
374 foreach ( $this->namespaceNames
as $key => $text ) {
375 if ( !isset( $validNamespaces[$key] ) ) {
376 unset( $this->namespaceNames
[$key] );
380 # The above mixing may leave namespaces out of canonical order.
381 # Re-order by namespace ID number...
382 ksort( $this->namespaceNames
);
384 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
386 return $this->namespaceNames
;
390 * Arbitrarily set all of the namespace names at once. Mainly used for testing
391 * @param $namespaces Array of namespaces (id => name)
393 public function setNamespaces( array $namespaces ) {
394 $this->namespaceNames
= $namespaces;
398 * A convenience function that returns the same thing as
399 * getNamespaces() except with the array values changed to ' '
400 * where it found '_', useful for producing output to be displayed
401 * e.g. in <select> forms.
405 function getFormattedNamespaces() {
406 $ns = $this->getNamespaces();
407 foreach ( $ns as $k => $v ) {
408 $ns[$k] = strtr( $v, '_', ' ' );
414 * Get a namespace value by key
416 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
417 * echo $mw_ns; // prints 'MediaWiki'
420 * @param $index Int: the array key of the namespace to return
421 * @return mixed, string if the namespace value exists, otherwise false
423 function getNsText( $index ) {
424 $ns = $this->getNamespaces();
425 return isset( $ns[$index] ) ?
$ns[$index] : false;
429 * A convenience function that returns the same thing as
430 * getNsText() except with '_' changed to ' ', useful for
433 * @param $index string
437 function getFormattedNsText( $index ) {
438 $ns = $this->getNsText( $index );
439 return strtr( $ns, '_', ' ' );
443 * Returns gender-dependent namespace alias if available.
444 * @param $index Int: namespace index
445 * @param $gender String: gender key (male, female... )
449 function getGenderNsText( $index, $gender ) {
450 global $wgExtraGenderNamespaces;
452 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
453 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
457 * Whether this language makes distinguishes genders for example in
462 function needsGenderDistinction() {
463 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
464 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
465 // $wgExtraGenderNamespaces overrides everything
467 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
468 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
469 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
472 // Check what is in i18n files
473 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
474 return count( $aliases ) > 0;
479 * Get a namespace key by value, case insensitive.
480 * Only matches namespace names for the current language, not the
481 * canonical ones defined in Namespace.php.
483 * @param $text String
484 * @return mixed An integer if $text is a valid value otherwise false
486 function getLocalNsIndex( $text ) {
487 $lctext = $this->lc( $text );
488 $ids = $this->getNamespaceIds();
489 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
495 function getNamespaceAliases() {
496 if ( is_null( $this->namespaceAliases
) ) {
497 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
501 foreach ( $aliases as $name => $index ) {
502 if ( $index === NS_PROJECT_TALK
) {
503 unset( $aliases[$name] );
504 $name = $this->fixVariableInNamespace( $name );
505 $aliases[$name] = $index;
510 global $wgExtraGenderNamespaces;
511 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
512 foreach ( $genders as $index => $forms ) {
513 foreach ( $forms as $alias ) {
514 $aliases[$alias] = $index;
518 $this->namespaceAliases
= $aliases;
520 return $this->namespaceAliases
;
526 function getNamespaceIds() {
527 if ( is_null( $this->mNamespaceIds
) ) {
528 global $wgNamespaceAliases;
529 # Put namespace names and aliases into a hashtable.
530 # If this is too slow, then we should arrange it so that it is done
531 # before caching. The catch is that at pre-cache time, the above
532 # class-specific fixup hasn't been done.
533 $this->mNamespaceIds
= array();
534 foreach ( $this->getNamespaces() as $index => $name ) {
535 $this->mNamespaceIds
[$this->lc( $name )] = $index;
537 foreach ( $this->getNamespaceAliases() as $name => $index ) {
538 $this->mNamespaceIds
[$this->lc( $name )] = $index;
540 if ( $wgNamespaceAliases ) {
541 foreach ( $wgNamespaceAliases as $name => $index ) {
542 $this->mNamespaceIds
[$this->lc( $name )] = $index;
546 return $this->mNamespaceIds
;
550 * Get a namespace key by value, case insensitive. Canonical namespace
551 * names override custom ones defined for the current language.
553 * @param $text String
554 * @return mixed An integer if $text is a valid value otherwise false
556 function getNsIndex( $text ) {
557 $lctext = $this->lc( $text );
558 $ns = MWNamespace
::getCanonicalIndex( $lctext );
559 if ( $ns !== null ) {
562 $ids = $this->getNamespaceIds();
563 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
567 * short names for language variants used for language conversion links.
569 * @param $code String
570 * @param $usemsg bool Use the "variantname-xyz" message if it exists
573 function getVariantname( $code, $usemsg = true ) {
574 $msg = "variantname-$code";
575 if ( $usemsg && wfMessage( $msg )->exists() ) {
576 return $this->getMessageFromDB( $msg );
578 $name = self
::fetchLanguageName( $code );
580 return $name; # if it's defined as a language name, show that
582 # otherwise, output the language code
588 * @param $name string
591 function specialPage( $name ) {
592 $aliases = $this->getSpecialPageAliases();
593 if ( isset( $aliases[$name][0] ) ) {
594 $name = $aliases[$name][0];
596 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
602 function getQuickbarSettings() {
604 $this->getMessage( 'qbsettings-none' ),
605 $this->getMessage( 'qbsettings-fixedleft' ),
606 $this->getMessage( 'qbsettings-fixedright' ),
607 $this->getMessage( 'qbsettings-floatingleft' ),
608 $this->getMessage( 'qbsettings-floatingright' ),
609 $this->getMessage( 'qbsettings-directionality' )
616 function getDatePreferences() {
617 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
623 function getDateFormats() {
624 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
628 * @return array|string
630 function getDefaultDateFormat() {
631 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
632 if ( $df === 'dmy or mdy' ) {
633 global $wgAmericanDates;
634 return $wgAmericanDates ?
'mdy' : 'dmy';
643 function getDatePreferenceMigrationMap() {
644 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
651 function getImageFile( $image ) {
652 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
658 function getExtraUserToggles() {
659 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
666 function getUserToggle( $tog ) {
667 return $this->getMessageFromDB( "tog-$tog" );
671 * Get native language names, indexed by code.
672 * Only those defined in MediaWiki, no other data like CLDR.
673 * If $customisedOnly is true, only returns codes with a messages file
675 * @param $customisedOnly bool
678 * @deprecated in 1.20, use fetchLanguageNames()
680 public static function getLanguageNames( $customisedOnly = false ) {
681 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
685 * Get translated language names. This is done on best effort and
686 * by default this is exactly the same as Language::getLanguageNames.
687 * The CLDR extension provides translated names.
688 * @param $code String Language code.
689 * @return Array language code => language name
691 * @deprecated in 1.20, use fetchLanguageNames()
693 public static function getTranslatedLanguageNames( $code ) {
694 return self
::fetchLanguageNames( $code, 'all' );
698 * Get an array of language names, indexed by code.
699 * @param $inLanguage null|string: Code of language in which to return the names
700 * Use null for autonyms (native names)
701 * @param $include string:
702 * 'all' all available languages
703 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
704 * 'mwfile' only if the language is in 'mw' *and* has a message file
705 * @return array: language code => language name
708 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
709 global $wgExtraLanguageNames;
710 static $coreLanguageNames;
712 if ( $coreLanguageNames === null ) {
713 include( MWInit
::compiledPath( 'languages/Names.php' ) );
719 # TODO: also include when $inLanguage is null, when this code is more efficient
720 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
723 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
724 foreach ( $mwNames as $mwCode => $mwName ) {
725 # - Prefer own MediaWiki native name when not using the hook
726 # TODO: prefer it always to make it consistent, but casing is different in CLDR
727 # - For other names just add if not added through the hook
728 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
729 $names[$mwCode] = $mwName;
733 if ( $include === 'all' ) {
738 $coreCodes = array_keys( $mwNames );
739 foreach( $coreCodes as $coreCode ) {
740 $returnMw[$coreCode] = $names[$coreCode];
743 if( $include === 'mwfile' ) {
744 $namesMwFile = array();
745 # We do this using a foreach over the codes instead of a directory
746 # loop so that messages files in extensions will work correctly.
747 foreach ( $returnMw as $code => $value ) {
748 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
749 $namesMwFile[$code] = $names[$code];
754 # 'mw' option; default if it's not one of the other two options (all/mwfile)
759 * @param $code string: The code of the language for which to get the name
760 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
761 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
762 * @return string: Language name or empty
765 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
766 $array = self
::fetchLanguageNames( $inLanguage, $include );
767 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
771 * Get a message from the MediaWiki namespace.
773 * @param $msg String: message name
776 function getMessageFromDB( $msg ) {
777 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
781 * Get the native language name of $code.
782 * Only if defined in MediaWiki, no other data like CLDR.
783 * @param $code string
785 * @deprecated in 1.20, use fetchLanguageName()
787 function getLanguageName( $code ) {
788 return self
::fetchLanguageName( $code );
795 function getMonthName( $key ) {
796 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
802 function getMonthNamesArray() {
803 $monthNames = array( '' );
804 for ( $i = 1; $i < 13; $i++
) {
805 $monthNames[] = $this->getMonthName( $i );
814 function getMonthNameGen( $key ) {
815 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
822 function getMonthAbbreviation( $key ) {
823 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
829 function getMonthAbbreviationsArray() {
830 $monthNames = array( '' );
831 for ( $i = 1; $i < 13; $i++
) {
832 $monthNames[] = $this->getMonthAbbreviation( $i );
841 function getWeekdayName( $key ) {
842 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
849 function getWeekdayAbbreviation( $key ) {
850 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
857 function getIranianCalendarMonthName( $key ) {
858 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
865 function getHebrewCalendarMonthName( $key ) {
866 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
873 function getHebrewCalendarMonthNameGen( $key ) {
874 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
881 function getHijriCalendarMonthName( $key ) {
882 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
886 * This is a workalike of PHP's date() function, but with better
887 * internationalisation, a reduced set of format characters, and a better
890 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
891 * PHP manual for definitions. There are a number of extensions, which
894 * xn Do not translate digits of the next numeric format character
895 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
896 * xr Use roman numerals for the next numeric format character
897 * xh Use hebrew numerals for the next numeric format character
899 * xg Genitive month name
901 * xij j (day number) in Iranian calendar
902 * xiF F (month name) in Iranian calendar
903 * xin n (month number) in Iranian calendar
904 * xiy y (two digit year) in Iranian calendar
905 * xiY Y (full year) in Iranian calendar
907 * xjj j (day number) in Hebrew calendar
908 * xjF F (month name) in Hebrew calendar
909 * xjt t (days in month) in Hebrew calendar
910 * xjx xg (genitive month name) in Hebrew calendar
911 * xjn n (month number) in Hebrew calendar
912 * xjY Y (full year) in Hebrew calendar
914 * xmj j (day number) in Hijri calendar
915 * xmF F (month name) in Hijri calendar
916 * xmn n (month number) in Hijri calendar
917 * xmY Y (full year) in Hijri calendar
919 * xkY Y (full year) in Thai solar calendar. Months and days are
920 * identical to the Gregorian calendar
921 * xoY Y (full year) in Minguo calendar or Juche year.
922 * Months and days are identical to the
924 * xtY Y (full year) in Japanese nengo. Months and days are
925 * identical to the Gregorian calendar
927 * Characters enclosed in double quotes will be considered literal (with
928 * the quotes themselves removed). Unmatched quotes will be considered
929 * literal quotes. Example:
931 * "The month is" F => The month is January
934 * Backslash escaping is also supported.
936 * Input timestamp is assumed to be pre-normalized to the desired local
939 * @param $format String
940 * @param $ts String: 14-character timestamp
943 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
947 function sprintfDate( $format, $ts ) {
960 for ( $p = 0; $p < strlen( $format ); $p++
) {
963 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
964 $code .= $format[++
$p];
967 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
968 $code .= $format[++
$p];
979 $rawToggle = !$rawToggle;
988 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
991 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
992 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
995 $num = substr( $ts, 6, 2 );
998 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
999 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1002 $num = intval( substr( $ts, 6, 2 ) );
1006 $iranian = self
::tsToIranian( $ts );
1012 $hijri = self
::tsToHijri( $ts );
1018 $hebrew = self
::tsToHebrew( $ts );
1024 $unix = wfTimestamp( TS_UNIX
, $ts );
1026 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1030 $unix = wfTimestamp( TS_UNIX
, $ts );
1032 $w = gmdate( 'w', $unix );
1037 $unix = wfTimestamp( TS_UNIX
, $ts );
1039 $num = gmdate( 'w', $unix );
1043 $unix = wfTimestamp( TS_UNIX
, $ts );
1045 $num = gmdate( 'z', $unix );
1049 $unix = wfTimestamp( TS_UNIX
, $ts );
1051 $num = gmdate( 'W', $unix );
1054 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1058 $iranian = self
::tsToIranian( $ts );
1060 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1064 $hijri = self
::tsToHijri( $ts );
1066 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1070 $hebrew = self
::tsToHebrew( $ts );
1072 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1075 $num = substr( $ts, 4, 2 );
1078 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1081 $num = intval( substr( $ts, 4, 2 ) );
1085 $iranian = self
::tsToIranian( $ts );
1091 $hijri = self
::tsToHijri ( $ts );
1097 $hebrew = self
::tsToHebrew( $ts );
1103 $unix = wfTimestamp( TS_UNIX
, $ts );
1105 $num = gmdate( 't', $unix );
1109 $hebrew = self
::tsToHebrew( $ts );
1115 $unix = wfTimestamp( TS_UNIX
, $ts );
1117 $num = gmdate( 'L', $unix );
1121 $unix = wfTimestamp( TS_UNIX
, $ts );
1123 $num = gmdate( 'o', $unix );
1126 $num = substr( $ts, 0, 4 );
1130 $iranian = self
::tsToIranian( $ts );
1136 $hijri = self
::tsToHijri( $ts );
1142 $hebrew = self
::tsToHebrew( $ts );
1148 $thai = self
::tsToYear( $ts, 'thai' );
1154 $minguo = self
::tsToYear( $ts, 'minguo' );
1160 $tenno = self
::tsToYear( $ts, 'tenno' );
1165 $num = substr( $ts, 2, 2 );
1169 $iranian = self
::tsToIranian( $ts );
1171 $num = substr( $iranian[0], -2 );
1174 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1177 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1180 $h = substr( $ts, 8, 2 );
1181 $num = $h %
12 ?
$h %
12 : 12;
1184 $num = intval( substr( $ts, 8, 2 ) );
1187 $h = substr( $ts, 8, 2 );
1188 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1191 $num = substr( $ts, 8, 2 );
1194 $num = substr( $ts, 10, 2 );
1197 $num = substr( $ts, 12, 2 );
1201 $unix = wfTimestamp( TS_UNIX
, $ts );
1203 $s .= gmdate( 'c', $unix );
1207 $unix = wfTimestamp( TS_UNIX
, $ts );
1209 $s .= gmdate( 'r', $unix );
1213 $unix = wfTimestamp( TS_UNIX
, $ts );
1218 # Backslash escaping
1219 if ( $p < strlen( $format ) - 1 ) {
1220 $s .= $format[++
$p];
1227 if ( $p < strlen( $format ) - 1 ) {
1228 $endQuote = strpos( $format, '"', $p +
1 );
1229 if ( $endQuote === false ) {
1230 # No terminating quote, assume literal "
1233 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1237 # Quote at end of string, assume literal "
1244 if ( $num !== false ) {
1245 if ( $rawToggle ||
$raw ) {
1248 } elseif ( $roman ) {
1249 $s .= self
::romanNumeral( $num );
1251 } elseif ( $hebrewNum ) {
1252 $s .= self
::hebrewNumeral( $num );
1255 $s .= $this->formatNum( $num, true );
1262 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1263 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1266 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1267 * Gregorian dates to Iranian dates. Originally written in C, it
1268 * is released under the terms of GNU Lesser General Public
1269 * License. Conversion to PHP was performed by Niklas Laxström.
1271 * Link: http://www.farsiweb.info/jalali/jalali.c
1277 private static function tsToIranian( $ts ) {
1278 $gy = substr( $ts, 0, 4 ) -1600;
1279 $gm = substr( $ts, 4, 2 ) -1;
1280 $gd = substr( $ts, 6, 2 ) -1;
1282 # Days passed from the beginning (including leap years)
1284 +
floor( ( $gy +
3 ) / 4 )
1285 - floor( ( $gy +
99 ) / 100 )
1286 +
floor( ( $gy +
399 ) / 400 );
1288 // Add days of the past months of this year
1289 for ( $i = 0; $i < $gm; $i++
) {
1290 $gDayNo +
= self
::$GREG_DAYS[$i];
1294 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1298 // Days passed in current month
1299 $gDayNo +
= (int)$gd;
1301 $jDayNo = $gDayNo - 79;
1303 $jNp = floor( $jDayNo / 12053 );
1306 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1309 if ( $jDayNo >= 366 ) {
1310 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1311 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1314 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1315 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1321 return array( $jy, $jm, $jd );
1325 * Converting Gregorian dates to Hijri dates.
1327 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1329 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1335 private static function tsToHijri( $ts ) {
1336 $year = substr( $ts, 0, 4 );
1337 $month = substr( $ts, 4, 2 );
1338 $day = substr( $ts, 6, 2 );
1346 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1347 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1350 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1351 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1352 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1355 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1356 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1359 $zl = $zjd -1948440 +
10632;
1360 $zn = (int)( ( $zl - 1 ) / 10631 );
1361 $zl = $zl - 10631 * $zn +
354;
1362 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1363 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1364 $zm = (int)( ( 24 * $zl ) / 709 );
1365 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1366 $zy = 30 * $zn +
$zj - 30;
1368 return array( $zy, $zm, $zd );
1372 * Converting Gregorian dates to Hebrew dates.
1374 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1375 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1376 * to translate the relevant functions into PHP and release them under
1379 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1380 * and Adar II is 14. In a non-leap year, Adar is 6.
1386 private static function tsToHebrew( $ts ) {
1388 $year = substr( $ts, 0, 4 );
1389 $month = substr( $ts, 4, 2 );
1390 $day = substr( $ts, 6, 2 );
1392 # Calculate Hebrew year
1393 $hebrewYear = $year +
3760;
1395 # Month number when September = 1, August = 12
1397 if ( $month > 12 ) {
1404 # Calculate day of year from 1 September
1406 for ( $i = 1; $i < $month; $i++
) {
1410 # Check if the year is leap
1411 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1414 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1421 # Calculate the start of the Hebrew year
1422 $start = self
::hebrewYearStart( $hebrewYear );
1424 # Calculate next year's start
1425 if ( $dayOfYear <= $start ) {
1426 # Day is before the start of the year - it is the previous year
1428 $nextStart = $start;
1432 # Add days since previous year's 1 September
1434 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1438 # Start of the new (previous) year
1439 $start = self
::hebrewYearStart( $hebrewYear );
1442 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1445 # Calculate Hebrew day of year
1446 $hebrewDayOfYear = $dayOfYear - $start;
1448 # Difference between year's days
1449 $diff = $nextStart - $start;
1450 # Add 12 (or 13 for leap years) days to ignore the difference between
1451 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1452 # difference is only about the year type
1453 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1459 # Check the year pattern, and is leap year
1460 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1461 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1462 # and non-leap years
1463 $yearPattern = $diff %
30;
1464 # Check if leap year
1465 $isLeap = $diff >= 30;
1467 # Calculate day in the month from number of day in the Hebrew year
1468 # Don't check Adar - if the day is not in Adar, we will stop before;
1469 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1470 $hebrewDay = $hebrewDayOfYear;
1473 while ( $hebrewMonth <= 12 ) {
1474 # Calculate days in this month
1475 if ( $isLeap && $hebrewMonth == 6 ) {
1476 # Adar in a leap year
1478 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1480 if ( $hebrewDay <= $days ) {
1484 # Subtract the days of Adar I
1485 $hebrewDay -= $days;
1488 if ( $hebrewDay <= $days ) {
1494 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1495 # Cheshvan in a complete year (otherwise as the rule below)
1497 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1498 # Kislev in an incomplete year (otherwise as the rule below)
1501 # Odd months have 30 days, even have 29
1502 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1504 if ( $hebrewDay <= $days ) {
1505 # In the current month
1508 # Subtract the days of the current month
1509 $hebrewDay -= $days;
1510 # Try in the next month
1515 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1519 * This calculates the Hebrew year start, as days since 1 September.
1520 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1521 * Used for Hebrew date.
1527 private static function hebrewYearStart( $year ) {
1528 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1529 $b = intval( ( $year - 1 ) %
4 );
1530 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1534 $Mar = intval( $m );
1540 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1541 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1543 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1545 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1549 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1554 * Algorithm to convert Gregorian dates to Thai solar dates,
1555 * Minguo dates or Minguo dates.
1557 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1558 * http://en.wikipedia.org/wiki/Minguo_calendar
1559 * http://en.wikipedia.org/wiki/Japanese_era_name
1561 * @param $ts String: 14-character timestamp
1562 * @param $cName String: calender name
1563 * @return Array: converted year, month, day
1565 private static function tsToYear( $ts, $cName ) {
1566 $gy = substr( $ts, 0, 4 );
1567 $gm = substr( $ts, 4, 2 );
1568 $gd = substr( $ts, 6, 2 );
1570 if ( !strcmp( $cName, 'thai' ) ) {
1572 # Add 543 years to the Gregorian calendar
1573 # Months and days are identical
1574 $gy_offset = $gy +
543;
1575 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1577 # Deduct 1911 years from the Gregorian calendar
1578 # Months and days are identical
1579 $gy_offset = $gy - 1911;
1580 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1581 # Nengō dates up to Meiji period
1582 # Deduct years from the Gregorian calendar
1583 # depending on the nengo periods
1584 # Months and days are identical
1585 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1587 $gy_gannen = $gy - 1868 +
1;
1588 $gy_offset = $gy_gannen;
1589 if ( $gy_gannen == 1 ) {
1592 $gy_offset = '明治' . $gy_offset;
1594 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1595 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1596 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1597 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1598 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1602 $gy_gannen = $gy - 1912 +
1;
1603 $gy_offset = $gy_gannen;
1604 if ( $gy_gannen == 1 ) {
1607 $gy_offset = '大正' . $gy_offset;
1609 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1610 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1611 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1615 $gy_gannen = $gy - 1926 +
1;
1616 $gy_offset = $gy_gannen;
1617 if ( $gy_gannen == 1 ) {
1620 $gy_offset = '昭和' . $gy_offset;
1623 $gy_gannen = $gy - 1989 +
1;
1624 $gy_offset = $gy_gannen;
1625 if ( $gy_gannen == 1 ) {
1628 $gy_offset = '平成' . $gy_offset;
1634 return array( $gy_offset, $gm, $gd );
1638 * Roman number formatting up to 3000
1644 static function romanNumeral( $num ) {
1645 static $table = array(
1646 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1647 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1648 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1649 array( '', 'M', 'MM', 'MMM' )
1652 $num = intval( $num );
1653 if ( $num > 3000 ||
$num <= 0 ) {
1658 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1659 if ( $num >= $pow10 ) {
1660 $s .= $table[$i][(int)floor( $num / $pow10 )];
1662 $num = $num %
$pow10;
1668 * Hebrew Gematria number formatting up to 9999
1674 static function hebrewNumeral( $num ) {
1675 static $table = array(
1676 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1677 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1678 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1679 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1682 $num = intval( $num );
1683 if ( $num > 9999 ||
$num <= 0 ) {
1688 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1689 if ( $num >= $pow10 ) {
1690 if ( $num == 15 ||
$num == 16 ) {
1691 $s .= $table[0][9] . $table[0][$num - 9];
1694 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1695 if ( $pow10 == 1000 ) {
1700 $num = $num %
$pow10;
1702 if ( strlen( $s ) == 2 ) {
1705 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1706 $str .= substr( $s, strlen( $s ) - 2, 2 );
1708 $start = substr( $str, 0, strlen( $str ) - 2 );
1709 $end = substr( $str, strlen( $str ) - 2 );
1712 $str = $start . 'ך';
1715 $str = $start . 'ם';
1718 $str = $start . 'ן';
1721 $str = $start . 'ף';
1724 $str = $start . 'ץ';
1731 * Used by date() and time() to adjust the time output.
1733 * @param $ts Int the time in date('YmdHis') format
1734 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1735 * get user timecorrection setting)
1738 function userAdjust( $ts, $tz = false ) {
1739 global $wgUser, $wgLocalTZoffset;
1741 if ( $tz === false ) {
1742 $tz = $wgUser->getOption( 'timecorrection' );
1745 $data = explode( '|', $tz, 3 );
1747 if ( $data[0] == 'ZoneInfo' ) {
1748 wfSuppressWarnings();
1749 $userTZ = timezone_open( $data[2] );
1750 wfRestoreWarnings();
1751 if ( $userTZ !== false ) {
1752 $date = date_create( $ts, timezone_open( 'UTC' ) );
1753 date_timezone_set( $date, $userTZ );
1754 $date = date_format( $date, 'YmdHis' );
1757 # Unrecognized timezone, default to 'Offset' with the stored offset.
1758 $data[0] = 'Offset';
1762 if ( $data[0] == 'System' ||
$tz == '' ) {
1763 # Global offset in minutes.
1764 if ( isset( $wgLocalTZoffset ) ) {
1765 $minDiff = $wgLocalTZoffset;
1767 } elseif ( $data[0] == 'Offset' ) {
1768 $minDiff = intval( $data[1] );
1770 $data = explode( ':', $tz );
1771 if ( count( $data ) == 2 ) {
1772 $data[0] = intval( $data[0] );
1773 $data[1] = intval( $data[1] );
1774 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1775 if ( $data[0] < 0 ) {
1776 $minDiff = -$minDiff;
1779 $minDiff = intval( $data[0] ) * 60;
1783 # No difference ? Return time unchanged
1784 if ( 0 == $minDiff ) {
1788 wfSuppressWarnings(); // E_STRICT system time bitching
1789 # Generate an adjusted date; take advantage of the fact that mktime
1790 # will normalize out-of-range values so we don't have to split $minDiff
1791 # into hours and minutes.
1793 (int)substr( $ts, 8, 2 ) ), # Hours
1794 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1795 (int)substr( $ts, 12, 2 ), # Seconds
1796 (int)substr( $ts, 4, 2 ), # Month
1797 (int)substr( $ts, 6, 2 ), # Day
1798 (int)substr( $ts, 0, 4 ) ); # Year
1800 $date = date( 'YmdHis', $t );
1801 wfRestoreWarnings();
1807 * This is meant to be used by time(), date(), and timeanddate() to get
1808 * the date preference they're supposed to use, it should be used in
1812 * function timeanddate([...], $format = true) {
1813 * $datePreference = $this->dateFormat($format);
1818 * @param $usePrefs Mixed: if true, the user's preference is used
1819 * if false, the site/language default is used
1820 * if int/string, assumed to be a format.
1823 function dateFormat( $usePrefs = true ) {
1826 if ( is_bool( $usePrefs ) ) {
1828 $datePreference = $wgUser->getDatePreference();
1830 $datePreference = (string)User
::getDefaultOption( 'date' );
1833 $datePreference = (string)$usePrefs;
1837 if ( $datePreference == '' ) {
1841 return $datePreference;
1845 * Get a format string for a given type and preference
1846 * @param $type string May be date, time or both
1847 * @param $pref string The format name as it appears in Messages*.php
1851 function getDateFormatString( $type, $pref ) {
1852 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1853 if ( $pref == 'default' ) {
1854 $pref = $this->getDefaultDateFormat();
1855 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1857 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1858 if ( is_null( $df ) ) {
1859 $pref = $this->getDefaultDateFormat();
1860 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1863 $this->dateFormatStrings
[$type][$pref] = $df;
1865 return $this->dateFormatStrings
[$type][$pref];
1869 * @param $ts Mixed: the time format which needs to be turned into a
1870 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1871 * @param $adj Bool: whether to adjust the time output according to the
1872 * user configured offset ($timecorrection)
1873 * @param $format Mixed: true to use user's date format preference
1874 * @param $timecorrection String|bool the time offset as returned by
1875 * validateTimeZone() in Special:Preferences
1878 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1879 $ts = wfTimestamp( TS_MW
, $ts );
1881 $ts = $this->userAdjust( $ts, $timecorrection );
1883 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1884 return $this->sprintfDate( $df, $ts );
1888 * @param $ts Mixed: the time format which needs to be turned into a
1889 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1890 * @param $adj Bool: whether to adjust the time output according to the
1891 * user configured offset ($timecorrection)
1892 * @param $format Mixed: true to use user's date format preference
1893 * @param $timecorrection String|bool the time offset as returned by
1894 * validateTimeZone() in Special:Preferences
1897 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1898 $ts = wfTimestamp( TS_MW
, $ts );
1900 $ts = $this->userAdjust( $ts, $timecorrection );
1902 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1903 return $this->sprintfDate( $df, $ts );
1907 * @param $ts Mixed: the time format which needs to be turned into a
1908 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1909 * @param $adj Bool: whether to adjust the time output according to the
1910 * user configured offset ($timecorrection)
1911 * @param $format Mixed: what format to return, if it's false output the
1912 * default one (default true)
1913 * @param $timecorrection String|bool the time offset as returned by
1914 * validateTimeZone() in Special:Preferences
1917 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1918 $ts = wfTimestamp( TS_MW
, $ts );
1920 $ts = $this->userAdjust( $ts, $timecorrection );
1922 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1923 return $this->sprintfDate( $df, $ts );
1927 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1931 * @param integer $seconds The amount of seconds.
1932 * @param array $chosenIntervals The intervals to enable.
1936 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1937 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1939 $segments = array();
1941 foreach ( $intervals as $intervalName => $intervalValue ) {
1942 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1943 $segments[] = $message->inLanguage( $this )->escaped();
1946 return $this->listToText( $segments );
1950 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1951 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1955 * @param integer $seconds The amount of seconds.
1956 * @param array $chosenIntervals The intervals to enable.
1960 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1961 if ( empty( $chosenIntervals ) ) {
1962 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1965 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
1966 $sortedNames = array_keys( $intervals );
1967 $smallestInterval = array_pop( $sortedNames );
1969 $segments = array();
1971 foreach ( $intervals as $name => $length ) {
1972 $value = floor( $seconds / $length );
1974 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
1975 $seconds -= $value * $length;
1976 $segments[$name] = $value;
1984 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1986 * @param $type String: can be 'date', 'time' or 'both'
1987 * @param $ts Mixed: the time format which needs to be turned into a
1988 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1989 * @param $user User object used to get preferences for timezone and format
1990 * @param $options Array, can contain the following keys:
1991 * - 'timecorrection': time correction, can have the following values:
1992 * - true: use user's preference
1993 * - false: don't use time correction
1994 * - integer: value of time correction in minutes
1995 * - 'format': format to use, can have the following values:
1996 * - true: use user's preference
1997 * - false: use default preference
1998 * - string: format to use
2002 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2003 $ts = wfTimestamp( TS_MW
, $ts );
2004 $options +
= array( 'timecorrection' => true, 'format' => true );
2005 if ( $options['timecorrection'] !== false ) {
2006 if ( $options['timecorrection'] === true ) {
2007 $offset = $user->getOption( 'timecorrection' );
2009 $offset = $options['timecorrection'];
2011 $ts = $this->userAdjust( $ts, $offset );
2013 if ( $options['format'] === true ) {
2014 $format = $user->getDatePreference();
2016 $format = $options['format'];
2018 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2019 return $this->sprintfDate( $df, $ts );
2023 * Get the formatted date for the given timestamp and formatted for
2026 * @param $ts Mixed: the time format which needs to be turned into a
2027 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2028 * @param $user User object used to get preferences for timezone and format
2029 * @param $options Array, can contain the following keys:
2030 * - 'timecorrection': time correction, can have the following values:
2031 * - true: use user's preference
2032 * - false: don't use time correction
2033 * - integer: value of time correction in minutes
2034 * - 'format': format to use, can have the following values:
2035 * - true: use user's preference
2036 * - false: use default preference
2037 * - string: format to use
2041 public function userDate( $ts, User
$user, array $options = array() ) {
2042 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2046 * Get the formatted time for the given timestamp and formatted for
2049 * @param $ts Mixed: the time format which needs to be turned into a
2050 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2051 * @param $user User object used to get preferences for timezone and format
2052 * @param $options Array, can contain the following keys:
2053 * - 'timecorrection': time correction, can have the following values:
2054 * - true: use user's preference
2055 * - false: don't use time correction
2056 * - integer: value of time correction in minutes
2057 * - 'format': format to use, can have the following values:
2058 * - true: use user's preference
2059 * - false: use default preference
2060 * - string: format to use
2064 public function userTime( $ts, User
$user, array $options = array() ) {
2065 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2069 * Get the formatted date and time for the given timestamp and formatted for
2072 * @param $ts Mixed: the time format which needs to be turned into a
2073 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2074 * @param $user User object used to get preferences for timezone and format
2075 * @param $options Array, can contain the following keys:
2076 * - 'timecorrection': time correction, can have the following values:
2077 * - true: use user's preference
2078 * - false: don't use time correction
2079 * - integer: value of time correction in minutes
2080 * - 'format': format to use, can have the following values:
2081 * - true: use user's preference
2082 * - false: use default preference
2083 * - string: format to use
2087 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2088 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2092 * @param $key string
2093 * @return array|null
2095 function getMessage( $key ) {
2096 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2102 function getAllMessages() {
2103 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2112 function iconv( $in, $out, $string ) {
2113 # This is a wrapper for iconv in all languages except esperanto,
2114 # which does some nasty x-conversions beforehand
2116 # Even with //IGNORE iconv can whine about illegal characters in
2117 # *input* string. We just ignore those too.
2118 # REF: http://bugs.php.net/bug.php?id=37166
2119 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2120 wfSuppressWarnings();
2121 $text = iconv( $in, $out . '//IGNORE', $string );
2122 wfRestoreWarnings();
2126 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2129 * @param $matches array
2130 * @return mixed|string
2132 function ucwordbreaksCallbackAscii( $matches ) {
2133 return $this->ucfirst( $matches[1] );
2137 * @param $matches array
2140 function ucwordbreaksCallbackMB( $matches ) {
2141 return mb_strtoupper( $matches[0] );
2145 * @param $matches array
2148 function ucCallback( $matches ) {
2149 list( $wikiUpperChars ) = self
::getCaseMaps();
2150 return strtr( $matches[1], $wikiUpperChars );
2154 * @param $matches array
2157 function lcCallback( $matches ) {
2158 list( , $wikiLowerChars ) = self
::getCaseMaps();
2159 return strtr( $matches[1], $wikiLowerChars );
2163 * @param $matches array
2166 function ucwordsCallbackMB( $matches ) {
2167 return mb_strtoupper( $matches[0] );
2171 * @param $matches array
2174 function ucwordsCallbackWiki( $matches ) {
2175 list( $wikiUpperChars ) = self
::getCaseMaps();
2176 return strtr( $matches[0], $wikiUpperChars );
2180 * Make a string's first character uppercase
2182 * @param $str string
2186 function ucfirst( $str ) {
2188 if ( $o < 96 ) { // if already uppercase...
2190 } elseif ( $o < 128 ) {
2191 return ucfirst( $str ); // use PHP's ucfirst()
2193 // fall back to more complex logic in case of multibyte strings
2194 return $this->uc( $str, true );
2199 * Convert a string to uppercase
2201 * @param $str string
2202 * @param $first bool
2206 function uc( $str, $first = false ) {
2207 if ( function_exists( 'mb_strtoupper' ) ) {
2209 if ( $this->isMultibyte( $str ) ) {
2210 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2212 return ucfirst( $str );
2215 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2218 if ( $this->isMultibyte( $str ) ) {
2219 $x = $first ?
'^' : '';
2220 return preg_replace_callback(
2221 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2222 array( $this, 'ucCallback' ),
2226 return $first ?
ucfirst( $str ) : strtoupper( $str );
2232 * @param $str string
2233 * @return mixed|string
2235 function lcfirst( $str ) {
2238 return strval( $str );
2239 } elseif ( $o >= 128 ) {
2240 return $this->lc( $str, true );
2241 } elseif ( $o > 96 ) {
2244 $str[0] = strtolower( $str[0] );
2250 * @param $str string
2251 * @param $first bool
2252 * @return mixed|string
2254 function lc( $str, $first = false ) {
2255 if ( function_exists( 'mb_strtolower' ) ) {
2257 if ( $this->isMultibyte( $str ) ) {
2258 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2260 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2263 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2266 if ( $this->isMultibyte( $str ) ) {
2267 $x = $first ?
'^' : '';
2268 return preg_replace_callback(
2269 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2270 array( $this, 'lcCallback' ),
2274 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2280 * @param $str string
2283 function isMultibyte( $str ) {
2284 return (bool)preg_match( '/[\x80-\xff]/', $str );
2288 * @param $str string
2289 * @return mixed|string
2291 function ucwords( $str ) {
2292 if ( $this->isMultibyte( $str ) ) {
2293 $str = $this->lc( $str );
2295 // regexp to find first letter in each word (i.e. after each space)
2296 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2298 // function to use to capitalize a single char
2299 if ( function_exists( 'mb_strtoupper' ) ) {
2300 return preg_replace_callback(
2302 array( $this, 'ucwordsCallbackMB' ),
2306 return preg_replace_callback(
2308 array( $this, 'ucwordsCallbackWiki' ),
2313 return ucwords( strtolower( $str ) );
2318 * capitalize words at word breaks
2320 * @param $str string
2323 function ucwordbreaks( $str ) {
2324 if ( $this->isMultibyte( $str ) ) {
2325 $str = $this->lc( $str );
2327 // since \b doesn't work for UTF-8, we explicitely define word break chars
2328 $breaks = "[ \-\(\)\}\{\.,\?!]";
2330 // find first letter after word break
2331 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2333 if ( function_exists( 'mb_strtoupper' ) ) {
2334 return preg_replace_callback(
2336 array( $this, 'ucwordbreaksCallbackMB' ),
2340 return preg_replace_callback(
2342 array( $this, 'ucwordsCallbackWiki' ),
2347 return preg_replace_callback(
2348 '/\b([\w\x80-\xff]+)\b/',
2349 array( $this, 'ucwordbreaksCallbackAscii' ),
2356 * Return a case-folded representation of $s
2358 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2359 * and $s2 are the same except for the case of their characters. It is not
2360 * necessary for the value returned to make sense when displayed.
2362 * Do *not* perform any other normalisation in this function. If a caller
2363 * uses this function when it should be using a more general normalisation
2364 * function, then fix the caller.
2370 function caseFold( $s ) {
2371 return $this->uc( $s );
2378 function checkTitleEncoding( $s ) {
2379 if ( is_array( $s ) ) {
2380 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2382 # Check for non-UTF-8 URLs
2383 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2388 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2389 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2394 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2400 function fallback8bitEncoding() {
2401 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2405 * Most writing systems use whitespace to break up words.
2406 * Some languages such as Chinese don't conventionally do this,
2407 * which requires special handling when breaking up words for
2412 function hasWordBreaks() {
2417 * Some languages such as Chinese require word segmentation,
2418 * Specify such segmentation when overridden in derived class.
2420 * @param $string String
2423 function segmentByWord( $string ) {
2428 * Some languages have special punctuation need to be normalized.
2429 * Make such changes here.
2431 * @param $string String
2434 function normalizeForSearch( $string ) {
2435 return self
::convertDoubleWidth( $string );
2439 * convert double-width roman characters to single-width.
2440 * range: ff00-ff5f ~= 0020-007f
2442 * @param $string string
2446 protected static function convertDoubleWidth( $string ) {
2447 static $full = null;
2448 static $half = null;
2450 if ( $full === null ) {
2451 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2452 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2453 $full = str_split( $fullWidth, 3 );
2454 $half = str_split( $halfWidth );
2457 $string = str_replace( $full, $half, $string );
2462 * @param $string string
2463 * @param $pattern string
2466 protected static function insertSpace( $string, $pattern ) {
2467 $string = preg_replace( $pattern, " $1 ", $string );
2468 $string = preg_replace( '/ +/', ' ', $string );
2473 * @param $termsArray array
2476 function convertForSearchResult( $termsArray ) {
2477 # some languages, e.g. Chinese, need to do a conversion
2478 # in order for search results to be displayed correctly
2483 * Get the first character of a string.
2488 function firstChar( $s ) {
2491 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2492 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2497 if ( isset( $matches[1] ) ) {
2498 if ( strlen( $matches[1] ) != 3 ) {
2502 // Break down Hangul syllables to grab the first jamo
2503 $code = utf8ToCodepoint( $matches[1] );
2504 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2506 } elseif ( $code < 0xb098 ) {
2507 return "\xe3\x84\xb1";
2508 } elseif ( $code < 0xb2e4 ) {
2509 return "\xe3\x84\xb4";
2510 } elseif ( $code < 0xb77c ) {
2511 return "\xe3\x84\xb7";
2512 } elseif ( $code < 0xb9c8 ) {
2513 return "\xe3\x84\xb9";
2514 } elseif ( $code < 0xbc14 ) {
2515 return "\xe3\x85\x81";
2516 } elseif ( $code < 0xc0ac ) {
2517 return "\xe3\x85\x82";
2518 } elseif ( $code < 0xc544 ) {
2519 return "\xe3\x85\x85";
2520 } elseif ( $code < 0xc790 ) {
2521 return "\xe3\x85\x87";
2522 } elseif ( $code < 0xcc28 ) {
2523 return "\xe3\x85\x88";
2524 } elseif ( $code < 0xce74 ) {
2525 return "\xe3\x85\x8a";
2526 } elseif ( $code < 0xd0c0 ) {
2527 return "\xe3\x85\x8b";
2528 } elseif ( $code < 0xd30c ) {
2529 return "\xe3\x85\x8c";
2530 } elseif ( $code < 0xd558 ) {
2531 return "\xe3\x85\x8d";
2533 return "\xe3\x85\x8e";
2540 function initEncoding() {
2541 # Some languages may have an alternate char encoding option
2542 # (Esperanto X-coding, Japanese furigana conversion, etc)
2543 # If this language is used as the primary content language,
2544 # an override to the defaults can be set here on startup.
2551 function recodeForEdit( $s ) {
2552 # For some languages we'll want to explicitly specify
2553 # which characters make it into the edit box raw
2554 # or are converted in some way or another.
2555 global $wgEditEncoding;
2556 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2559 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2567 function recodeInput( $s ) {
2568 # Take the previous into account.
2569 global $wgEditEncoding;
2570 if ( $wgEditEncoding != '' ) {
2571 $enc = $wgEditEncoding;
2575 if ( $enc == 'UTF-8' ) {
2578 return $this->iconv( $enc, 'UTF-8', $s );
2583 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2584 * also cleans up certain backwards-compatible sequences, converting them
2585 * to the modern Unicode equivalent.
2587 * This is language-specific for performance reasons only.
2593 function normalize( $s ) {
2594 global $wgAllUnicodeFixes;
2595 $s = UtfNormal
::cleanUp( $s );
2596 if ( $wgAllUnicodeFixes ) {
2597 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2598 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2605 * Transform a string using serialized data stored in the given file (which
2606 * must be in the serialized subdirectory of $IP). The file contains pairs
2607 * mapping source characters to destination characters.
2609 * The data is cached in process memory. This will go faster if you have the
2610 * FastStringSearch extension.
2612 * @param $file string
2613 * @param $string string
2615 * @throws MWException
2618 function transformUsingPairFile( $file, $string ) {
2619 if ( !isset( $this->transformData
[$file] ) ) {
2620 $data = wfGetPrecompiledData( $file );
2621 if ( $data === false ) {
2622 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2624 $this->transformData
[$file] = new ReplacementArray( $data );
2626 return $this->transformData
[$file]->replace( $string );
2630 * For right-to-left language support
2635 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2639 * Return the correct HTML 'dir' attribute value for this language.
2643 return $this->isRTL() ?
'rtl' : 'ltr';
2647 * Return 'left' or 'right' as appropriate alignment for line-start
2648 * for this language's text direction.
2650 * Should be equivalent to CSS3 'start' text-align value....
2654 function alignStart() {
2655 return $this->isRTL() ?
'right' : 'left';
2659 * Return 'right' or 'left' as appropriate alignment for line-end
2660 * for this language's text direction.
2662 * Should be equivalent to CSS3 'end' text-align value....
2666 function alignEnd() {
2667 return $this->isRTL() ?
'left' : 'right';
2671 * A hidden direction mark (LRM or RLM), depending on the language direction.
2672 * Unlike getDirMark(), this function returns the character as an HTML entity.
2673 * This function should be used when the output is guaranteed to be HTML,
2674 * because it makes the output HTML source code more readable. When
2675 * the output is plain text or can be escaped, getDirMark() should be used.
2677 * @param $opposite Boolean Get the direction mark opposite to your language
2680 function getDirMarkEntity( $opposite = false ) {
2681 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2682 return $this->isRTL() ?
'‏' : '‎';
2686 * A hidden direction mark (LRM or RLM), depending on the language direction.
2687 * This function produces them as invisible Unicode characters and
2688 * the output may be hard to read and debug, so it should only be used
2689 * when the output is plain text or can be escaped. When the output is
2690 * HTML, use getDirMarkEntity() instead.
2692 * @param $opposite Boolean Get the direction mark opposite to your language
2695 function getDirMark( $opposite = false ) {
2696 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2697 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2698 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2699 return $this->isRTL() ?
$rlm : $lrm;
2705 function capitalizeAllNouns() {
2706 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2710 * An arrow, depending on the language direction
2714 function getArrow() {
2715 return $this->isRTL() ?
'←' : '→';
2719 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2723 function linkPrefixExtension() {
2724 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2730 function getMagicWords() {
2731 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2734 protected function doMagicHook() {
2735 if ( $this->mMagicHookDone
) {
2738 $this->mMagicHookDone
= true;
2739 wfProfileIn( 'LanguageGetMagic' );
2740 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2741 wfProfileOut( 'LanguageGetMagic' );
2745 * Fill a MagicWord object with data from here
2749 function getMagic( $mw ) {
2750 $this->doMagicHook();
2752 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2753 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2755 $magicWords = $this->getMagicWords();
2756 if ( isset( $magicWords[$mw->mId
] ) ) {
2757 $rawEntry = $magicWords[$mw->mId
];
2763 if ( !is_array( $rawEntry ) ) {
2764 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2766 $mw->mCaseSensitive
= $rawEntry[0];
2767 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2772 * Add magic words to the extension array
2774 * @param $newWords array
2776 function addMagicWordsByLang( $newWords ) {
2777 $fallbackChain = $this->getFallbackLanguages();
2778 $fallbackChain = array_reverse( $fallbackChain );
2779 foreach ( $fallbackChain as $code ) {
2780 if ( isset( $newWords[$code] ) ) {
2781 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2787 * Get special page names, as an associative array
2788 * case folded alias => real name
2790 function getSpecialPageAliases() {
2791 // Cache aliases because it may be slow to load them
2792 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2794 $this->mExtendedSpecialPageAliases
=
2795 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2796 wfRunHooks( 'LanguageGetSpecialPageAliases',
2797 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2800 return $this->mExtendedSpecialPageAliases
;
2804 * Italic is unsuitable for some languages
2806 * @param $text String: the text to be emphasized.
2809 function emphasize( $text ) {
2810 return "<em>$text</em>";
2814 * Normally we output all numbers in plain en_US style, that is
2815 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2816 * point twohundredthirtyfive. However this is not suitable for all
2817 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2818 * Icelandic just want to use commas instead of dots, and dots instead
2819 * of commas like "293.291,235".
2821 * An example of this function being called:
2823 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2826 * See LanguageGu.php for the Gujarati implementation and
2827 * $separatorTransformTable on MessageIs.php for
2828 * the , => . and . => , implementation.
2830 * @todo check if it's viable to use localeconv() for the decimal
2832 * @param $number Mixed: the string to be formatted, should be an integer
2833 * or a floating point number.
2834 * @param $nocommafy Bool: set to true for special numbers like dates
2837 public function formatNum( $number, $nocommafy = false ) {
2838 global $wgTranslateNumerals;
2839 if ( !$nocommafy ) {
2840 $number = $this->commafy( $number );
2841 $s = $this->separatorTransformTable();
2843 $number = strtr( $number, $s );
2847 if ( $wgTranslateNumerals ) {
2848 $s = $this->digitTransformTable();
2850 $number = strtr( $number, $s );
2858 * @param $number string
2861 function parseFormattedNumber( $number ) {
2862 $s = $this->digitTransformTable();
2864 $number = strtr( $number, array_flip( $s ) );
2867 $s = $this->separatorTransformTable();
2869 $number = strtr( $number, array_flip( $s ) );
2872 $number = strtr( $number, array( ',' => '' ) );
2877 * Adds commas to a given number
2882 function commafy( $_ ) {
2883 $digitGroupingPattern = $this->digitGroupingPattern();
2884 if ( $_ === null ) {
2888 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2889 // default grouping is at thousands, use the same for ###,###,### pattern too.
2890 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2892 // Ref: http://cldr.unicode.org/translation/number-patterns
2894 if ( intval( $_ ) < 0 ) {
2895 // For negative numbers apply the algorithm like positive number and add sign.
2897 $_ = substr( $_, 1 );
2899 $numberpart = array();
2900 $decimalpart = array();
2901 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2902 preg_match( "/\d+/", $_, $numberpart );
2903 preg_match( "/\.\d*/", $_, $decimalpart );
2904 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2905 if ( $groupedNumber === $_ ) {
2906 // the string does not have any number part. Eg: .12345
2907 return $sign . $groupedNumber;
2909 $start = $end = strlen( $numberpart[0] );
2910 while ( $start > 0 ) {
2911 $match = $matches[0][$numMatches -1] ;
2912 $matchLen = strlen( $match );
2913 $start = $end - $matchLen;
2917 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2919 if ( $numMatches > 1 ) {
2920 // use the last pattern for the rest of the number
2924 $groupedNumber = "," . $groupedNumber;
2927 return $sign . $groupedNumber;
2933 function digitGroupingPattern() {
2934 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2940 function digitTransformTable() {
2941 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2947 function separatorTransformTable() {
2948 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2952 * Take a list of strings and build a locale-friendly comma-separated
2953 * list, using the local comma-separator message.
2954 * The last two strings are chained with an "and".
2959 function listToText( array $l ) {
2961 $m = count( $l ) - 1;
2963 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2965 for ( $i = $m; $i >= 0; $i-- ) {
2968 } elseif ( $i == $m - 1 ) {
2969 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2971 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2979 * Take a list of strings and build a locale-friendly comma-separated
2980 * list, using the local comma-separator message.
2981 * @param $list array of strings to put in a comma list
2984 function commaList( array $list ) {
2988 array( 'parsemag', 'escapenoentities', 'language' => $this )
2995 * Take a list of strings and build a locale-friendly semicolon-separated
2996 * list, using the local semicolon-separator message.
2997 * @param $list array of strings to put in a semicolon list
3000 function semicolonList( array $list ) {
3003 'semicolon-separator',
3004 array( 'parsemag', 'escapenoentities', 'language' => $this )
3011 * Same as commaList, but separate it with the pipe instead.
3012 * @param $list array of strings to put in a pipe list
3015 function pipeList( array $list ) {
3019 array( 'escapenoentities', 'language' => $this )
3026 * Truncate a string to a specified length in bytes, appending an optional
3027 * string (e.g. for ellipses)
3029 * The database offers limited byte lengths for some columns in the database;
3030 * multi-byte character sets mean we need to ensure that only whole characters
3031 * are included, otherwise broken characters can be passed to the user
3033 * If $length is negative, the string will be truncated from the beginning
3035 * @param $string String to truncate
3036 * @param $length Int: maximum length (including ellipses)
3037 * @param $ellipsis String to append to the truncated text
3038 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3039 * $adjustLength was introduced in 1.18, before that behaved as if false.
3042 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3043 # Use the localized ellipsis character
3044 if ( $ellipsis == '...' ) {
3045 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3047 # Check if there is no need to truncate
3048 if ( $length == 0 ) {
3049 return $ellipsis; // convention
3050 } elseif ( strlen( $string ) <= abs( $length ) ) {
3051 return $string; // no need to truncate
3053 $stringOriginal = $string;
3054 # If ellipsis length is >= $length then we can't apply $adjustLength
3055 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3056 $string = $ellipsis; // this can be slightly unexpected
3057 # Otherwise, truncate and add ellipsis...
3059 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3060 if ( $length > 0 ) {
3061 $length -= $eLength;
3062 $string = substr( $string, 0, $length ); // xyz...
3063 $string = $this->removeBadCharLast( $string );
3064 $string = $string . $ellipsis;
3066 $length +
= $eLength;
3067 $string = substr( $string, $length ); // ...xyz
3068 $string = $this->removeBadCharFirst( $string );
3069 $string = $ellipsis . $string;
3072 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3073 # This check is *not* redundant if $adjustLength, due to the single case where
3074 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3075 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3078 return $stringOriginal;
3083 * Remove bytes that represent an incomplete Unicode character
3084 * at the end of string (e.g. bytes of the char are missing)
3086 * @param $string String
3089 protected function removeBadCharLast( $string ) {
3090 if ( $string != '' ) {
3091 $char = ord( $string[strlen( $string ) - 1] );
3093 if ( $char >= 0xc0 ) {
3094 # We got the first byte only of a multibyte char; remove it.
3095 $string = substr( $string, 0, -1 );
3096 } elseif ( $char >= 0x80 &&
3097 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3098 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3100 # We chopped in the middle of a character; remove it
3108 * Remove bytes that represent an incomplete Unicode character
3109 * at the start of string (e.g. bytes of the char are missing)
3111 * @param $string String
3114 protected function removeBadCharFirst( $string ) {
3115 if ( $string != '' ) {
3116 $char = ord( $string[0] );
3117 if ( $char >= 0x80 && $char < 0xc0 ) {
3118 # We chopped in the middle of a character; remove the whole thing
3119 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3126 * Truncate a string of valid HTML to a specified length in bytes,
3127 * appending an optional string (e.g. for ellipses), and return valid HTML
3129 * This is only intended for styled/linked text, such as HTML with
3130 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3131 * Also, this will not detect things like "display:none" CSS.
3133 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3135 * @param string $text HTML string to truncate
3136 * @param int $length (zero/positive) Maximum length (including ellipses)
3137 * @param string $ellipsis String to append to the truncated text
3140 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3141 # Use the localized ellipsis character
3142 if ( $ellipsis == '...' ) {
3143 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3145 # Check if there is clearly no need to truncate
3146 if ( $length <= 0 ) {
3147 return $ellipsis; // no text shown, nothing to format (convention)
3148 } elseif ( strlen( $text ) <= $length ) {
3149 return $text; // string short enough even *with* HTML (short-circuit)
3152 $dispLen = 0; // innerHTML legth so far
3153 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3154 $tagType = 0; // 0-open, 1-close
3155 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3156 $entityState = 0; // 0-not entity, 1-entity
3157 $tag = $ret = ''; // accumulated tag name, accumulated result string
3158 $openTags = array(); // open tag stack
3159 $maybeState = null; // possible truncation state
3161 $textLen = strlen( $text );
3162 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3163 for ( $pos = 0; true; ++
$pos ) {
3164 # Consider truncation once the display length has reached the maximim.
3165 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3166 # Check that we're not in the middle of a bracket/entity...
3167 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3168 if ( !$testingEllipsis ) {
3169 $testingEllipsis = true;
3170 # Save where we are; we will truncate here unless there turn out to
3171 # be so few remaining characters that truncation is not necessary.
3172 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3173 $maybeState = array( $ret, $openTags ); // save state
3175 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3176 # String in fact does need truncation, the truncation point was OK.
3177 list( $ret, $openTags ) = $maybeState; // reload state
3178 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3179 $ret .= $ellipsis; // add ellipsis
3183 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3185 # Read the next char...
3187 $lastCh = $pos ?
$text[$pos - 1] : '';
3188 $ret .= $ch; // add to result string
3190 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3191 $entityState = 0; // for bad HTML
3192 $bracketState = 1; // tag started (checking for backslash)
3193 } elseif ( $ch == '>' ) {
3194 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3195 $entityState = 0; // for bad HTML
3196 $bracketState = 0; // out of brackets
3197 } elseif ( $bracketState == 1 ) {
3199 $tagType = 1; // close tag (e.g. "</span>")
3201 $tagType = 0; // open tag (e.g. "<span>")
3204 $bracketState = 2; // building tag name
3205 } elseif ( $bracketState == 2 ) {
3209 // Name found (e.g. "<a href=..."), add on tag attributes...
3210 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3212 } elseif ( $bracketState == 0 ) {
3213 if ( $entityState ) {
3216 $dispLen++
; // entity is one displayed char
3219 if ( $neLength == 0 && !$maybeState ) {
3220 // Save state without $ch. We want to *hit* the first
3221 // display char (to get tags) but not *use* it if truncating.
3222 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3225 $entityState = 1; // entity found, (e.g. " ")
3227 $dispLen++
; // this char is displayed
3228 // Add the next $max display text chars after this in one swoop...
3229 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3230 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3231 $dispLen +
= $skipped;
3237 // Close the last tag if left unclosed by bad HTML
3238 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3239 while ( count( $openTags ) > 0 ) {
3240 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3246 * truncateHtml() helper function
3247 * like strcspn() but adds the skipped chars to $ret
3256 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3257 if ( $len === null ) {
3258 $len = -1; // -1 means "no limit" for strcspn
3259 } elseif ( $len < 0 ) {
3263 if ( $start < strlen( $text ) ) {
3264 $skipCount = strcspn( $text, $search, $start, $len );
3265 $ret .= substr( $text, $start, $skipCount );
3271 * truncateHtml() helper function
3272 * (a) push or pop $tag from $openTags as needed
3273 * (b) clear $tag value
3274 * @param &$tag string Current HTML tag name we are looking at
3275 * @param $tagType int (0-open tag, 1-close tag)
3276 * @param $lastCh string Character before the '>' that ended this tag
3277 * @param &$openTags array Open tag stack (not accounting for $tag)
3279 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3280 $tag = ltrim( $tag );
3282 if ( $tagType == 0 && $lastCh != '/' ) {
3283 $openTags[] = $tag; // tag opened (didn't close itself)
3284 } elseif ( $tagType == 1 ) {
3285 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3286 array_pop( $openTags ); // tag closed
3294 * Grammatical transformations, needed for inflected languages
3295 * Invoked by putting {{grammar:case|word}} in a message
3297 * @param $word string
3298 * @param $case string
3301 function convertGrammar( $word, $case ) {
3302 global $wgGrammarForms;
3303 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3304 return $wgGrammarForms[$this->getCode()][$case][$word];
3309 * Get the grammar forms for the content language
3310 * @return array of grammar forms
3313 function getGrammarForms() {
3314 global $wgGrammarForms;
3315 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3316 return $wgGrammarForms[$this->getCode()];
3321 * Provides an alternative text depending on specified gender.
3322 * Usage {{gender:username|masculine|feminine|neutral}}.
3323 * username is optional, in which case the gender of current user is used,
3324 * but only in (some) interface messages; otherwise default gender is used.
3326 * If no forms are given, an empty string is returned. If only one form is
3327 * given, it will be returned unconditionally. These details are implied by
3328 * the caller and cannot be overridden in subclasses.
3330 * If more than one form is given, the default is to use the neutral one
3331 * if it is specified, and to use the masculine one otherwise. These
3332 * details can be overridden in subclasses.
3334 * @param $gender string
3335 * @param $forms array
3339 function gender( $gender, $forms ) {
3340 if ( !count( $forms ) ) {
3343 $forms = $this->preConvertPlural( $forms, 2 );
3344 if ( $gender === 'male' ) {
3347 if ( $gender === 'female' ) {
3350 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3354 * Plural form transformations, needed for some languages.
3355 * For example, there are 3 form of plural in Russian and Polish,
3356 * depending on "count mod 10". See [[w:Plural]]
3357 * For English it is pretty simple.
3359 * Invoked by putting {{plural:count|wordform1|wordform2}}
3360 * or {{plural:count|wordform1|wordform2|wordform3}}
3362 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3364 * @param $count Integer: non-localized number
3365 * @param $forms Array: different plural forms
3366 * @return string Correct form of plural for $count in this language
3368 function convertPlural( $count, $forms ) {
3369 if ( !count( $forms ) ) {
3372 $forms = $this->preConvertPlural( $forms, 2 );
3374 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3378 * Checks that convertPlural was given an array and pads it to requested
3379 * amount of forms by copying the last one.
3381 * @param $count Integer: How many forms should there be at least
3382 * @param $forms Array of forms given to convertPlural
3383 * @return array Padded array of forms or an exception if not an array
3385 protected function preConvertPlural( /* Array */ $forms, $count ) {
3386 while ( count( $forms ) < $count ) {
3387 $forms[] = $forms[count( $forms ) - 1];
3393 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3394 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3395 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3396 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3399 * @param $str String: the validated block duration in English
3400 * @return string Somehow translated block duration
3401 * @see LanguageFi.php for example implementation
3403 function translateBlockExpiry( $str ) {
3404 $duration = SpecialBlock
::getSuggestedDurations( $this );
3405 foreach ( $duration as $show => $value ) {
3406 if ( strcmp( $str, $value ) == 0 ) {
3407 return htmlspecialchars( trim( $show ) );
3411 // Since usually only infinite or indefinite is only on list, so try
3412 // equivalents if still here.
3413 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3414 if ( in_array( $str, $indefs ) ) {
3415 foreach ( $indefs as $val ) {
3416 $show = array_search( $val, $duration, true );
3417 if ( $show !== false ) {
3418 return htmlspecialchars( trim( $show ) );
3422 // If all else fails, return the original string.
3427 * languages like Chinese need to be segmented in order for the diff
3430 * @param $text String
3433 public function segmentForDiff( $text ) {
3438 * and unsegment to show the result
3440 * @param $text String
3443 public function unsegmentForDiff( $text ) {
3448 * Return the LanguageConverter used in the Language
3451 * @return LanguageConverter
3453 public function getConverter() {
3454 return $this->mConverter
;
3458 * convert text to all supported variants
3460 * @param $text string
3463 public function autoConvertToAllVariants( $text ) {
3464 return $this->mConverter
->autoConvertToAllVariants( $text );
3468 * convert text to different variants of a language.
3470 * @param $text string
3473 public function convert( $text ) {
3474 return $this->mConverter
->convert( $text );
3478 * Convert a Title object to a string in the preferred variant
3480 * @param $title Title
3483 public function convertTitle( $title ) {
3484 return $this->mConverter
->convertTitle( $title );
3488 * Check if this is a language with variants
3492 public function hasVariants() {
3493 return sizeof( $this->getVariants() ) > 1;
3497 * Check if the language has the specific variant
3500 * @param $variant string
3503 public function hasVariant( $variant ) {
3504 return (bool)$this->mConverter
->validateVariant( $variant );
3508 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3510 * @param $text string
3513 public function armourMath( $text ) {
3514 return $this->mConverter
->armourMath( $text );
3518 * Perform output conversion on a string, and encode for safe HTML output.
3519 * @param $text String text to be converted
3520 * @param $isTitle Bool whether this conversion is for the article title
3522 * @todo this should get integrated somewhere sane
3524 public function convertHtml( $text, $isTitle = false ) {
3525 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3529 * @param $key string
3532 public function convertCategoryKey( $key ) {
3533 return $this->mConverter
->convertCategoryKey( $key );
3537 * Get the list of variants supported by this language
3538 * see sample implementation in LanguageZh.php
3540 * @return array an array of language codes
3542 public function getVariants() {
3543 return $this->mConverter
->getVariants();
3549 public function getPreferredVariant() {
3550 return $this->mConverter
->getPreferredVariant();
3556 public function getDefaultVariant() {
3557 return $this->mConverter
->getDefaultVariant();
3563 public function getURLVariant() {
3564 return $this->mConverter
->getURLVariant();
3568 * If a language supports multiple variants, it is
3569 * possible that non-existing link in one variant
3570 * actually exists in another variant. this function
3571 * tries to find it. See e.g. LanguageZh.php
3573 * @param $link String: the name of the link
3574 * @param $nt Mixed: the title object of the link
3575 * @param $ignoreOtherCond Boolean: to disable other conditions when
3576 * we need to transclude a template or update a category's link
3577 * @return null the input parameters may be modified upon return
3579 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3580 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3584 * If a language supports multiple variants, converts text
3585 * into an array of all possible variants of the text:
3586 * 'variant' => text in that variant
3588 * @deprecated since 1.17 Use autoConvertToAllVariants()
3590 * @param $text string
3594 public function convertLinkToAllVariants( $text ) {
3595 return $this->mConverter
->convertLinkToAllVariants( $text );
3599 * returns language specific options used by User::getPageRenderHash()
3600 * for example, the preferred language variant
3604 function getExtraHashOptions() {
3605 return $this->mConverter
->getExtraHashOptions();
3609 * For languages that support multiple variants, the title of an
3610 * article may be displayed differently in different variants. this
3611 * function returns the apporiate title defined in the body of the article.
3615 public function getParsedTitle() {
3616 return $this->mConverter
->getParsedTitle();
3620 * Enclose a string with the "no conversion" tag. This is used by
3621 * various functions in the Parser
3623 * @param $text String: text to be tagged for no conversion
3624 * @param $noParse bool
3625 * @return string the tagged text
3627 public function markNoConversion( $text, $noParse = false ) {
3628 return $this->mConverter
->markNoConversion( $text, $noParse );
3632 * A regular expression to match legal word-trailing characters
3633 * which should be merged onto a link of the form [[foo]]bar.
3637 public function linkTrail() {
3638 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3644 function getLangObj() {
3649 * Get the RFC 3066 code for this language object
3653 public function getCode() {
3654 return $this->mCode
;
3658 * Get the code in Bcp47 format which we can use
3659 * inside of html lang="" tags.
3663 public function getHtmlCode() {
3664 if ( is_null( $this->mHtmlCode
) ) {
3665 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3667 return $this->mHtmlCode
;
3671 * @param $code string
3673 public function setCode( $code ) {
3674 $this->mCode
= $code;
3675 // Ensure we don't leave an incorrect html code lying around
3676 $this->mHtmlCode
= null;
3680 * Get the name of a file for a certain language code
3681 * @param $prefix string Prepend this to the filename
3682 * @param $code string Language code
3683 * @param $suffix string Append this to the filename
3684 * @throws MWException
3685 * @return string $prefix . $mangledCode . $suffix
3687 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3688 // Protect against path traversal
3689 if ( !Language
::isValidCode( $code )
3690 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3692 throw new MWException( "Invalid language code \"$code\"" );
3695 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3699 * Get the language code from a file name. Inverse of getFileName()
3700 * @param $filename string $prefix . $languageCode . $suffix
3701 * @param $prefix string Prefix before the language code
3702 * @param $suffix string Suffix after the language code
3703 * @return string Language code, or false if $prefix or $suffix isn't found
3705 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3707 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3708 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3709 if ( !count( $m ) ) {
3712 return str_replace( '_', '-', strtolower( $m[1] ) );
3716 * @param $code string
3719 public static function getMessagesFileName( $code ) {
3721 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3722 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3727 * @param $code string
3730 public static function getClassFileName( $code ) {
3732 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3736 * Get the first fallback for a given language.
3738 * @param $code string
3740 * @return bool|string
3742 public static function getFallbackFor( $code ) {
3743 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3746 $fallbacks = self
::getFallbacksFor( $code );
3747 $first = array_shift( $fallbacks );
3753 * Get the ordered list of fallback languages.
3756 * @param $code string Language code
3759 public static function getFallbacksFor( $code ) {
3760 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3763 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3764 $v = array_map( 'trim', explode( ',', $v ) );
3765 if ( $v[count( $v ) - 1] !== 'en' ) {
3773 * Get all messages for a given language
3774 * WARNING: this may take a long time. If you just need all message *keys*
3775 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3777 * @param $code string
3781 public static function getMessagesFor( $code ) {
3782 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3786 * Get a message for a given language
3788 * @param $key string
3789 * @param $code string
3793 public static function getMessageFor( $key, $code ) {
3794 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3798 * Get all message keys for a given language. This is a faster alternative to
3799 * array_keys( Language::getMessagesFor( $code ) )
3802 * @param $code string Language code
3803 * @return array of message keys (strings)
3805 public static function getMessageKeysFor( $code ) {
3806 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3813 function fixVariableInNamespace( $talk ) {
3814 if ( strpos( $talk, '$1' ) === false ) {
3818 global $wgMetaNamespace;
3819 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3821 # Allow grammar transformations
3822 # Allowing full message-style parsing would make simple requests
3823 # such as action=raw much more expensive than they need to be.
3824 # This will hopefully cover most cases.
3825 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3826 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3827 return str_replace( ' ', '_', $talk );
3834 function replaceGrammarInNamespace( $m ) {
3835 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3839 * @throws MWException
3842 static function getCaseMaps() {
3843 static $wikiUpperChars, $wikiLowerChars;
3844 if ( isset( $wikiUpperChars ) ) {
3845 return array( $wikiUpperChars, $wikiLowerChars );
3848 wfProfileIn( __METHOD__
);
3849 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3850 if ( $arr === false ) {
3851 throw new MWException(
3852 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3854 $wikiUpperChars = $arr['wikiUpperChars'];
3855 $wikiLowerChars = $arr['wikiLowerChars'];
3856 wfProfileOut( __METHOD__
);
3857 return array( $wikiUpperChars, $wikiLowerChars );
3861 * Decode an expiry (block, protection, etc) which has come from the DB
3863 * @FIXME: why are we returnings DBMS-dependent strings???
3865 * @param $expiry String: Database expiry String
3866 * @param $format Bool|Int true to process using language functions, or TS_ constant
3867 * to return the expiry in a given timestamp
3870 public function formatExpiry( $expiry, $format = true ) {
3871 static $infinity, $infinityMsg;
3872 if ( $infinity === null ) {
3873 $infinityMsg = wfMessage( 'infiniteblock' );
3874 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3877 if ( $expiry == '' ||
$expiry == $infinity ) {
3878 return $format === true
3882 return $format === true
3883 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3884 : wfTimestamp( $format, $expiry );
3890 * @param $seconds int|float
3891 * @param $format Array Optional
3892 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3893 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3894 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3895 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3898 function formatTimePeriod( $seconds, $format = array() ) {
3899 if ( !is_array( $format ) ) {
3900 $format = array( 'avoid' => $format ); // For backwards compatibility
3902 if ( !isset( $format['avoid'] ) ) {
3903 $format['avoid'] = false;
3905 if ( !isset( $format['noabbrevs' ] ) ) {
3906 $format['noabbrevs'] = false;
3908 $secondsMsg = wfMessage(
3909 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3910 $minutesMsg = wfMessage(
3911 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3912 $hoursMsg = wfMessage(
3913 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3914 $daysMsg = wfMessage(
3915 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3917 if ( round( $seconds * 10 ) < 100 ) {
3918 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3919 $s = $secondsMsg->params( $s )->text();
3920 } elseif ( round( $seconds ) < 60 ) {
3921 $s = $this->formatNum( round( $seconds ) );
3922 $s = $secondsMsg->params( $s )->text();
3923 } elseif ( round( $seconds ) < 3600 ) {
3924 $minutes = floor( $seconds / 60 );
3925 $secondsPart = round( fmod( $seconds, 60 ) );
3926 if ( $secondsPart == 60 ) {
3930 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3932 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3933 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3934 $hours = floor( $seconds / 3600 );
3935 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3936 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3937 if ( $secondsPart == 60 ) {
3941 if ( $minutes == 60 ) {
3945 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3947 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3948 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3949 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3952 $days = floor( $seconds / 86400 );
3953 if ( $format['avoid'] === 'avoidminutes' ) {
3954 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3955 if ( $hours == 24 ) {
3959 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3961 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3962 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3963 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3964 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3965 if ( $minutes == 60 ) {
3969 if ( $hours == 24 ) {
3973 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3975 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3977 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3979 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3981 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3988 * Format a bitrate for output, using an appropriate
3989 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3991 * This use base 1000. For base 1024 use formatSize(), for another base
3992 * see formatComputingNumbers()
3997 function formatBitrate( $bps ) {
3998 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4002 * @param $size int Size of the unit
4003 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4004 * @param $messageKey string Message key to be uesd
4007 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4009 return str_replace( '$1', $this->formatNum( $size ),
4010 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4013 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4016 $maxIndex = count( $sizes ) - 1;
4017 while ( $size >= $boundary && $index < $maxIndex ) {
4022 // For small sizes no decimal places necessary
4025 // For MB and bigger two decimal places are smarter
4028 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4030 $size = round( $size, $round );
4031 $text = $this->getMessageFromDB( $msg );
4032 return str_replace( '$1', $this->formatNum( $size ), $text );
4036 * Format a size in bytes for output, using an appropriate
4037 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4039 * This method use base 1024. For base 1000 use formatBitrate(), for
4040 * another base see formatComputingNumbers()
4042 * @param $size int Size to format
4043 * @return string Plain text (not HTML)
4045 function formatSize( $size ) {
4046 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4050 * Make a list item, used by various special pages
4052 * @param $page String Page link
4053 * @param $details String Text between brackets
4054 * @param $oppositedm Boolean Add the direction mark opposite to your
4055 * language, to display text properly
4058 function specialList( $page, $details, $oppositedm = true ) {
4059 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4060 $this->getDirMark();
4061 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4062 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4063 return $page . $details;
4067 * Generate (prev x| next x) (20|50|100...) type links for paging
4069 * @param $title Title object to link
4070 * @param $offset Integer offset parameter
4071 * @param $limit Integer limit parameter
4072 * @param $query String optional URL query parameter string
4073 * @param $atend Bool optional param for specified if this is the last page
4076 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4077 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4079 # Make 'previous' link
4080 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4081 if ( $offset > 0 ) {
4082 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4083 $query, $prev, 'prevn-title', 'mw-prevlink' );
4085 $plink = htmlspecialchars( $prev );
4089 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4091 $nlink = htmlspecialchars( $next );
4093 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4094 $query, $next, 'prevn-title', 'mw-nextlink' );
4097 # Make links to set number of items per page
4098 $numLinks = array();
4099 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4100 $numLinks[] = $this->numLink( $title, $offset, $num,
4101 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4104 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4105 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4109 * Helper function for viewPrevNext() that generates links
4111 * @param $title Title object to link
4112 * @param $offset Integer offset parameter
4113 * @param $limit Integer limit parameter
4114 * @param $query Array extra query parameters
4115 * @param $link String text to use for the link; will be escaped
4116 * @param $tooltipMsg String name of the message to use as tooltip
4117 * @param $class String value of the "class" attribute of the link
4118 * @return String HTML fragment
4120 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4121 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4122 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4123 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4124 'title' => $tooltip, 'class' => $class ), $link );
4128 * Get the conversion rule title, if any.
4132 public function getConvRuleTitle() {
4133 return $this->mConverter
->getConvRuleTitle();