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'
143 * Get a cached language object for a given language code
144 * @param $code String
147 static function factory( $code ) {
148 if ( !isset( self
::$mLangObjCache[$code] ) ) {
149 if ( count( self
::$mLangObjCache ) > 10 ) {
150 // Don't keep a billion objects around, that's stupid.
151 self
::$mLangObjCache = array();
153 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
155 return self
::$mLangObjCache[$code];
159 * Create a language object for a given language code
160 * @param $code String
163 protected static function newFromCode( $code ) {
164 // Protect against path traversal below
165 if ( !Language
::isValidCode( $code )
166 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
168 throw new MWException( "Invalid language code \"$code\"" );
171 if ( !Language
::isValidBuiltInCode( $code ) ) {
172 // It's not possible to customise this code with class files, so
173 // just return a Language object. This is to support uselang= hacks.
174 $lang = new Language
;
175 $lang->setCode( $code );
179 // Check if there is a language class for the code
180 $class = self
::classFromCode( $code );
181 self
::preloadLanguageClass( $class );
182 if ( MWInit
::classExists( $class ) ) {
187 // Keep trying the fallback list until we find an existing class
188 $fallbacks = Language
::getFallbacksFor( $code );
189 foreach ( $fallbacks as $fallbackCode ) {
190 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
191 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
194 $class = self
::classFromCode( $fallbackCode );
195 self
::preloadLanguageClass( $class );
196 if ( MWInit
::classExists( $class ) ) {
197 $lang = Language
::newFromCode( $fallbackCode );
198 $lang->setCode( $code );
203 throw new MWException( "Invalid fallback sequence for language '$code'" );
207 * Returns true if a language code string is of a valid form, whether or
208 * not it exists. This includes codes which are used solely for
209 * customisation via the MediaWiki namespace.
211 * @param $code string
215 public static function isValidCode( $code ) {
217 strcspn( $code, ":/\\\000" ) === strlen( $code )
218 && !preg_match( Title
::getTitleInvalidRegex(), $code );
222 * Returns true if a language code is of a valid form for the purposes of
223 * internal customisation of MediaWiki, via Messages*.php.
225 * @param $code string
230 public static function isValidBuiltInCode( $code ) {
231 return preg_match( '/^[a-z0-9-]+$/i', $code );
236 * @return String Name of the language class
238 public static function classFromCode( $code ) {
239 if ( $code == 'en' ) {
242 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
247 * Includes language class files
249 * @param $class string Name of the language class
251 public static function preloadLanguageClass( $class ) {
254 if ( $class === 'Language' ) {
258 if ( !defined( 'MW_COMPILED' ) ) {
259 // Preload base classes to work around APC/PHP5 bug
260 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
261 include_once( "$IP/languages/classes/$class.deps.php" );
263 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
264 include_once( "$IP/languages/classes/$class.php" );
270 * Get the LocalisationCache instance
272 * @return LocalisationCache
274 public static function getLocalisationCache() {
275 if ( is_null( self
::$dataCache ) ) {
276 global $wgLocalisationCacheConf;
277 $class = $wgLocalisationCacheConf['class'];
278 self
::$dataCache = new $class( $wgLocalisationCacheConf );
280 return self
::$dataCache;
283 function __construct() {
284 $this->mConverter
= new FakeConverter( $this );
285 // Set the code to the name of the descendant
286 if ( get_class( $this ) == 'Language' ) {
289 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
291 self
::getLocalisationCache();
295 * Reduce memory usage
297 function __destruct() {
298 foreach ( $this as $name => $value ) {
299 unset( $this->$name );
304 * Hook which will be called if this is the content language.
305 * Descendants can use this to register hook functions or modify globals
307 function initContLang() { }
310 * Same as getFallbacksFor for current language.
312 * @deprecated in 1.19
314 function getFallbackLanguageCode() {
315 wfDeprecated( __METHOD__
);
316 return self
::getFallbackFor( $this->mCode
);
323 function getFallbackLanguages() {
324 return self
::getFallbacksFor( $this->mCode
);
328 * Exports $wgBookstoreListEn
331 function getBookstoreList() {
332 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
338 public function getNamespaces() {
339 if ( is_null( $this->namespaceNames
) ) {
340 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
342 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
343 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
345 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
347 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
348 if ( $wgMetaNamespaceTalk ) {
349 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
351 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
352 $this->namespaceNames
[NS_PROJECT_TALK
] =
353 $this->fixVariableInNamespace( $talk );
356 # Sometimes a language will be localised but not actually exist on this wiki.
357 foreach ( $this->namespaceNames
as $key => $text ) {
358 if ( !isset( $validNamespaces[$key] ) ) {
359 unset( $this->namespaceNames
[$key] );
363 # The above mixing may leave namespaces out of canonical order.
364 # Re-order by namespace ID number...
365 ksort( $this->namespaceNames
);
367 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
369 return $this->namespaceNames
;
373 * Arbitrarily set all of the namespace names at once. Mainly used for testing
374 * @param $namespaces Array of namespaces (id => name)
376 public function setNamespaces( array $namespaces ) {
377 $this->namespaceNames
= $namespaces;
381 * A convenience function that returns the same thing as
382 * getNamespaces() except with the array values changed to ' '
383 * where it found '_', useful for producing output to be displayed
384 * e.g. in <select> forms.
388 function getFormattedNamespaces() {
389 $ns = $this->getNamespaces();
390 foreach ( $ns as $k => $v ) {
391 $ns[$k] = strtr( $v, '_', ' ' );
397 * Get a namespace value by key
399 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
400 * echo $mw_ns; // prints 'MediaWiki'
403 * @param $index Int: the array key of the namespace to return
404 * @return mixed, string if the namespace value exists, otherwise false
406 function getNsText( $index ) {
407 $ns = $this->getNamespaces();
408 return isset( $ns[$index] ) ?
$ns[$index] : false;
412 * A convenience function that returns the same thing as
413 * getNsText() except with '_' changed to ' ', useful for
416 * @param $index string
420 function getFormattedNsText( $index ) {
421 $ns = $this->getNsText( $index );
422 return strtr( $ns, '_', ' ' );
426 * Returns gender-dependent namespace alias if available.
427 * @param $index Int: namespace index
428 * @param $gender String: gender key (male, female... )
432 function getGenderNsText( $index, $gender ) {
433 global $wgExtraGenderNamespaces;
435 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
436 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
440 * Whether this language makes distinguishes genders for example in
445 function needsGenderDistinction() {
446 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
447 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
448 // $wgExtraGenderNamespaces overrides everything
450 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
451 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
452 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
455 // Check what is in i18n files
456 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
457 return count( $aliases ) > 0;
462 * Get a namespace key by value, case insensitive.
463 * Only matches namespace names for the current language, not the
464 * canonical ones defined in Namespace.php.
466 * @param $text String
467 * @return mixed An integer if $text is a valid value otherwise false
469 function getLocalNsIndex( $text ) {
470 $lctext = $this->lc( $text );
471 $ids = $this->getNamespaceIds();
472 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
478 function getNamespaceAliases() {
479 if ( is_null( $this->namespaceAliases
) ) {
480 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
484 foreach ( $aliases as $name => $index ) {
485 if ( $index === NS_PROJECT_TALK
) {
486 unset( $aliases[$name] );
487 $name = $this->fixVariableInNamespace( $name );
488 $aliases[$name] = $index;
493 global $wgExtraGenderNamespaces;
494 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
495 foreach ( $genders as $index => $forms ) {
496 foreach ( $forms as $alias ) {
497 $aliases[$alias] = $index;
501 $this->namespaceAliases
= $aliases;
503 return $this->namespaceAliases
;
509 function getNamespaceIds() {
510 if ( is_null( $this->mNamespaceIds
) ) {
511 global $wgNamespaceAliases;
512 # Put namespace names and aliases into a hashtable.
513 # If this is too slow, then we should arrange it so that it is done
514 # before caching. The catch is that at pre-cache time, the above
515 # class-specific fixup hasn't been done.
516 $this->mNamespaceIds
= array();
517 foreach ( $this->getNamespaces() as $index => $name ) {
518 $this->mNamespaceIds
[$this->lc( $name )] = $index;
520 foreach ( $this->getNamespaceAliases() as $name => $index ) {
521 $this->mNamespaceIds
[$this->lc( $name )] = $index;
523 if ( $wgNamespaceAliases ) {
524 foreach ( $wgNamespaceAliases as $name => $index ) {
525 $this->mNamespaceIds
[$this->lc( $name )] = $index;
529 return $this->mNamespaceIds
;
533 * Get a namespace key by value, case insensitive. Canonical namespace
534 * names override custom ones defined for the current language.
536 * @param $text String
537 * @return mixed An integer if $text is a valid value otherwise false
539 function getNsIndex( $text ) {
540 $lctext = $this->lc( $text );
541 $ns = MWNamespace
::getCanonicalIndex( $lctext );
542 if ( $ns !== null ) {
545 $ids = $this->getNamespaceIds();
546 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
550 * short names for language variants used for language conversion links.
552 * @param $code String
553 * @param $usemsg bool Use the "variantname-xyz" message if it exists
556 function getVariantname( $code, $usemsg = true ) {
557 $msg = "variantname-$code";
558 list( $rootCode ) = explode( '-', $code );
559 if ( $usemsg && wfMessage( $msg )->exists() ) {
560 return $this->getMessageFromDB( $msg );
562 $name = self
::getLanguageName( $code );
564 return $name; # if it's defined as a language name, show that
566 # otherwise, output the language code
572 * @param $name string
575 function specialPage( $name ) {
576 $aliases = $this->getSpecialPageAliases();
577 if ( isset( $aliases[$name][0] ) ) {
578 $name = $aliases[$name][0];
580 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
586 function getQuickbarSettings() {
588 $this->getMessage( 'qbsettings-none' ),
589 $this->getMessage( 'qbsettings-fixedleft' ),
590 $this->getMessage( 'qbsettings-fixedright' ),
591 $this->getMessage( 'qbsettings-floatingleft' ),
592 $this->getMessage( 'qbsettings-floatingright' ),
593 $this->getMessage( 'qbsettings-directionality' )
600 function getDatePreferences() {
601 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
607 function getDateFormats() {
608 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
612 * @return array|string
614 function getDefaultDateFormat() {
615 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
616 if ( $df === 'dmy or mdy' ) {
617 global $wgAmericanDates;
618 return $wgAmericanDates ?
'mdy' : 'dmy';
627 function getDatePreferenceMigrationMap() {
628 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
635 function getImageFile( $image ) {
636 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
642 function getExtraUserToggles() {
643 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
650 function getUserToggle( $tog ) {
651 return $this->getMessageFromDB( "tog-$tog" );
655 * Get native language names, indexed by code.
656 * Only those defined in MediaWiki, no other data like CLDR.
657 * If $customisedOnly is true, only returns codes with a messages file
659 * @param $customisedOnly bool
662 * @deprecated in 1.20, use fetchLanguageNames()
664 public static function getLanguageNames( $customisedOnly = false ) {
665 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
669 * Get translated language names. This is done on best effort and
670 * by default this is exactly the same as Language::getLanguageNames.
671 * The CLDR extension provides translated names.
672 * @param $code String Language code.
673 * @return Array language code => language name
675 * @deprecated in 1.20, use fetchLanguageNames()
677 public static function getTranslatedLanguageNames( $code ) {
678 return self
::fetchLanguageNames( $code, 'all' );
683 * Get an array of language names, indexed by code.
684 * @param $inLanguage null|string: Code of language in which to return the names
685 * Use null for autonyms (native names)
686 * @param $include string:
687 * 'all' all available languages
688 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames
689 * 'mwfile' only if the language is in 'mw' *and* has a message file
690 * @return array|false: language code => language name, false if $include is wrong
692 public static function fetchLanguageNames( $inLanguage = null, $include = 'all' ) {
693 global $wgExtraLanguageNames;
694 static $coreLanguageNames;
696 if ( $coreLanguageNames === null ) {
697 include( MWInit
::compiledPath( 'languages/Names.php' ) );
703 # TODO: also include when $inLanguage is null, when this code is more efficient
704 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
707 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
708 foreach ( $mwNames as $mwCode => $mwName ) {
709 # - Prefer own MediaWiki native name when not using the hook
710 # TODO: prefer it always to make it consistent, but casing is different in CLDR
711 # - For other names just add if not added through the hook
712 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
713 $names[$mwCode] = $mwName;
717 if ( $include === 'all' ) {
722 $coreCodes = array_keys( $mwNames );
723 foreach( $coreCodes as $coreCode ) {
724 $returnMw[$coreCode] = $names[$coreCode];
727 if( $include === 'mw' ) {
729 } elseif( $include === 'mwfile' ) {
730 $namesMwFile = array();
731 # We do this using a foreach over the codes instead of a directory
732 # loop so that messages files in extensions will work correctly.
733 foreach ( $returnMw as $code => $value ) {
734 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
735 $namesMwFile[$code] = $names[$code];
744 * @param $code string: The code of the language for which to get the name
745 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
746 * @return string: Language name or empty
749 public static function fetchLanguageName( $code, $inLanguage = null ) {
750 $array = self
::fetchLanguageNames( $inLanguage, 'all' );
751 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
755 * Get a message from the MediaWiki namespace.
757 * @param $msg String: message name
760 function getMessageFromDB( $msg ) {
761 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
765 * Get the native language name of $code.
766 * Only if defined in MediaWiki, no other data like CLDR.
767 * @param $code string
769 * @deprecated in 1.20, use fetchLanguageName()
771 function getLanguageName( $code ) {
772 return self
::fetchLanguageName( $code );
779 function getMonthName( $key ) {
780 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
786 function getMonthNamesArray() {
787 $monthNames = array( '' );
788 for ( $i = 1; $i < 13; $i++
) {
789 $monthNames[] = $this->getMonthName( $i );
798 function getMonthNameGen( $key ) {
799 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
806 function getMonthAbbreviation( $key ) {
807 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
813 function getMonthAbbreviationsArray() {
814 $monthNames = array( '' );
815 for ( $i = 1; $i < 13; $i++
) {
816 $monthNames[] = $this->getMonthAbbreviation( $i );
825 function getWeekdayName( $key ) {
826 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
833 function getWeekdayAbbreviation( $key ) {
834 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
841 function getIranianCalendarMonthName( $key ) {
842 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
849 function getHebrewCalendarMonthName( $key ) {
850 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
857 function getHebrewCalendarMonthNameGen( $key ) {
858 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
865 function getHijriCalendarMonthName( $key ) {
866 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
870 * This is a workalike of PHP's date() function, but with better
871 * internationalisation, a reduced set of format characters, and a better
874 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
875 * PHP manual for definitions. There are a number of extensions, which
878 * xn Do not translate digits of the next numeric format character
879 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
880 * xr Use roman numerals for the next numeric format character
881 * xh Use hebrew numerals for the next numeric format character
883 * xg Genitive month name
885 * xij j (day number) in Iranian calendar
886 * xiF F (month name) in Iranian calendar
887 * xin n (month number) in Iranian calendar
888 * xiy y (two digit year) in Iranian calendar
889 * xiY Y (full year) in Iranian calendar
891 * xjj j (day number) in Hebrew calendar
892 * xjF F (month name) in Hebrew calendar
893 * xjt t (days in month) in Hebrew calendar
894 * xjx xg (genitive month name) in Hebrew calendar
895 * xjn n (month number) in Hebrew calendar
896 * xjY Y (full year) in Hebrew calendar
898 * xmj j (day number) in Hijri calendar
899 * xmF F (month name) in Hijri calendar
900 * xmn n (month number) in Hijri calendar
901 * xmY Y (full year) in Hijri calendar
903 * xkY Y (full year) in Thai solar calendar. Months and days are
904 * identical to the Gregorian calendar
905 * xoY Y (full year) in Minguo calendar or Juche year.
906 * Months and days are identical to the
908 * xtY Y (full year) in Japanese nengo. Months and days are
909 * identical to the Gregorian calendar
911 * Characters enclosed in double quotes will be considered literal (with
912 * the quotes themselves removed). Unmatched quotes will be considered
913 * literal quotes. Example:
915 * "The month is" F => The month is January
918 * Backslash escaping is also supported.
920 * Input timestamp is assumed to be pre-normalized to the desired local
923 * @param $format String
924 * @param $ts String: 14-character timestamp
927 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
931 function sprintfDate( $format, $ts ) {
944 for ( $p = 0; $p < strlen( $format ); $p++
) {
947 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
948 $code .= $format[++
$p];
951 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
952 $code .= $format[++
$p];
963 $rawToggle = !$rawToggle;
972 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
975 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
976 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
979 $num = substr( $ts, 6, 2 );
982 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
983 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
986 $num = intval( substr( $ts, 6, 2 ) );
990 $iranian = self
::tsToIranian( $ts );
996 $hijri = self
::tsToHijri( $ts );
1002 $hebrew = self
::tsToHebrew( $ts );
1008 $unix = wfTimestamp( TS_UNIX
, $ts );
1010 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1014 $unix = wfTimestamp( TS_UNIX
, $ts );
1016 $w = gmdate( 'w', $unix );
1021 $unix = wfTimestamp( TS_UNIX
, $ts );
1023 $num = gmdate( 'w', $unix );
1027 $unix = wfTimestamp( TS_UNIX
, $ts );
1029 $num = gmdate( 'z', $unix );
1033 $unix = wfTimestamp( TS_UNIX
, $ts );
1035 $num = gmdate( 'W', $unix );
1038 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1042 $iranian = self
::tsToIranian( $ts );
1044 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1048 $hijri = self
::tsToHijri( $ts );
1050 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1054 $hebrew = self
::tsToHebrew( $ts );
1056 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1059 $num = substr( $ts, 4, 2 );
1062 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1065 $num = intval( substr( $ts, 4, 2 ) );
1069 $iranian = self
::tsToIranian( $ts );
1075 $hijri = self
::tsToHijri ( $ts );
1081 $hebrew = self
::tsToHebrew( $ts );
1087 $unix = wfTimestamp( TS_UNIX
, $ts );
1089 $num = gmdate( 't', $unix );
1093 $hebrew = self
::tsToHebrew( $ts );
1099 $unix = wfTimestamp( TS_UNIX
, $ts );
1101 $num = gmdate( 'L', $unix );
1105 $unix = wfTimestamp( TS_UNIX
, $ts );
1107 $num = gmdate( 'o', $unix );
1110 $num = substr( $ts, 0, 4 );
1114 $iranian = self
::tsToIranian( $ts );
1120 $hijri = self
::tsToHijri( $ts );
1126 $hebrew = self
::tsToHebrew( $ts );
1132 $thai = self
::tsToYear( $ts, 'thai' );
1138 $minguo = self
::tsToYear( $ts, 'minguo' );
1144 $tenno = self
::tsToYear( $ts, 'tenno' );
1149 $num = substr( $ts, 2, 2 );
1153 $iranian = self
::tsToIranian( $ts );
1155 $num = substr( $iranian[0], -2 );
1158 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1161 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1164 $h = substr( $ts, 8, 2 );
1165 $num = $h %
12 ?
$h %
12 : 12;
1168 $num = intval( substr( $ts, 8, 2 ) );
1171 $h = substr( $ts, 8, 2 );
1172 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1175 $num = substr( $ts, 8, 2 );
1178 $num = substr( $ts, 10, 2 );
1181 $num = substr( $ts, 12, 2 );
1185 $unix = wfTimestamp( TS_UNIX
, $ts );
1187 $s .= gmdate( 'c', $unix );
1191 $unix = wfTimestamp( TS_UNIX
, $ts );
1193 $s .= gmdate( 'r', $unix );
1197 $unix = wfTimestamp( TS_UNIX
, $ts );
1202 # Backslash escaping
1203 if ( $p < strlen( $format ) - 1 ) {
1204 $s .= $format[++
$p];
1211 if ( $p < strlen( $format ) - 1 ) {
1212 $endQuote = strpos( $format, '"', $p +
1 );
1213 if ( $endQuote === false ) {
1214 # No terminating quote, assume literal "
1217 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1221 # Quote at end of string, assume literal "
1228 if ( $num !== false ) {
1229 if ( $rawToggle ||
$raw ) {
1232 } elseif ( $roman ) {
1233 $s .= self
::romanNumeral( $num );
1235 } elseif ( $hebrewNum ) {
1236 $s .= self
::hebrewNumeral( $num );
1239 $s .= $this->formatNum( $num, true );
1246 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1247 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1250 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1251 * Gregorian dates to Iranian dates. Originally written in C, it
1252 * is released under the terms of GNU Lesser General Public
1253 * License. Conversion to PHP was performed by Niklas Laxström.
1255 * Link: http://www.farsiweb.info/jalali/jalali.c
1261 private static function tsToIranian( $ts ) {
1262 $gy = substr( $ts, 0, 4 ) -1600;
1263 $gm = substr( $ts, 4, 2 ) -1;
1264 $gd = substr( $ts, 6, 2 ) -1;
1266 # Days passed from the beginning (including leap years)
1268 +
floor( ( $gy +
3 ) / 4 )
1269 - floor( ( $gy +
99 ) / 100 )
1270 +
floor( ( $gy +
399 ) / 400 );
1272 // Add days of the past months of this year
1273 for ( $i = 0; $i < $gm; $i++
) {
1274 $gDayNo +
= self
::$GREG_DAYS[$i];
1278 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1282 // Days passed in current month
1283 $gDayNo +
= (int)$gd;
1285 $jDayNo = $gDayNo - 79;
1287 $jNp = floor( $jDayNo / 12053 );
1290 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1293 if ( $jDayNo >= 366 ) {
1294 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1295 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1298 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1299 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1305 return array( $jy, $jm, $jd );
1309 * Converting Gregorian dates to Hijri dates.
1311 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1313 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1319 private static function tsToHijri( $ts ) {
1320 $year = substr( $ts, 0, 4 );
1321 $month = substr( $ts, 4, 2 );
1322 $day = substr( $ts, 6, 2 );
1330 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1331 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1334 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1335 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1336 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1339 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1340 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1343 $zl = $zjd -1948440 +
10632;
1344 $zn = (int)( ( $zl - 1 ) / 10631 );
1345 $zl = $zl - 10631 * $zn +
354;
1346 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1347 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1348 $zm = (int)( ( 24 * $zl ) / 709 );
1349 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1350 $zy = 30 * $zn +
$zj - 30;
1352 return array( $zy, $zm, $zd );
1356 * Converting Gregorian dates to Hebrew dates.
1358 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1359 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1360 * to translate the relevant functions into PHP and release them under
1363 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1364 * and Adar II is 14. In a non-leap year, Adar is 6.
1370 private static function tsToHebrew( $ts ) {
1372 $year = substr( $ts, 0, 4 );
1373 $month = substr( $ts, 4, 2 );
1374 $day = substr( $ts, 6, 2 );
1376 # Calculate Hebrew year
1377 $hebrewYear = $year +
3760;
1379 # Month number when September = 1, August = 12
1381 if ( $month > 12 ) {
1388 # Calculate day of year from 1 September
1390 for ( $i = 1; $i < $month; $i++
) {
1394 # Check if the year is leap
1395 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1398 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1405 # Calculate the start of the Hebrew year
1406 $start = self
::hebrewYearStart( $hebrewYear );
1408 # Calculate next year's start
1409 if ( $dayOfYear <= $start ) {
1410 # Day is before the start of the year - it is the previous year
1412 $nextStart = $start;
1416 # Add days since previous year's 1 September
1418 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1422 # Start of the new (previous) year
1423 $start = self
::hebrewYearStart( $hebrewYear );
1426 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1429 # Calculate Hebrew day of year
1430 $hebrewDayOfYear = $dayOfYear - $start;
1432 # Difference between year's days
1433 $diff = $nextStart - $start;
1434 # Add 12 (or 13 for leap years) days to ignore the difference between
1435 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1436 # difference is only about the year type
1437 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1443 # Check the year pattern, and is leap year
1444 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1445 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1446 # and non-leap years
1447 $yearPattern = $diff %
30;
1448 # Check if leap year
1449 $isLeap = $diff >= 30;
1451 # Calculate day in the month from number of day in the Hebrew year
1452 # Don't check Adar - if the day is not in Adar, we will stop before;
1453 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1454 $hebrewDay = $hebrewDayOfYear;
1457 while ( $hebrewMonth <= 12 ) {
1458 # Calculate days in this month
1459 if ( $isLeap && $hebrewMonth == 6 ) {
1460 # Adar in a leap year
1462 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1464 if ( $hebrewDay <= $days ) {
1468 # Subtract the days of Adar I
1469 $hebrewDay -= $days;
1472 if ( $hebrewDay <= $days ) {
1478 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1479 # Cheshvan in a complete year (otherwise as the rule below)
1481 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1482 # Kislev in an incomplete year (otherwise as the rule below)
1485 # Odd months have 30 days, even have 29
1486 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1488 if ( $hebrewDay <= $days ) {
1489 # In the current month
1492 # Subtract the days of the current month
1493 $hebrewDay -= $days;
1494 # Try in the next month
1499 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1503 * This calculates the Hebrew year start, as days since 1 September.
1504 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1505 * Used for Hebrew date.
1511 private static function hebrewYearStart( $year ) {
1512 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1513 $b = intval( ( $year - 1 ) %
4 );
1514 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1518 $Mar = intval( $m );
1524 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1525 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1527 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1529 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1533 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1538 * Algorithm to convert Gregorian dates to Thai solar dates,
1539 * Minguo dates or Minguo dates.
1541 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1542 * http://en.wikipedia.org/wiki/Minguo_calendar
1543 * http://en.wikipedia.org/wiki/Japanese_era_name
1545 * @param $ts String: 14-character timestamp
1546 * @param $cName String: calender name
1547 * @return Array: converted year, month, day
1549 private static function tsToYear( $ts, $cName ) {
1550 $gy = substr( $ts, 0, 4 );
1551 $gm = substr( $ts, 4, 2 );
1552 $gd = substr( $ts, 6, 2 );
1554 if ( !strcmp( $cName, 'thai' ) ) {
1556 # Add 543 years to the Gregorian calendar
1557 # Months and days are identical
1558 $gy_offset = $gy +
543;
1559 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1561 # Deduct 1911 years from the Gregorian calendar
1562 # Months and days are identical
1563 $gy_offset = $gy - 1911;
1564 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1565 # Nengō dates up to Meiji period
1566 # Deduct years from the Gregorian calendar
1567 # depending on the nengo periods
1568 # Months and days are identical
1569 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1571 $gy_gannen = $gy - 1868 +
1;
1572 $gy_offset = $gy_gannen;
1573 if ( $gy_gannen == 1 ) {
1576 $gy_offset = '明治' . $gy_offset;
1578 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1579 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1580 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1581 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1582 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1586 $gy_gannen = $gy - 1912 +
1;
1587 $gy_offset = $gy_gannen;
1588 if ( $gy_gannen == 1 ) {
1591 $gy_offset = '大正' . $gy_offset;
1593 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1594 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1595 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1599 $gy_gannen = $gy - 1926 +
1;
1600 $gy_offset = $gy_gannen;
1601 if ( $gy_gannen == 1 ) {
1604 $gy_offset = '昭和' . $gy_offset;
1607 $gy_gannen = $gy - 1989 +
1;
1608 $gy_offset = $gy_gannen;
1609 if ( $gy_gannen == 1 ) {
1612 $gy_offset = '平成' . $gy_offset;
1618 return array( $gy_offset, $gm, $gd );
1622 * Roman number formatting up to 3000
1628 static function romanNumeral( $num ) {
1629 static $table = array(
1630 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1631 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1632 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1633 array( '', 'M', 'MM', 'MMM' )
1636 $num = intval( $num );
1637 if ( $num > 3000 ||
$num <= 0 ) {
1642 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1643 if ( $num >= $pow10 ) {
1644 $s .= $table[$i][(int)floor( $num / $pow10 )];
1646 $num = $num %
$pow10;
1652 * Hebrew Gematria number formatting up to 9999
1658 static function hebrewNumeral( $num ) {
1659 static $table = array(
1660 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1661 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1662 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1663 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1666 $num = intval( $num );
1667 if ( $num > 9999 ||
$num <= 0 ) {
1672 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1673 if ( $num >= $pow10 ) {
1674 if ( $num == 15 ||
$num == 16 ) {
1675 $s .= $table[0][9] . $table[0][$num - 9];
1678 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1679 if ( $pow10 == 1000 ) {
1684 $num = $num %
$pow10;
1686 if ( strlen( $s ) == 2 ) {
1689 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1690 $str .= substr( $s, strlen( $s ) - 2, 2 );
1692 $start = substr( $str, 0, strlen( $str ) - 2 );
1693 $end = substr( $str, strlen( $str ) - 2 );
1696 $str = $start . 'ך';
1699 $str = $start . 'ם';
1702 $str = $start . 'ן';
1705 $str = $start . 'ף';
1708 $str = $start . 'ץ';
1715 * Used by date() and time() to adjust the time output.
1717 * @param $ts Int the time in date('YmdHis') format
1718 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1719 * get user timecorrection setting)
1722 function userAdjust( $ts, $tz = false ) {
1723 global $wgUser, $wgLocalTZoffset;
1725 if ( $tz === false ) {
1726 $tz = $wgUser->getOption( 'timecorrection' );
1729 $data = explode( '|', $tz, 3 );
1731 if ( $data[0] == 'ZoneInfo' ) {
1732 wfSuppressWarnings();
1733 $userTZ = timezone_open( $data[2] );
1734 wfRestoreWarnings();
1735 if ( $userTZ !== false ) {
1736 $date = date_create( $ts, timezone_open( 'UTC' ) );
1737 date_timezone_set( $date, $userTZ );
1738 $date = date_format( $date, 'YmdHis' );
1741 # Unrecognized timezone, default to 'Offset' with the stored offset.
1742 $data[0] = 'Offset';
1746 if ( $data[0] == 'System' ||
$tz == '' ) {
1747 # Global offset in minutes.
1748 if ( isset( $wgLocalTZoffset ) ) {
1749 $minDiff = $wgLocalTZoffset;
1751 } elseif ( $data[0] == 'Offset' ) {
1752 $minDiff = intval( $data[1] );
1754 $data = explode( ':', $tz );
1755 if ( count( $data ) == 2 ) {
1756 $data[0] = intval( $data[0] );
1757 $data[1] = intval( $data[1] );
1758 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1759 if ( $data[0] < 0 ) {
1760 $minDiff = -$minDiff;
1763 $minDiff = intval( $data[0] ) * 60;
1767 # No difference ? Return time unchanged
1768 if ( 0 == $minDiff ) {
1772 wfSuppressWarnings(); // E_STRICT system time bitching
1773 # Generate an adjusted date; take advantage of the fact that mktime
1774 # will normalize out-of-range values so we don't have to split $minDiff
1775 # into hours and minutes.
1777 (int)substr( $ts, 8, 2 ) ), # Hours
1778 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1779 (int)substr( $ts, 12, 2 ), # Seconds
1780 (int)substr( $ts, 4, 2 ), # Month
1781 (int)substr( $ts, 6, 2 ), # Day
1782 (int)substr( $ts, 0, 4 ) ); # Year
1784 $date = date( 'YmdHis', $t );
1785 wfRestoreWarnings();
1791 * This is meant to be used by time(), date(), and timeanddate() to get
1792 * the date preference they're supposed to use, it should be used in
1796 * function timeanddate([...], $format = true) {
1797 * $datePreference = $this->dateFormat($format);
1802 * @param $usePrefs Mixed: if true, the user's preference is used
1803 * if false, the site/language default is used
1804 * if int/string, assumed to be a format.
1807 function dateFormat( $usePrefs = true ) {
1810 if ( is_bool( $usePrefs ) ) {
1812 $datePreference = $wgUser->getDatePreference();
1814 $datePreference = (string)User
::getDefaultOption( 'date' );
1817 $datePreference = (string)$usePrefs;
1821 if ( $datePreference == '' ) {
1825 return $datePreference;
1829 * Get a format string for a given type and preference
1830 * @param $type string May be date, time or both
1831 * @param $pref string The format name as it appears in Messages*.php
1835 function getDateFormatString( $type, $pref ) {
1836 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1837 if ( $pref == 'default' ) {
1838 $pref = $this->getDefaultDateFormat();
1839 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1841 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1842 if ( is_null( $df ) ) {
1843 $pref = $this->getDefaultDateFormat();
1844 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1847 $this->dateFormatStrings
[$type][$pref] = $df;
1849 return $this->dateFormatStrings
[$type][$pref];
1853 * @param $ts Mixed: the time format which needs to be turned into a
1854 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1855 * @param $adj Bool: whether to adjust the time output according to the
1856 * user configured offset ($timecorrection)
1857 * @param $format Mixed: true to use user's date format preference
1858 * @param $timecorrection String|bool the time offset as returned by
1859 * validateTimeZone() in Special:Preferences
1862 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1863 $ts = wfTimestamp( TS_MW
, $ts );
1865 $ts = $this->userAdjust( $ts, $timecorrection );
1867 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1868 return $this->sprintfDate( $df, $ts );
1872 * @param $ts Mixed: the time format which needs to be turned into a
1873 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1874 * @param $adj Bool: whether to adjust the time output according to the
1875 * user configured offset ($timecorrection)
1876 * @param $format Mixed: true to use user's date format preference
1877 * @param $timecorrection String|bool the time offset as returned by
1878 * validateTimeZone() in Special:Preferences
1881 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1882 $ts = wfTimestamp( TS_MW
, $ts );
1884 $ts = $this->userAdjust( $ts, $timecorrection );
1886 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1887 return $this->sprintfDate( $df, $ts );
1891 * @param $ts Mixed: the time format which needs to be turned into a
1892 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1893 * @param $adj Bool: whether to adjust the time output according to the
1894 * user configured offset ($timecorrection)
1895 * @param $format Mixed: what format to return, if it's false output the
1896 * default one (default true)
1897 * @param $timecorrection String|bool the time offset as returned by
1898 * validateTimeZone() in Special:Preferences
1901 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1902 $ts = wfTimestamp( TS_MW
, $ts );
1904 $ts = $this->userAdjust( $ts, $timecorrection );
1906 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1907 return $this->sprintfDate( $df, $ts );
1911 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1913 * @param $type String: can be 'date', 'time' or 'both'
1914 * @param $ts Mixed: the time format which needs to be turned into a
1915 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1916 * @param $user User object used to get preferences for timezone and format
1917 * @param $options Array, can contain the following keys:
1918 * - 'timecorrection': time correction, can have the following values:
1919 * - true: use user's preference
1920 * - false: don't use time correction
1921 * - integer: value of time correction in minutes
1922 * - 'format': format to use, can have the following values:
1923 * - true: use user's preference
1924 * - false: use default preference
1925 * - string: format to use
1929 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1930 $ts = wfTimestamp( TS_MW
, $ts );
1931 $options +
= array( 'timecorrection' => true, 'format' => true );
1932 if ( $options['timecorrection'] !== false ) {
1933 if ( $options['timecorrection'] === true ) {
1934 $offset = $user->getOption( 'timecorrection' );
1936 $offset = $options['timecorrection'];
1938 $ts = $this->userAdjust( $ts, $offset );
1940 if ( $options['format'] === true ) {
1941 $format = $user->getDatePreference();
1943 $format = $options['format'];
1945 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1946 return $this->sprintfDate( $df, $ts );
1950 * Get the formatted date for the given timestamp and formatted for
1953 * @param $ts Mixed: the time format which needs to be turned into a
1954 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1955 * @param $user User object used to get preferences for timezone and format
1956 * @param $options Array, can contain the following keys:
1957 * - 'timecorrection': time correction, can have the following values:
1958 * - true: use user's preference
1959 * - false: don't use time correction
1960 * - integer: value of time correction in minutes
1961 * - 'format': format to use, can have the following values:
1962 * - true: use user's preference
1963 * - false: use default preference
1964 * - string: format to use
1968 public function userDate( $ts, User
$user, array $options = array() ) {
1969 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1973 * Get the formatted time for the given timestamp and formatted for
1976 * @param $ts Mixed: the time format which needs to be turned into a
1977 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1978 * @param $user User object used to get preferences for timezone and format
1979 * @param $options Array, can contain the following keys:
1980 * - 'timecorrection': time correction, can have the following values:
1981 * - true: use user's preference
1982 * - false: don't use time correction
1983 * - integer: value of time correction in minutes
1984 * - 'format': format to use, can have the following values:
1985 * - true: use user's preference
1986 * - false: use default preference
1987 * - string: format to use
1991 public function userTime( $ts, User
$user, array $options = array() ) {
1992 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1996 * Get the formatted date and time for the given timestamp and formatted for
1999 * @param $ts Mixed: the time format which needs to be turned into a
2000 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2001 * @param $user User object used to get preferences for timezone and format
2002 * @param $options Array, can contain the following keys:
2003 * - 'timecorrection': time correction, can have the following values:
2004 * - true: use user's preference
2005 * - false: don't use time correction
2006 * - integer: value of time correction in minutes
2007 * - 'format': format to use, can have the following values:
2008 * - true: use user's preference
2009 * - false: use default preference
2010 * - string: format to use
2014 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2015 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2019 * @param $key string
2020 * @return array|null
2022 function getMessage( $key ) {
2023 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2029 function getAllMessages() {
2030 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2039 function iconv( $in, $out, $string ) {
2040 # This is a wrapper for iconv in all languages except esperanto,
2041 # which does some nasty x-conversions beforehand
2043 # Even with //IGNORE iconv can whine about illegal characters in
2044 # *input* string. We just ignore those too.
2045 # REF: http://bugs.php.net/bug.php?id=37166
2046 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2047 wfSuppressWarnings();
2048 $text = iconv( $in, $out . '//IGNORE', $string );
2049 wfRestoreWarnings();
2053 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2056 * @param $matches array
2057 * @return mixed|string
2059 function ucwordbreaksCallbackAscii( $matches ) {
2060 return $this->ucfirst( $matches[1] );
2064 * @param $matches array
2067 function ucwordbreaksCallbackMB( $matches ) {
2068 return mb_strtoupper( $matches[0] );
2072 * @param $matches array
2075 function ucCallback( $matches ) {
2076 list( $wikiUpperChars ) = self
::getCaseMaps();
2077 return strtr( $matches[1], $wikiUpperChars );
2081 * @param $matches array
2084 function lcCallback( $matches ) {
2085 list( , $wikiLowerChars ) = self
::getCaseMaps();
2086 return strtr( $matches[1], $wikiLowerChars );
2090 * @param $matches array
2093 function ucwordsCallbackMB( $matches ) {
2094 return mb_strtoupper( $matches[0] );
2098 * @param $matches array
2101 function ucwordsCallbackWiki( $matches ) {
2102 list( $wikiUpperChars ) = self
::getCaseMaps();
2103 return strtr( $matches[0], $wikiUpperChars );
2107 * Make a string's first character uppercase
2109 * @param $str string
2113 function ucfirst( $str ) {
2115 if ( $o < 96 ) { // if already uppercase...
2117 } elseif ( $o < 128 ) {
2118 return ucfirst( $str ); // use PHP's ucfirst()
2120 // fall back to more complex logic in case of multibyte strings
2121 return $this->uc( $str, true );
2126 * Convert a string to uppercase
2128 * @param $str string
2129 * @param $first bool
2133 function uc( $str, $first = false ) {
2134 if ( function_exists( 'mb_strtoupper' ) ) {
2136 if ( $this->isMultibyte( $str ) ) {
2137 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2139 return ucfirst( $str );
2142 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2145 if ( $this->isMultibyte( $str ) ) {
2146 $x = $first ?
'^' : '';
2147 return preg_replace_callback(
2148 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2149 array( $this, 'ucCallback' ),
2153 return $first ?
ucfirst( $str ) : strtoupper( $str );
2159 * @param $str string
2160 * @return mixed|string
2162 function lcfirst( $str ) {
2165 return strval( $str );
2166 } elseif ( $o >= 128 ) {
2167 return $this->lc( $str, true );
2168 } elseif ( $o > 96 ) {
2171 $str[0] = strtolower( $str[0] );
2177 * @param $str string
2178 * @param $first bool
2179 * @return mixed|string
2181 function lc( $str, $first = false ) {
2182 if ( function_exists( 'mb_strtolower' ) ) {
2184 if ( $this->isMultibyte( $str ) ) {
2185 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2187 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2190 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2193 if ( $this->isMultibyte( $str ) ) {
2194 $x = $first ?
'^' : '';
2195 return preg_replace_callback(
2196 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2197 array( $this, 'lcCallback' ),
2201 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2207 * @param $str string
2210 function isMultibyte( $str ) {
2211 return (bool)preg_match( '/[\x80-\xff]/', $str );
2215 * @param $str string
2216 * @return mixed|string
2218 function ucwords( $str ) {
2219 if ( $this->isMultibyte( $str ) ) {
2220 $str = $this->lc( $str );
2222 // regexp to find first letter in each word (i.e. after each space)
2223 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2225 // function to use to capitalize a single char
2226 if ( function_exists( 'mb_strtoupper' ) ) {
2227 return preg_replace_callback(
2229 array( $this, 'ucwordsCallbackMB' ),
2233 return preg_replace_callback(
2235 array( $this, 'ucwordsCallbackWiki' ),
2240 return ucwords( strtolower( $str ) );
2245 * capitalize words at word breaks
2247 * @param $str string
2250 function ucwordbreaks( $str ) {
2251 if ( $this->isMultibyte( $str ) ) {
2252 $str = $this->lc( $str );
2254 // since \b doesn't work for UTF-8, we explicitely define word break chars
2255 $breaks = "[ \-\(\)\}\{\.,\?!]";
2257 // find first letter after word break
2258 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2260 if ( function_exists( 'mb_strtoupper' ) ) {
2261 return preg_replace_callback(
2263 array( $this, 'ucwordbreaksCallbackMB' ),
2267 return preg_replace_callback(
2269 array( $this, 'ucwordsCallbackWiki' ),
2274 return preg_replace_callback(
2275 '/\b([\w\x80-\xff]+)\b/',
2276 array( $this, 'ucwordbreaksCallbackAscii' ),
2283 * Return a case-folded representation of $s
2285 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2286 * and $s2 are the same except for the case of their characters. It is not
2287 * necessary for the value returned to make sense when displayed.
2289 * Do *not* perform any other normalisation in this function. If a caller
2290 * uses this function when it should be using a more general normalisation
2291 * function, then fix the caller.
2297 function caseFold( $s ) {
2298 return $this->uc( $s );
2305 function checkTitleEncoding( $s ) {
2306 if ( is_array( $s ) ) {
2307 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2309 # Check for non-UTF-8 URLs
2310 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2315 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2316 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2321 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2327 function fallback8bitEncoding() {
2328 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2332 * Most writing systems use whitespace to break up words.
2333 * Some languages such as Chinese don't conventionally do this,
2334 * which requires special handling when breaking up words for
2339 function hasWordBreaks() {
2344 * Some languages such as Chinese require word segmentation,
2345 * Specify such segmentation when overridden in derived class.
2347 * @param $string String
2350 function segmentByWord( $string ) {
2355 * Some languages have special punctuation need to be normalized.
2356 * Make such changes here.
2358 * @param $string String
2361 function normalizeForSearch( $string ) {
2362 return self
::convertDoubleWidth( $string );
2366 * convert double-width roman characters to single-width.
2367 * range: ff00-ff5f ~= 0020-007f
2369 * @param $string string
2373 protected static function convertDoubleWidth( $string ) {
2374 static $full = null;
2375 static $half = null;
2377 if ( $full === null ) {
2378 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2379 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2380 $full = str_split( $fullWidth, 3 );
2381 $half = str_split( $halfWidth );
2384 $string = str_replace( $full, $half, $string );
2389 * @param $string string
2390 * @param $pattern string
2393 protected static function insertSpace( $string, $pattern ) {
2394 $string = preg_replace( $pattern, " $1 ", $string );
2395 $string = preg_replace( '/ +/', ' ', $string );
2400 * @param $termsArray array
2403 function convertForSearchResult( $termsArray ) {
2404 # some languages, e.g. Chinese, need to do a conversion
2405 # in order for search results to be displayed correctly
2410 * Get the first character of a string.
2415 function firstChar( $s ) {
2418 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2419 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2424 if ( isset( $matches[1] ) ) {
2425 if ( strlen( $matches[1] ) != 3 ) {
2429 // Break down Hangul syllables to grab the first jamo
2430 $code = utf8ToCodepoint( $matches[1] );
2431 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2433 } elseif ( $code < 0xb098 ) {
2434 return "\xe3\x84\xb1";
2435 } elseif ( $code < 0xb2e4 ) {
2436 return "\xe3\x84\xb4";
2437 } elseif ( $code < 0xb77c ) {
2438 return "\xe3\x84\xb7";
2439 } elseif ( $code < 0xb9c8 ) {
2440 return "\xe3\x84\xb9";
2441 } elseif ( $code < 0xbc14 ) {
2442 return "\xe3\x85\x81";
2443 } elseif ( $code < 0xc0ac ) {
2444 return "\xe3\x85\x82";
2445 } elseif ( $code < 0xc544 ) {
2446 return "\xe3\x85\x85";
2447 } elseif ( $code < 0xc790 ) {
2448 return "\xe3\x85\x87";
2449 } elseif ( $code < 0xcc28 ) {
2450 return "\xe3\x85\x88";
2451 } elseif ( $code < 0xce74 ) {
2452 return "\xe3\x85\x8a";
2453 } elseif ( $code < 0xd0c0 ) {
2454 return "\xe3\x85\x8b";
2455 } elseif ( $code < 0xd30c ) {
2456 return "\xe3\x85\x8c";
2457 } elseif ( $code < 0xd558 ) {
2458 return "\xe3\x85\x8d";
2460 return "\xe3\x85\x8e";
2467 function initEncoding() {
2468 # Some languages may have an alternate char encoding option
2469 # (Esperanto X-coding, Japanese furigana conversion, etc)
2470 # If this language is used as the primary content language,
2471 # an override to the defaults can be set here on startup.
2478 function recodeForEdit( $s ) {
2479 # For some languages we'll want to explicitly specify
2480 # which characters make it into the edit box raw
2481 # or are converted in some way or another.
2482 global $wgEditEncoding;
2483 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2486 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2494 function recodeInput( $s ) {
2495 # Take the previous into account.
2496 global $wgEditEncoding;
2497 if ( $wgEditEncoding != '' ) {
2498 $enc = $wgEditEncoding;
2502 if ( $enc == 'UTF-8' ) {
2505 return $this->iconv( $enc, 'UTF-8', $s );
2510 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2511 * also cleans up certain backwards-compatible sequences, converting them
2512 * to the modern Unicode equivalent.
2514 * This is language-specific for performance reasons only.
2520 function normalize( $s ) {
2521 global $wgAllUnicodeFixes;
2522 $s = UtfNormal
::cleanUp( $s );
2523 if ( $wgAllUnicodeFixes ) {
2524 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2525 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2532 * Transform a string using serialized data stored in the given file (which
2533 * must be in the serialized subdirectory of $IP). The file contains pairs
2534 * mapping source characters to destination characters.
2536 * The data is cached in process memory. This will go faster if you have the
2537 * FastStringSearch extension.
2539 * @param $file string
2540 * @param $string string
2544 function transformUsingPairFile( $file, $string ) {
2545 if ( !isset( $this->transformData
[$file] ) ) {
2546 $data = wfGetPrecompiledData( $file );
2547 if ( $data === false ) {
2548 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2550 $this->transformData
[$file] = new ReplacementArray( $data );
2552 return $this->transformData
[$file]->replace( $string );
2556 * For right-to-left language support
2561 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2565 * Return the correct HTML 'dir' attribute value for this language.
2569 return $this->isRTL() ?
'rtl' : 'ltr';
2573 * Return 'left' or 'right' as appropriate alignment for line-start
2574 * for this language's text direction.
2576 * Should be equivalent to CSS3 'start' text-align value....
2580 function alignStart() {
2581 return $this->isRTL() ?
'right' : 'left';
2585 * Return 'right' or 'left' as appropriate alignment for line-end
2586 * for this language's text direction.
2588 * Should be equivalent to CSS3 'end' text-align value....
2592 function alignEnd() {
2593 return $this->isRTL() ?
'left' : 'right';
2597 * A hidden direction mark (LRM or RLM), depending on the language direction
2599 * @param $opposite Boolean Get the direction mark opposite to your language
2602 function getDirMark( $opposite = false ) {
2603 $rtl = "\xE2\x80\x8F";
2604 $ltr = "\xE2\x80\x8E";
2605 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2606 return $this->isRTL() ?
$rtl : $ltr;
2612 function capitalizeAllNouns() {
2613 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2617 * An arrow, depending on the language direction
2621 function getArrow() {
2622 return $this->isRTL() ?
'←' : '→';
2626 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2630 function linkPrefixExtension() {
2631 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2637 function getMagicWords() {
2638 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2641 protected function doMagicHook() {
2642 if ( $this->mMagicHookDone
) {
2645 $this->mMagicHookDone
= true;
2646 wfProfileIn( 'LanguageGetMagic' );
2647 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2648 wfProfileOut( 'LanguageGetMagic' );
2652 * Fill a MagicWord object with data from here
2656 function getMagic( $mw ) {
2657 $this->doMagicHook();
2659 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2660 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2662 $magicWords = $this->getMagicWords();
2663 if ( isset( $magicWords[$mw->mId
] ) ) {
2664 $rawEntry = $magicWords[$mw->mId
];
2670 if ( !is_array( $rawEntry ) ) {
2671 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2673 $mw->mCaseSensitive
= $rawEntry[0];
2674 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2679 * Add magic words to the extension array
2681 * @param $newWords array
2683 function addMagicWordsByLang( $newWords ) {
2684 $fallbackChain = $this->getFallbackLanguages();
2685 $fallbackChain = array_reverse( $fallbackChain );
2686 foreach ( $fallbackChain as $code ) {
2687 if ( isset( $newWords[$code] ) ) {
2688 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2694 * Get special page names, as an associative array
2695 * case folded alias => real name
2697 function getSpecialPageAliases() {
2698 // Cache aliases because it may be slow to load them
2699 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2701 $this->mExtendedSpecialPageAliases
=
2702 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2703 wfRunHooks( 'LanguageGetSpecialPageAliases',
2704 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2707 return $this->mExtendedSpecialPageAliases
;
2711 * Italic is unsuitable for some languages
2713 * @param $text String: the text to be emphasized.
2716 function emphasize( $text ) {
2717 return "<em>$text</em>";
2721 * Normally we output all numbers in plain en_US style, that is
2722 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2723 * point twohundredthirtyfive. However this is not suitable for all
2724 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2725 * Icelandic just want to use commas instead of dots, and dots instead
2726 * of commas like "293.291,235".
2728 * An example of this function being called:
2730 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2733 * See LanguageGu.php for the Gujarati implementation and
2734 * $separatorTransformTable on MessageIs.php for
2735 * the , => . and . => , implementation.
2737 * @todo check if it's viable to use localeconv() for the decimal
2739 * @param $number Mixed: the string to be formatted, should be an integer
2740 * or a floating point number.
2741 * @param $nocommafy Bool: set to true for special numbers like dates
2744 public function formatNum( $number, $nocommafy = false ) {
2745 global $wgTranslateNumerals;
2746 if ( !$nocommafy ) {
2747 $number = $this->commafy( $number );
2748 $s = $this->separatorTransformTable();
2750 $number = strtr( $number, $s );
2754 if ( $wgTranslateNumerals ) {
2755 $s = $this->digitTransformTable();
2757 $number = strtr( $number, $s );
2765 * @param $number string
2768 function parseFormattedNumber( $number ) {
2769 $s = $this->digitTransformTable();
2771 $number = strtr( $number, array_flip( $s ) );
2774 $s = $this->separatorTransformTable();
2776 $number = strtr( $number, array_flip( $s ) );
2779 $number = strtr( $number, array( ',' => '' ) );
2784 * Adds commas to a given number
2789 function commafy( $_ ) {
2790 $digitGroupingPattern = $this->digitGroupingPattern();
2791 if ( $_ === null ) {
2795 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2796 // default grouping is at thousands, use the same for ###,###,### pattern too.
2797 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2799 // Ref: http://cldr.unicode.org/translation/number-patterns
2801 if ( intval( $_ ) < 0 ) {
2802 // For negative numbers apply the algorithm like positive number and add sign.
2804 $_ = substr( $_, 1 );
2806 $numberpart = array();
2807 $decimalpart = array();
2808 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2809 preg_match( "/\d+/", $_, $numberpart );
2810 preg_match( "/\.\d*/", $_, $decimalpart );
2811 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2812 if ( $groupedNumber === $_ ) {
2813 // the string does not have any number part. Eg: .12345
2814 return $sign . $groupedNumber;
2816 $start = $end = strlen( $numberpart[0] );
2817 while ( $start > 0 ) {
2818 $match = $matches[0][$numMatches -1] ;
2819 $matchLen = strlen( $match );
2820 $start = $end - $matchLen;
2824 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2826 if ( $numMatches > 1 ) {
2827 // use the last pattern for the rest of the number
2831 $groupedNumber = "," . $groupedNumber;
2834 return $sign . $groupedNumber;
2840 function digitGroupingPattern() {
2841 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2847 function digitTransformTable() {
2848 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2854 function separatorTransformTable() {
2855 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2859 * Take a list of strings and build a locale-friendly comma-separated
2860 * list, using the local comma-separator message.
2861 * The last two strings are chained with an "and".
2866 function listToText( array $l ) {
2868 $m = count( $l ) - 1;
2870 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2872 for ( $i = $m; $i >= 0; $i-- ) {
2875 } elseif ( $i == $m - 1 ) {
2876 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2878 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2886 * Take a list of strings and build a locale-friendly comma-separated
2887 * list, using the local comma-separator message.
2888 * @param $list array of strings to put in a comma list
2891 function commaList( array $list ) {
2895 array( 'parsemag', 'escapenoentities', 'language' => $this )
2902 * Take a list of strings and build a locale-friendly semicolon-separated
2903 * list, using the local semicolon-separator message.
2904 * @param $list array of strings to put in a semicolon list
2907 function semicolonList( array $list ) {
2910 'semicolon-separator',
2911 array( 'parsemag', 'escapenoentities', 'language' => $this )
2918 * Same as commaList, but separate it with the pipe instead.
2919 * @param $list array of strings to put in a pipe list
2922 function pipeList( array $list ) {
2926 array( 'escapenoentities', 'language' => $this )
2933 * Truncate a string to a specified length in bytes, appending an optional
2934 * string (e.g. for ellipses)
2936 * The database offers limited byte lengths for some columns in the database;
2937 * multi-byte character sets mean we need to ensure that only whole characters
2938 * are included, otherwise broken characters can be passed to the user
2940 * If $length is negative, the string will be truncated from the beginning
2942 * @param $string String to truncate
2943 * @param $length Int: maximum length (including ellipses)
2944 * @param $ellipsis String to append to the truncated text
2945 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2946 * $adjustLength was introduced in 1.18, before that behaved as if false.
2949 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2950 # Use the localized ellipsis character
2951 if ( $ellipsis == '...' ) {
2952 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2954 # Check if there is no need to truncate
2955 if ( $length == 0 ) {
2956 return $ellipsis; // convention
2957 } elseif ( strlen( $string ) <= abs( $length ) ) {
2958 return $string; // no need to truncate
2960 $stringOriginal = $string;
2961 # If ellipsis length is >= $length then we can't apply $adjustLength
2962 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2963 $string = $ellipsis; // this can be slightly unexpected
2964 # Otherwise, truncate and add ellipsis...
2966 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2967 if ( $length > 0 ) {
2968 $length -= $eLength;
2969 $string = substr( $string, 0, $length ); // xyz...
2970 $string = $this->removeBadCharLast( $string );
2971 $string = $string . $ellipsis;
2973 $length +
= $eLength;
2974 $string = substr( $string, $length ); // ...xyz
2975 $string = $this->removeBadCharFirst( $string );
2976 $string = $ellipsis . $string;
2979 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2980 # This check is *not* redundant if $adjustLength, due to the single case where
2981 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2982 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2985 return $stringOriginal;
2990 * Remove bytes that represent an incomplete Unicode character
2991 * at the end of string (e.g. bytes of the char are missing)
2993 * @param $string String
2996 protected function removeBadCharLast( $string ) {
2997 if ( $string != '' ) {
2998 $char = ord( $string[strlen( $string ) - 1] );
3000 if ( $char >= 0xc0 ) {
3001 # We got the first byte only of a multibyte char; remove it.
3002 $string = substr( $string, 0, -1 );
3003 } elseif ( $char >= 0x80 &&
3004 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3005 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3007 # We chopped in the middle of a character; remove it
3015 * Remove bytes that represent an incomplete Unicode character
3016 * at the start of string (e.g. bytes of the char are missing)
3018 * @param $string String
3021 protected function removeBadCharFirst( $string ) {
3022 if ( $string != '' ) {
3023 $char = ord( $string[0] );
3024 if ( $char >= 0x80 && $char < 0xc0 ) {
3025 # We chopped in the middle of a character; remove the whole thing
3026 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3033 * Truncate a string of valid HTML to a specified length in bytes,
3034 * appending an optional string (e.g. for ellipses), and return valid HTML
3036 * This is only intended for styled/linked text, such as HTML with
3037 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3038 * Also, this will not detect things like "display:none" CSS.
3040 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3042 * @param string $text HTML string to truncate
3043 * @param int $length (zero/positive) Maximum length (including ellipses)
3044 * @param string $ellipsis String to append to the truncated text
3047 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3048 # Use the localized ellipsis character
3049 if ( $ellipsis == '...' ) {
3050 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3052 # Check if there is clearly no need to truncate
3053 if ( $length <= 0 ) {
3054 return $ellipsis; // no text shown, nothing to format (convention)
3055 } elseif ( strlen( $text ) <= $length ) {
3056 return $text; // string short enough even *with* HTML (short-circuit)
3059 $dispLen = 0; // innerHTML legth so far
3060 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3061 $tagType = 0; // 0-open, 1-close
3062 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3063 $entityState = 0; // 0-not entity, 1-entity
3064 $tag = $ret = ''; // accumulated tag name, accumulated result string
3065 $openTags = array(); // open tag stack
3066 $maybeState = null; // possible truncation state
3068 $textLen = strlen( $text );
3069 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3070 for ( $pos = 0; true; ++
$pos ) {
3071 # Consider truncation once the display length has reached the maximim.
3072 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3073 # Check that we're not in the middle of a bracket/entity...
3074 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3075 if ( !$testingEllipsis ) {
3076 $testingEllipsis = true;
3077 # Save where we are; we will truncate here unless there turn out to
3078 # be so few remaining characters that truncation is not necessary.
3079 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3080 $maybeState = array( $ret, $openTags ); // save state
3082 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3083 # String in fact does need truncation, the truncation point was OK.
3084 list( $ret, $openTags ) = $maybeState; // reload state
3085 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3086 $ret .= $ellipsis; // add ellipsis
3090 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3092 # Read the next char...
3094 $lastCh = $pos ?
$text[$pos - 1] : '';
3095 $ret .= $ch; // add to result string
3097 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3098 $entityState = 0; // for bad HTML
3099 $bracketState = 1; // tag started (checking for backslash)
3100 } elseif ( $ch == '>' ) {
3101 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3102 $entityState = 0; // for bad HTML
3103 $bracketState = 0; // out of brackets
3104 } elseif ( $bracketState == 1 ) {
3106 $tagType = 1; // close tag (e.g. "</span>")
3108 $tagType = 0; // open tag (e.g. "<span>")
3111 $bracketState = 2; // building tag name
3112 } elseif ( $bracketState == 2 ) {
3116 // Name found (e.g. "<a href=..."), add on tag attributes...
3117 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3119 } elseif ( $bracketState == 0 ) {
3120 if ( $entityState ) {
3123 $dispLen++
; // entity is one displayed char
3126 if ( $neLength == 0 && !$maybeState ) {
3127 // Save state without $ch. We want to *hit* the first
3128 // display char (to get tags) but not *use* it if truncating.
3129 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3132 $entityState = 1; // entity found, (e.g. " ")
3134 $dispLen++
; // this char is displayed
3135 // Add the next $max display text chars after this in one swoop...
3136 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3137 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3138 $dispLen +
= $skipped;
3144 // Close the last tag if left unclosed by bad HTML
3145 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3146 while ( count( $openTags ) > 0 ) {
3147 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3153 * truncateHtml() helper function
3154 * like strcspn() but adds the skipped chars to $ret
3163 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3164 if ( $len === null ) {
3165 $len = -1; // -1 means "no limit" for strcspn
3166 } elseif ( $len < 0 ) {
3170 if ( $start < strlen( $text ) ) {
3171 $skipCount = strcspn( $text, $search, $start, $len );
3172 $ret .= substr( $text, $start, $skipCount );
3178 * truncateHtml() helper function
3179 * (a) push or pop $tag from $openTags as needed
3180 * (b) clear $tag value
3181 * @param &$tag string Current HTML tag name we are looking at
3182 * @param $tagType int (0-open tag, 1-close tag)
3183 * @param $lastCh string Character before the '>' that ended this tag
3184 * @param &$openTags array Open tag stack (not accounting for $tag)
3186 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3187 $tag = ltrim( $tag );
3189 if ( $tagType == 0 && $lastCh != '/' ) {
3190 $openTags[] = $tag; // tag opened (didn't close itself)
3191 } elseif ( $tagType == 1 ) {
3192 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3193 array_pop( $openTags ); // tag closed
3201 * Grammatical transformations, needed for inflected languages
3202 * Invoked by putting {{grammar:case|word}} in a message
3204 * @param $word string
3205 * @param $case string
3208 function convertGrammar( $word, $case ) {
3209 global $wgGrammarForms;
3210 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3211 return $wgGrammarForms[$this->getCode()][$case][$word];
3217 * Provides an alternative text depending on specified gender.
3218 * Usage {{gender:username|masculine|feminine|neutral}}.
3219 * username is optional, in which case the gender of current user is used,
3220 * but only in (some) interface messages; otherwise default gender is used.
3222 * If no forms are given, an empty string is returned. If only one form is
3223 * given, it will be returned unconditionally. These details are implied by
3224 * the caller and cannot be overridden in subclasses.
3226 * If more than one form is given, the default is to use the neutral one
3227 * if it is specified, and to use the masculine one otherwise. These
3228 * details can be overridden in subclasses.
3230 * @param $gender string
3231 * @param $forms array
3235 function gender( $gender, $forms ) {
3236 if ( !count( $forms ) ) {
3239 $forms = $this->preConvertPlural( $forms, 2 );
3240 if ( $gender === 'male' ) {
3243 if ( $gender === 'female' ) {
3246 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3250 * Plural form transformations, needed for some languages.
3251 * For example, there are 3 form of plural in Russian and Polish,
3252 * depending on "count mod 10". See [[w:Plural]]
3253 * For English it is pretty simple.
3255 * Invoked by putting {{plural:count|wordform1|wordform2}}
3256 * or {{plural:count|wordform1|wordform2|wordform3}}
3258 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3260 * @param $count Integer: non-localized number
3261 * @param $forms Array: different plural forms
3262 * @return string Correct form of plural for $count in this language
3264 function convertPlural( $count, $forms ) {
3265 if ( !count( $forms ) ) {
3268 $forms = $this->preConvertPlural( $forms, 2 );
3270 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3274 * Checks that convertPlural was given an array and pads it to requested
3275 * amount of forms by copying the last one.
3277 * @param $count Integer: How many forms should there be at least
3278 * @param $forms Array of forms given to convertPlural
3279 * @return array Padded array of forms or an exception if not an array
3281 protected function preConvertPlural( /* Array */ $forms, $count ) {
3282 while ( count( $forms ) < $count ) {
3283 $forms[] = $forms[count( $forms ) - 1];
3289 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3290 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3291 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3292 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3295 * @param $str String: the validated block duration in English
3296 * @return string Somehow translated block duration
3297 * @see LanguageFi.php for example implementation
3299 function translateBlockExpiry( $str ) {
3300 $duration = SpecialBlock
::getSuggestedDurations( $this );
3301 foreach ( $duration as $show => $value ) {
3302 if ( strcmp( $str, $value ) == 0 ) {
3303 return htmlspecialchars( trim( $show ) );
3307 // Since usually only infinite or indefinite is only on list, so try
3308 // equivalents if still here.
3309 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3310 if ( in_array( $str, $indefs ) ) {
3311 foreach ( $indefs as $val ) {
3312 $show = array_search( $val, $duration, true );
3313 if ( $show !== false ) {
3314 return htmlspecialchars( trim( $show ) );
3318 // If all else fails, return the original string.
3323 * languages like Chinese need to be segmented in order for the diff
3326 * @param $text String
3329 public function segmentForDiff( $text ) {
3334 * and unsegment to show the result
3336 * @param $text String
3339 public function unsegmentForDiff( $text ) {
3344 * Return the LanguageConverter used in the Language
3347 * @return LanguageConverter
3349 public function getConverter() {
3350 return $this->mConverter
;
3354 * convert text to all supported variants
3356 * @param $text string
3359 public function autoConvertToAllVariants( $text ) {
3360 return $this->mConverter
->autoConvertToAllVariants( $text );
3364 * convert text to different variants of a language.
3366 * @param $text string
3369 public function convert( $text ) {
3370 return $this->mConverter
->convert( $text );
3374 * Convert a Title object to a string in the preferred variant
3376 * @param $title Title
3379 public function convertTitle( $title ) {
3380 return $this->mConverter
->convertTitle( $title );
3384 * Check if this is a language with variants
3388 public function hasVariants() {
3389 return sizeof( $this->getVariants() ) > 1;
3393 * Check if the language has the specific variant
3396 * @param $variant string
3399 public function hasVariant( $variant ) {
3400 return (bool)$this->mConverter
->validateVariant( $variant );
3404 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3406 * @param $text string
3409 public function armourMath( $text ) {
3410 return $this->mConverter
->armourMath( $text );
3414 * Perform output conversion on a string, and encode for safe HTML output.
3415 * @param $text String text to be converted
3416 * @param $isTitle Bool whether this conversion is for the article title
3418 * @todo this should get integrated somewhere sane
3420 public function convertHtml( $text, $isTitle = false ) {
3421 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3425 * @param $key string
3428 public function convertCategoryKey( $key ) {
3429 return $this->mConverter
->convertCategoryKey( $key );
3433 * Get the list of variants supported by this language
3434 * see sample implementation in LanguageZh.php
3436 * @return array an array of language codes
3438 public function getVariants() {
3439 return $this->mConverter
->getVariants();
3445 public function getPreferredVariant() {
3446 return $this->mConverter
->getPreferredVariant();
3452 public function getDefaultVariant() {
3453 return $this->mConverter
->getDefaultVariant();
3459 public function getURLVariant() {
3460 return $this->mConverter
->getURLVariant();
3464 * If a language supports multiple variants, it is
3465 * possible that non-existing link in one variant
3466 * actually exists in another variant. this function
3467 * tries to find it. See e.g. LanguageZh.php
3469 * @param $link String: the name of the link
3470 * @param $nt Mixed: the title object of the link
3471 * @param $ignoreOtherCond Boolean: to disable other conditions when
3472 * we need to transclude a template or update a category's link
3473 * @return null the input parameters may be modified upon return
3475 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3476 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3480 * If a language supports multiple variants, converts text
3481 * into an array of all possible variants of the text:
3482 * 'variant' => text in that variant
3484 * @deprecated since 1.17 Use autoConvertToAllVariants()
3486 * @param $text string
3490 public function convertLinkToAllVariants( $text ) {
3491 return $this->mConverter
->convertLinkToAllVariants( $text );
3495 * returns language specific options used by User::getPageRenderHash()
3496 * for example, the preferred language variant
3500 function getExtraHashOptions() {
3501 return $this->mConverter
->getExtraHashOptions();
3505 * For languages that support multiple variants, the title of an
3506 * article may be displayed differently in different variants. this
3507 * function returns the apporiate title defined in the body of the article.
3511 public function getParsedTitle() {
3512 return $this->mConverter
->getParsedTitle();
3516 * Enclose a string with the "no conversion" tag. This is used by
3517 * various functions in the Parser
3519 * @param $text String: text to be tagged for no conversion
3520 * @param $noParse bool
3521 * @return string the tagged text
3523 public function markNoConversion( $text, $noParse = false ) {
3524 return $this->mConverter
->markNoConversion( $text, $noParse );
3528 * A regular expression to match legal word-trailing characters
3529 * which should be merged onto a link of the form [[foo]]bar.
3533 public function linkTrail() {
3534 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3540 function getLangObj() {
3545 * Get the RFC 3066 code for this language object
3549 public function getCode() {
3550 return $this->mCode
;
3554 * Get the code in Bcp47 format which we can use
3555 * inside of html lang="" tags.
3559 public function getHtmlCode() {
3560 if ( is_null( $this->mHtmlCode
) ) {
3561 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3563 return $this->mHtmlCode
;
3567 * @param $code string
3569 public function setCode( $code ) {
3570 $this->mCode
= $code;
3571 // Ensure we don't leave an incorrect html code lying around
3572 $this->mHtmlCode
= null;
3576 * Get the name of a file for a certain language code
3577 * @param $prefix string Prepend this to the filename
3578 * @param $code string Language code
3579 * @param $suffix string Append this to the filename
3580 * @return string $prefix . $mangledCode . $suffix
3582 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3583 // Protect against path traversal
3584 if ( !Language
::isValidCode( $code )
3585 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3587 throw new MWException( "Invalid language code \"$code\"" );
3590 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3594 * Get the language code from a file name. Inverse of getFileName()
3595 * @param $filename string $prefix . $languageCode . $suffix
3596 * @param $prefix string Prefix before the language code
3597 * @param $suffix string Suffix after the language code
3598 * @return string Language code, or false if $prefix or $suffix isn't found
3600 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3602 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3603 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3604 if ( !count( $m ) ) {
3607 return str_replace( '_', '-', strtolower( $m[1] ) );
3611 * @param $code string
3614 public static function getMessagesFileName( $code ) {
3616 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3617 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3622 * @param $code string
3625 public static function getClassFileName( $code ) {
3627 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3631 * Get the first fallback for a given language.
3633 * @param $code string
3635 * @return bool|string
3637 public static function getFallbackFor( $code ) {
3638 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3641 $fallbacks = self
::getFallbacksFor( $code );
3642 $first = array_shift( $fallbacks );
3648 * Get the ordered list of fallback languages.
3651 * @param $code string Language code
3654 public static function getFallbacksFor( $code ) {
3655 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3658 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3659 $v = array_map( 'trim', explode( ',', $v ) );
3660 if ( $v[count( $v ) - 1] !== 'en' ) {
3668 * Get all messages for a given language
3669 * WARNING: this may take a long time. If you just need all message *keys*
3670 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3672 * @param $code string
3676 public static function getMessagesFor( $code ) {
3677 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3681 * Get a message for a given language
3683 * @param $key string
3684 * @param $code string
3688 public static function getMessageFor( $key, $code ) {
3689 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3693 * Get all message keys for a given language. This is a faster alternative to
3694 * array_keys( Language::getMessagesFor( $code ) )
3697 * @param $code string Language code
3698 * @return array of message keys (strings)
3700 public static function getMessageKeysFor( $code ) {
3701 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3708 function fixVariableInNamespace( $talk ) {
3709 if ( strpos( $talk, '$1' ) === false ) {
3713 global $wgMetaNamespace;
3714 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3716 # Allow grammar transformations
3717 # Allowing full message-style parsing would make simple requests
3718 # such as action=raw much more expensive than they need to be.
3719 # This will hopefully cover most cases.
3720 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3721 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3722 return str_replace( ' ', '_', $talk );
3729 function replaceGrammarInNamespace( $m ) {
3730 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3734 * @throws MWException
3737 static function getCaseMaps() {
3738 static $wikiUpperChars, $wikiLowerChars;
3739 if ( isset( $wikiUpperChars ) ) {
3740 return array( $wikiUpperChars, $wikiLowerChars );
3743 wfProfileIn( __METHOD__
);
3744 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3745 if ( $arr === false ) {
3746 throw new MWException(
3747 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3749 $wikiUpperChars = $arr['wikiUpperChars'];
3750 $wikiLowerChars = $arr['wikiLowerChars'];
3751 wfProfileOut( __METHOD__
);
3752 return array( $wikiUpperChars, $wikiLowerChars );
3756 * Decode an expiry (block, protection, etc) which has come from the DB
3758 * @param $expiry String: Database expiry String
3759 * @param $format Bool|Int true to process using language functions, or TS_ constant
3760 * to return the expiry in a given timestamp
3763 public function formatExpiry( $expiry, $format = true ) {
3764 static $infinity, $infinityMsg;
3765 if ( $infinity === null ) {
3766 $infinityMsg = wfMessage( 'infiniteblock' );
3767 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3770 if ( $expiry == '' ||
$expiry == $infinity ) {
3771 return $format === true
3775 return $format === true
3776 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3777 : wfTimestamp( $format, $expiry );
3783 * @param $seconds int|float
3784 * @param $format Array Optional
3785 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3786 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3787 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3788 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3791 function formatTimePeriod( $seconds, $format = array() ) {
3792 if ( !is_array( $format ) ) {
3793 $format = array( 'avoid' => $format ); // For backwards compatibility
3795 if ( !isset( $format['avoid'] ) ) {
3796 $format['avoid'] = false;
3798 if ( !isset( $format['noabbrevs' ] ) ) {
3799 $format['noabbrevs'] = false;
3801 $secondsMsg = wfMessage(
3802 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3803 $minutesMsg = wfMessage(
3804 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3805 $hoursMsg = wfMessage(
3806 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3807 $daysMsg = wfMessage(
3808 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3810 if ( round( $seconds * 10 ) < 100 ) {
3811 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3812 $s = $secondsMsg->params( $s )->text();
3813 } elseif ( round( $seconds ) < 60 ) {
3814 $s = $this->formatNum( round( $seconds ) );
3815 $s = $secondsMsg->params( $s )->text();
3816 } elseif ( round( $seconds ) < 3600 ) {
3817 $minutes = floor( $seconds / 60 );
3818 $secondsPart = round( fmod( $seconds, 60 ) );
3819 if ( $secondsPart == 60 ) {
3823 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3825 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3826 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3827 $hours = floor( $seconds / 3600 );
3828 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3829 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3830 if ( $secondsPart == 60 ) {
3834 if ( $minutes == 60 ) {
3838 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3840 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3841 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3842 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3845 $days = floor( $seconds / 86400 );
3846 if ( $format['avoid'] === 'avoidminutes' ) {
3847 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3848 if ( $hours == 24 ) {
3852 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3854 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3855 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3856 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3857 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3858 if ( $minutes == 60 ) {
3862 if ( $hours == 24 ) {
3866 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3868 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3870 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3872 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3874 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3881 * Format a bitrate for output, using an appropriate
3882 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3884 * This use base 1000. For base 1024 use formatSize(), for another base
3885 * see formatComputingNumbers()
3890 function formatBitrate( $bps ) {
3891 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3895 * @param $size int Size of the unit
3896 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3897 * @param $messageKey string Message key to be uesd
3900 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3902 return str_replace( '$1', $this->formatNum( $size ),
3903 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3906 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3909 $maxIndex = count( $sizes ) - 1;
3910 while ( $size >= $boundary && $index < $maxIndex ) {
3915 // For small sizes no decimal places necessary
3918 // For MB and bigger two decimal places are smarter
3921 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3923 $size = round( $size, $round );
3924 $text = $this->getMessageFromDB( $msg );
3925 return str_replace( '$1', $this->formatNum( $size ), $text );
3929 * Format a size in bytes for output, using an appropriate
3930 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3932 * This method use base 1024. For base 1000 use formatBitrate(), for
3933 * another base see formatComputingNumbers()
3935 * @param $size int Size to format
3936 * @return string Plain text (not HTML)
3938 function formatSize( $size ) {
3939 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3943 * Make a list item, used by various special pages
3945 * @param $page String Page link
3946 * @param $details String Text between brackets
3947 * @param $oppositedm Boolean Add the direction mark opposite to your
3948 * language, to display text properly
3951 function specialList( $page, $details, $oppositedm = true ) {
3952 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3953 $this->getDirMark();
3954 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3955 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3956 return $page . $details;
3960 * Generate (prev x| next x) (20|50|100...) type links for paging
3962 * @param $title Title object to link
3963 * @param $offset Integer offset parameter
3964 * @param $limit Integer limit parameter
3965 * @param $query String optional URL query parameter string
3966 * @param $atend Bool optional param for specified if this is the last page
3969 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3970 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3972 # Make 'previous' link
3973 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3974 if ( $offset > 0 ) {
3975 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3976 $query, $prev, 'prevn-title', 'mw-prevlink' );
3978 $plink = htmlspecialchars( $prev );
3982 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3984 $nlink = htmlspecialchars( $next );
3986 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3987 $query, $next, 'prevn-title', 'mw-nextlink' );
3990 # Make links to set number of items per page
3991 $numLinks = array();
3992 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
3993 $numLinks[] = $this->numLink( $title, $offset, $num,
3994 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3997 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3998 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4002 * Helper function for viewPrevNext() that generates links
4004 * @param $title Title object to link
4005 * @param $offset Integer offset parameter
4006 * @param $limit Integer limit parameter
4007 * @param $query Array extra query parameters
4008 * @param $link String text to use for the link; will be escaped
4009 * @param $tooltipMsg String name of the message to use as tooltip
4010 * @param $class String value of the "class" attribute of the link
4011 * @return String HTML fragment
4013 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4014 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4015 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4016 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4017 'title' => $tooltip, 'class' => $class ), $link );
4021 * Get the conversion rule title, if any.
4025 public function getConvRuleTitle() {
4026 return $this->mConverter
->getConvRuleTitle();