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
161 * @throws MWException
164 protected static function newFromCode( $code ) {
165 // Protect against path traversal below
166 if ( !Language
::isValidCode( $code )
167 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
169 throw new MWException( "Invalid language code \"$code\"" );
172 if ( !Language
::isValidBuiltInCode( $code ) ) {
173 // It's not possible to customise this code with class files, so
174 // just return a Language object. This is to support uselang= hacks.
175 $lang = new Language
;
176 $lang->setCode( $code );
180 // Check if there is a language class for the code
181 $class = self
::classFromCode( $code );
182 self
::preloadLanguageClass( $class );
183 if ( MWInit
::classExists( $class ) ) {
188 // Keep trying the fallback list until we find an existing class
189 $fallbacks = Language
::getFallbacksFor( $code );
190 foreach ( $fallbacks as $fallbackCode ) {
191 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
192 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
195 $class = self
::classFromCode( $fallbackCode );
196 self
::preloadLanguageClass( $class );
197 if ( MWInit
::classExists( $class ) ) {
198 $lang = Language
::newFromCode( $fallbackCode );
199 $lang->setCode( $code );
204 throw new MWException( "Invalid fallback sequence for language '$code'" );
208 * Returns true if a language code string is of a valid form, whether or
209 * not it exists. This includes codes which are used solely for
210 * customisation via the MediaWiki namespace.
212 * @param $code string
216 public static function isValidCode( $code ) {
218 strcspn( $code, ":/\\\000" ) === strlen( $code )
219 && !preg_match( Title
::getTitleInvalidRegex(), $code );
223 * Returns true if a language code is of a valid form for the purposes of
224 * internal customisation of MediaWiki, via Messages*.php.
226 * @param $code string
231 public static function isValidBuiltInCode( $code ) {
232 return preg_match( '/^[a-z0-9-]+$/i', $code );
237 * @return String Name of the language class
239 public static function classFromCode( $code ) {
240 if ( $code == 'en' ) {
243 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
248 * Includes language class files
250 * @param $class string Name of the language class
252 public static function preloadLanguageClass( $class ) {
255 if ( $class === 'Language' ) {
259 if ( !defined( 'MW_COMPILED' ) ) {
260 // Preload base classes to work around APC/PHP5 bug
261 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
262 include_once( "$IP/languages/classes/$class.deps.php" );
264 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
265 include_once( "$IP/languages/classes/$class.php" );
271 * Get the LocalisationCache instance
273 * @return LocalisationCache
275 public static function getLocalisationCache() {
276 if ( is_null( self
::$dataCache ) ) {
277 global $wgLocalisationCacheConf;
278 $class = $wgLocalisationCacheConf['class'];
279 self
::$dataCache = new $class( $wgLocalisationCacheConf );
281 return self
::$dataCache;
284 function __construct() {
285 $this->mConverter
= new FakeConverter( $this );
286 // Set the code to the name of the descendant
287 if ( get_class( $this ) == 'Language' ) {
290 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
292 self
::getLocalisationCache();
296 * Reduce memory usage
298 function __destruct() {
299 foreach ( $this as $name => $value ) {
300 unset( $this->$name );
305 * Hook which will be called if this is the content language.
306 * Descendants can use this to register hook functions or modify globals
308 function initContLang() { }
311 * Same as getFallbacksFor for current language.
313 * @deprecated in 1.19
315 function getFallbackLanguageCode() {
316 wfDeprecated( __METHOD__
);
317 return self
::getFallbackFor( $this->mCode
);
324 function getFallbackLanguages() {
325 return self
::getFallbacksFor( $this->mCode
);
329 * Exports $wgBookstoreListEn
332 function getBookstoreList() {
333 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
339 public function getNamespaces() {
340 if ( is_null( $this->namespaceNames
) ) {
341 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
343 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
344 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
346 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
348 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
349 if ( $wgMetaNamespaceTalk ) {
350 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
352 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
353 $this->namespaceNames
[NS_PROJECT_TALK
] =
354 $this->fixVariableInNamespace( $talk );
357 # Sometimes a language will be localised but not actually exist on this wiki.
358 foreach ( $this->namespaceNames
as $key => $text ) {
359 if ( !isset( $validNamespaces[$key] ) ) {
360 unset( $this->namespaceNames
[$key] );
364 # The above mixing may leave namespaces out of canonical order.
365 # Re-order by namespace ID number...
366 ksort( $this->namespaceNames
);
368 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
370 return $this->namespaceNames
;
374 * Arbitrarily set all of the namespace names at once. Mainly used for testing
375 * @param $namespaces Array of namespaces (id => name)
377 public function setNamespaces( array $namespaces ) {
378 $this->namespaceNames
= $namespaces;
382 * A convenience function that returns the same thing as
383 * getNamespaces() except with the array values changed to ' '
384 * where it found '_', useful for producing output to be displayed
385 * e.g. in <select> forms.
389 function getFormattedNamespaces() {
390 $ns = $this->getNamespaces();
391 foreach ( $ns as $k => $v ) {
392 $ns[$k] = strtr( $v, '_', ' ' );
398 * Get a namespace value by key
400 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
401 * echo $mw_ns; // prints 'MediaWiki'
404 * @param $index Int: the array key of the namespace to return
405 * @return mixed, string if the namespace value exists, otherwise false
407 function getNsText( $index ) {
408 $ns = $this->getNamespaces();
409 return isset( $ns[$index] ) ?
$ns[$index] : false;
413 * A convenience function that returns the same thing as
414 * getNsText() except with '_' changed to ' ', useful for
417 * @param $index string
421 function getFormattedNsText( $index ) {
422 $ns = $this->getNsText( $index );
423 return strtr( $ns, '_', ' ' );
427 * Returns gender-dependent namespace alias if available.
428 * @param $index Int: namespace index
429 * @param $gender String: gender key (male, female... )
433 function getGenderNsText( $index, $gender ) {
434 global $wgExtraGenderNamespaces;
436 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
437 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
441 * Whether this language makes distinguishes genders for example in
446 function needsGenderDistinction() {
447 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
448 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
449 // $wgExtraGenderNamespaces overrides everything
451 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
452 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
453 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
456 // Check what is in i18n files
457 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
458 return count( $aliases ) > 0;
463 * Get a namespace key by value, case insensitive.
464 * Only matches namespace names for the current language, not the
465 * canonical ones defined in Namespace.php.
467 * @param $text String
468 * @return mixed An integer if $text is a valid value otherwise false
470 function getLocalNsIndex( $text ) {
471 $lctext = $this->lc( $text );
472 $ids = $this->getNamespaceIds();
473 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
479 function getNamespaceAliases() {
480 if ( is_null( $this->namespaceAliases
) ) {
481 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
485 foreach ( $aliases as $name => $index ) {
486 if ( $index === NS_PROJECT_TALK
) {
487 unset( $aliases[$name] );
488 $name = $this->fixVariableInNamespace( $name );
489 $aliases[$name] = $index;
494 global $wgExtraGenderNamespaces;
495 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
496 foreach ( $genders as $index => $forms ) {
497 foreach ( $forms as $alias ) {
498 $aliases[$alias] = $index;
502 $this->namespaceAliases
= $aliases;
504 return $this->namespaceAliases
;
510 function getNamespaceIds() {
511 if ( is_null( $this->mNamespaceIds
) ) {
512 global $wgNamespaceAliases;
513 # Put namespace names and aliases into a hashtable.
514 # If this is too slow, then we should arrange it so that it is done
515 # before caching. The catch is that at pre-cache time, the above
516 # class-specific fixup hasn't been done.
517 $this->mNamespaceIds
= array();
518 foreach ( $this->getNamespaces() as $index => $name ) {
519 $this->mNamespaceIds
[$this->lc( $name )] = $index;
521 foreach ( $this->getNamespaceAliases() as $name => $index ) {
522 $this->mNamespaceIds
[$this->lc( $name )] = $index;
524 if ( $wgNamespaceAliases ) {
525 foreach ( $wgNamespaceAliases as $name => $index ) {
526 $this->mNamespaceIds
[$this->lc( $name )] = $index;
530 return $this->mNamespaceIds
;
534 * Get a namespace key by value, case insensitive. Canonical namespace
535 * names override custom ones defined for the current language.
537 * @param $text String
538 * @return mixed An integer if $text is a valid value otherwise false
540 function getNsIndex( $text ) {
541 $lctext = $this->lc( $text );
542 $ns = MWNamespace
::getCanonicalIndex( $lctext );
543 if ( $ns !== null ) {
546 $ids = $this->getNamespaceIds();
547 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
551 * short names for language variants used for language conversion links.
553 * @param $code String
554 * @param $usemsg bool Use the "variantname-xyz" message if it exists
557 function getVariantname( $code, $usemsg = true ) {
558 $msg = "variantname-$code";
559 list( $rootCode ) = explode( '-', $code );
560 if ( $usemsg && wfMessage( $msg )->exists() ) {
561 return $this->getMessageFromDB( $msg );
563 $name = self
::fetchLanguageName( $code );
565 return $name; # if it's defined as a language name, show that
567 # otherwise, output the language code
573 * @param $name string
576 function specialPage( $name ) {
577 $aliases = $this->getSpecialPageAliases();
578 if ( isset( $aliases[$name][0] ) ) {
579 $name = $aliases[$name][0];
581 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
587 function getQuickbarSettings() {
589 $this->getMessage( 'qbsettings-none' ),
590 $this->getMessage( 'qbsettings-fixedleft' ),
591 $this->getMessage( 'qbsettings-fixedright' ),
592 $this->getMessage( 'qbsettings-floatingleft' ),
593 $this->getMessage( 'qbsettings-floatingright' ),
594 $this->getMessage( 'qbsettings-directionality' )
601 function getDatePreferences() {
602 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
608 function getDateFormats() {
609 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
613 * @return array|string
615 function getDefaultDateFormat() {
616 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
617 if ( $df === 'dmy or mdy' ) {
618 global $wgAmericanDates;
619 return $wgAmericanDates ?
'mdy' : 'dmy';
628 function getDatePreferenceMigrationMap() {
629 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
636 function getImageFile( $image ) {
637 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
643 function getExtraUserToggles() {
644 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
651 function getUserToggle( $tog ) {
652 return $this->getMessageFromDB( "tog-$tog" );
656 * Get native language names, indexed by code.
657 * Only those defined in MediaWiki, no other data like CLDR.
658 * If $customisedOnly is true, only returns codes with a messages file
660 * @param $customisedOnly bool
663 * @deprecated in 1.20, use fetchLanguageNames()
665 public static function getLanguageNames( $customisedOnly = false ) {
666 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
670 * Get translated language names. This is done on best effort and
671 * by default this is exactly the same as Language::getLanguageNames.
672 * The CLDR extension provides translated names.
673 * @param $code String Language code.
674 * @return Array language code => language name
676 * @deprecated in 1.20, use fetchLanguageNames()
678 public static function getTranslatedLanguageNames( $code ) {
679 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|bool: 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
2542 * @throws MWException
2545 function transformUsingPairFile( $file, $string ) {
2546 if ( !isset( $this->transformData
[$file] ) ) {
2547 $data = wfGetPrecompiledData( $file );
2548 if ( $data === false ) {
2549 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2551 $this->transformData
[$file] = new ReplacementArray( $data );
2553 return $this->transformData
[$file]->replace( $string );
2557 * For right-to-left language support
2562 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2566 * Return the correct HTML 'dir' attribute value for this language.
2570 return $this->isRTL() ?
'rtl' : 'ltr';
2574 * Return 'left' or 'right' as appropriate alignment for line-start
2575 * for this language's text direction.
2577 * Should be equivalent to CSS3 'start' text-align value....
2581 function alignStart() {
2582 return $this->isRTL() ?
'right' : 'left';
2586 * Return 'right' or 'left' as appropriate alignment for line-end
2587 * for this language's text direction.
2589 * Should be equivalent to CSS3 'end' text-align value....
2593 function alignEnd() {
2594 return $this->isRTL() ?
'left' : 'right';
2598 * A hidden direction mark (LRM or RLM), depending on the language direction
2600 * @param $opposite Boolean Get the direction mark opposite to your language
2603 function getDirMark( $opposite = false ) {
2604 $rtl = "\xE2\x80\x8F";
2605 $ltr = "\xE2\x80\x8E";
2606 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2607 return $this->isRTL() ?
$rtl : $ltr;
2613 function capitalizeAllNouns() {
2614 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2618 * An arrow, depending on the language direction
2622 function getArrow() {
2623 return $this->isRTL() ?
'←' : '→';
2627 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2631 function linkPrefixExtension() {
2632 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2638 function getMagicWords() {
2639 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2642 protected function doMagicHook() {
2643 if ( $this->mMagicHookDone
) {
2646 $this->mMagicHookDone
= true;
2647 wfProfileIn( 'LanguageGetMagic' );
2648 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2649 wfProfileOut( 'LanguageGetMagic' );
2653 * Fill a MagicWord object with data from here
2657 function getMagic( $mw ) {
2658 $this->doMagicHook();
2660 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2661 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2663 $magicWords = $this->getMagicWords();
2664 if ( isset( $magicWords[$mw->mId
] ) ) {
2665 $rawEntry = $magicWords[$mw->mId
];
2671 if ( !is_array( $rawEntry ) ) {
2672 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2674 $mw->mCaseSensitive
= $rawEntry[0];
2675 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2680 * Add magic words to the extension array
2682 * @param $newWords array
2684 function addMagicWordsByLang( $newWords ) {
2685 $fallbackChain = $this->getFallbackLanguages();
2686 $fallbackChain = array_reverse( $fallbackChain );
2687 foreach ( $fallbackChain as $code ) {
2688 if ( isset( $newWords[$code] ) ) {
2689 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2695 * Get special page names, as an associative array
2696 * case folded alias => real name
2698 function getSpecialPageAliases() {
2699 // Cache aliases because it may be slow to load them
2700 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2702 $this->mExtendedSpecialPageAliases
=
2703 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2704 wfRunHooks( 'LanguageGetSpecialPageAliases',
2705 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2708 return $this->mExtendedSpecialPageAliases
;
2712 * Italic is unsuitable for some languages
2714 * @param $text String: the text to be emphasized.
2717 function emphasize( $text ) {
2718 return "<em>$text</em>";
2722 * Normally we output all numbers in plain en_US style, that is
2723 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2724 * point twohundredthirtyfive. However this is not suitable for all
2725 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2726 * Icelandic just want to use commas instead of dots, and dots instead
2727 * of commas like "293.291,235".
2729 * An example of this function being called:
2731 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2734 * See LanguageGu.php for the Gujarati implementation and
2735 * $separatorTransformTable on MessageIs.php for
2736 * the , => . and . => , implementation.
2738 * @todo check if it's viable to use localeconv() for the decimal
2740 * @param $number Mixed: the string to be formatted, should be an integer
2741 * or a floating point number.
2742 * @param $nocommafy Bool: set to true for special numbers like dates
2745 public function formatNum( $number, $nocommafy = false ) {
2746 global $wgTranslateNumerals;
2747 if ( !$nocommafy ) {
2748 $number = $this->commafy( $number );
2749 $s = $this->separatorTransformTable();
2751 $number = strtr( $number, $s );
2755 if ( $wgTranslateNumerals ) {
2756 $s = $this->digitTransformTable();
2758 $number = strtr( $number, $s );
2766 * @param $number string
2769 function parseFormattedNumber( $number ) {
2770 $s = $this->digitTransformTable();
2772 $number = strtr( $number, array_flip( $s ) );
2775 $s = $this->separatorTransformTable();
2777 $number = strtr( $number, array_flip( $s ) );
2780 $number = strtr( $number, array( ',' => '' ) );
2785 * Adds commas to a given number
2790 function commafy( $_ ) {
2791 $digitGroupingPattern = $this->digitGroupingPattern();
2792 if ( $_ === null ) {
2796 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2797 // default grouping is at thousands, use the same for ###,###,### pattern too.
2798 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2800 // Ref: http://cldr.unicode.org/translation/number-patterns
2802 if ( intval( $_ ) < 0 ) {
2803 // For negative numbers apply the algorithm like positive number and add sign.
2805 $_ = substr( $_, 1 );
2807 $numberpart = array();
2808 $decimalpart = array();
2809 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2810 preg_match( "/\d+/", $_, $numberpart );
2811 preg_match( "/\.\d*/", $_, $decimalpart );
2812 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2813 if ( $groupedNumber === $_ ) {
2814 // the string does not have any number part. Eg: .12345
2815 return $sign . $groupedNumber;
2817 $start = $end = strlen( $numberpart[0] );
2818 while ( $start > 0 ) {
2819 $match = $matches[0][$numMatches -1] ;
2820 $matchLen = strlen( $match );
2821 $start = $end - $matchLen;
2825 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2827 if ( $numMatches > 1 ) {
2828 // use the last pattern for the rest of the number
2832 $groupedNumber = "," . $groupedNumber;
2835 return $sign . $groupedNumber;
2841 function digitGroupingPattern() {
2842 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2848 function digitTransformTable() {
2849 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2855 function separatorTransformTable() {
2856 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2860 * Take a list of strings and build a locale-friendly comma-separated
2861 * list, using the local comma-separator message.
2862 * The last two strings are chained with an "and".
2867 function listToText( array $l ) {
2869 $m = count( $l ) - 1;
2871 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2873 for ( $i = $m; $i >= 0; $i-- ) {
2876 } elseif ( $i == $m - 1 ) {
2877 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2879 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2887 * Take a list of strings and build a locale-friendly comma-separated
2888 * list, using the local comma-separator message.
2889 * @param $list array of strings to put in a comma list
2892 function commaList( array $list ) {
2896 array( 'parsemag', 'escapenoentities', 'language' => $this )
2903 * Take a list of strings and build a locale-friendly semicolon-separated
2904 * list, using the local semicolon-separator message.
2905 * @param $list array of strings to put in a semicolon list
2908 function semicolonList( array $list ) {
2911 'semicolon-separator',
2912 array( 'parsemag', 'escapenoentities', 'language' => $this )
2919 * Same as commaList, but separate it with the pipe instead.
2920 * @param $list array of strings to put in a pipe list
2923 function pipeList( array $list ) {
2927 array( 'escapenoentities', 'language' => $this )
2934 * Truncate a string to a specified length in bytes, appending an optional
2935 * string (e.g. for ellipses)
2937 * The database offers limited byte lengths for some columns in the database;
2938 * multi-byte character sets mean we need to ensure that only whole characters
2939 * are included, otherwise broken characters can be passed to the user
2941 * If $length is negative, the string will be truncated from the beginning
2943 * @param $string String to truncate
2944 * @param $length Int: maximum length (including ellipses)
2945 * @param $ellipsis String to append to the truncated text
2946 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2947 * $adjustLength was introduced in 1.18, before that behaved as if false.
2950 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2951 # Use the localized ellipsis character
2952 if ( $ellipsis == '...' ) {
2953 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2955 # Check if there is no need to truncate
2956 if ( $length == 0 ) {
2957 return $ellipsis; // convention
2958 } elseif ( strlen( $string ) <= abs( $length ) ) {
2959 return $string; // no need to truncate
2961 $stringOriginal = $string;
2962 # If ellipsis length is >= $length then we can't apply $adjustLength
2963 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2964 $string = $ellipsis; // this can be slightly unexpected
2965 # Otherwise, truncate and add ellipsis...
2967 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2968 if ( $length > 0 ) {
2969 $length -= $eLength;
2970 $string = substr( $string, 0, $length ); // xyz...
2971 $string = $this->removeBadCharLast( $string );
2972 $string = $string . $ellipsis;
2974 $length +
= $eLength;
2975 $string = substr( $string, $length ); // ...xyz
2976 $string = $this->removeBadCharFirst( $string );
2977 $string = $ellipsis . $string;
2980 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2981 # This check is *not* redundant if $adjustLength, due to the single case where
2982 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2983 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2986 return $stringOriginal;
2991 * Remove bytes that represent an incomplete Unicode character
2992 * at the end of string (e.g. bytes of the char are missing)
2994 * @param $string String
2997 protected function removeBadCharLast( $string ) {
2998 if ( $string != '' ) {
2999 $char = ord( $string[strlen( $string ) - 1] );
3001 if ( $char >= 0xc0 ) {
3002 # We got the first byte only of a multibyte char; remove it.
3003 $string = substr( $string, 0, -1 );
3004 } elseif ( $char >= 0x80 &&
3005 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3006 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3008 # We chopped in the middle of a character; remove it
3016 * Remove bytes that represent an incomplete Unicode character
3017 * at the start of string (e.g. bytes of the char are missing)
3019 * @param $string String
3022 protected function removeBadCharFirst( $string ) {
3023 if ( $string != '' ) {
3024 $char = ord( $string[0] );
3025 if ( $char >= 0x80 && $char < 0xc0 ) {
3026 # We chopped in the middle of a character; remove the whole thing
3027 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3034 * Truncate a string of valid HTML to a specified length in bytes,
3035 * appending an optional string (e.g. for ellipses), and return valid HTML
3037 * This is only intended for styled/linked text, such as HTML with
3038 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3039 * Also, this will not detect things like "display:none" CSS.
3041 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3043 * @param string $text HTML string to truncate
3044 * @param int $length (zero/positive) Maximum length (including ellipses)
3045 * @param string $ellipsis String to append to the truncated text
3048 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3049 # Use the localized ellipsis character
3050 if ( $ellipsis == '...' ) {
3051 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3053 # Check if there is clearly no need to truncate
3054 if ( $length <= 0 ) {
3055 return $ellipsis; // no text shown, nothing to format (convention)
3056 } elseif ( strlen( $text ) <= $length ) {
3057 return $text; // string short enough even *with* HTML (short-circuit)
3060 $dispLen = 0; // innerHTML legth so far
3061 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3062 $tagType = 0; // 0-open, 1-close
3063 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3064 $entityState = 0; // 0-not entity, 1-entity
3065 $tag = $ret = ''; // accumulated tag name, accumulated result string
3066 $openTags = array(); // open tag stack
3067 $maybeState = null; // possible truncation state
3069 $textLen = strlen( $text );
3070 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3071 for ( $pos = 0; true; ++
$pos ) {
3072 # Consider truncation once the display length has reached the maximim.
3073 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3074 # Check that we're not in the middle of a bracket/entity...
3075 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3076 if ( !$testingEllipsis ) {
3077 $testingEllipsis = true;
3078 # Save where we are; we will truncate here unless there turn out to
3079 # be so few remaining characters that truncation is not necessary.
3080 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3081 $maybeState = array( $ret, $openTags ); // save state
3083 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3084 # String in fact does need truncation, the truncation point was OK.
3085 list( $ret, $openTags ) = $maybeState; // reload state
3086 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3087 $ret .= $ellipsis; // add ellipsis
3091 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3093 # Read the next char...
3095 $lastCh = $pos ?
$text[$pos - 1] : '';
3096 $ret .= $ch; // add to result string
3098 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3099 $entityState = 0; // for bad HTML
3100 $bracketState = 1; // tag started (checking for backslash)
3101 } elseif ( $ch == '>' ) {
3102 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3103 $entityState = 0; // for bad HTML
3104 $bracketState = 0; // out of brackets
3105 } elseif ( $bracketState == 1 ) {
3107 $tagType = 1; // close tag (e.g. "</span>")
3109 $tagType = 0; // open tag (e.g. "<span>")
3112 $bracketState = 2; // building tag name
3113 } elseif ( $bracketState == 2 ) {
3117 // Name found (e.g. "<a href=..."), add on tag attributes...
3118 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3120 } elseif ( $bracketState == 0 ) {
3121 if ( $entityState ) {
3124 $dispLen++
; // entity is one displayed char
3127 if ( $neLength == 0 && !$maybeState ) {
3128 // Save state without $ch. We want to *hit* the first
3129 // display char (to get tags) but not *use* it if truncating.
3130 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3133 $entityState = 1; // entity found, (e.g. " ")
3135 $dispLen++
; // this char is displayed
3136 // Add the next $max display text chars after this in one swoop...
3137 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3138 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3139 $dispLen +
= $skipped;
3145 // Close the last tag if left unclosed by bad HTML
3146 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3147 while ( count( $openTags ) > 0 ) {
3148 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3154 * truncateHtml() helper function
3155 * like strcspn() but adds the skipped chars to $ret
3164 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3165 if ( $len === null ) {
3166 $len = -1; // -1 means "no limit" for strcspn
3167 } elseif ( $len < 0 ) {
3171 if ( $start < strlen( $text ) ) {
3172 $skipCount = strcspn( $text, $search, $start, $len );
3173 $ret .= substr( $text, $start, $skipCount );
3179 * truncateHtml() helper function
3180 * (a) push or pop $tag from $openTags as needed
3181 * (b) clear $tag value
3182 * @param &$tag string Current HTML tag name we are looking at
3183 * @param $tagType int (0-open tag, 1-close tag)
3184 * @param $lastCh string Character before the '>' that ended this tag
3185 * @param &$openTags array Open tag stack (not accounting for $tag)
3187 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3188 $tag = ltrim( $tag );
3190 if ( $tagType == 0 && $lastCh != '/' ) {
3191 $openTags[] = $tag; // tag opened (didn't close itself)
3192 } elseif ( $tagType == 1 ) {
3193 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3194 array_pop( $openTags ); // tag closed
3202 * Grammatical transformations, needed for inflected languages
3203 * Invoked by putting {{grammar:case|word}} in a message
3205 * @param $word string
3206 * @param $case string
3209 function convertGrammar( $word, $case ) {
3210 global $wgGrammarForms;
3211 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3212 return $wgGrammarForms[$this->getCode()][$case][$word];
3218 * Provides an alternative text depending on specified gender.
3219 * Usage {{gender:username|masculine|feminine|neutral}}.
3220 * username is optional, in which case the gender of current user is used,
3221 * but only in (some) interface messages; otherwise default gender is used.
3223 * If no forms are given, an empty string is returned. If only one form is
3224 * given, it will be returned unconditionally. These details are implied by
3225 * the caller and cannot be overridden in subclasses.
3227 * If more than one form is given, the default is to use the neutral one
3228 * if it is specified, and to use the masculine one otherwise. These
3229 * details can be overridden in subclasses.
3231 * @param $gender string
3232 * @param $forms array
3236 function gender( $gender, $forms ) {
3237 if ( !count( $forms ) ) {
3240 $forms = $this->preConvertPlural( $forms, 2 );
3241 if ( $gender === 'male' ) {
3244 if ( $gender === 'female' ) {
3247 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3251 * Plural form transformations, needed for some languages.
3252 * For example, there are 3 form of plural in Russian and Polish,
3253 * depending on "count mod 10". See [[w:Plural]]
3254 * For English it is pretty simple.
3256 * Invoked by putting {{plural:count|wordform1|wordform2}}
3257 * or {{plural:count|wordform1|wordform2|wordform3}}
3259 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3261 * @param $count Integer: non-localized number
3262 * @param $forms Array: different plural forms
3263 * @return string Correct form of plural for $count in this language
3265 function convertPlural( $count, $forms ) {
3266 if ( !count( $forms ) ) {
3269 $forms = $this->preConvertPlural( $forms, 2 );
3271 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3275 * Checks that convertPlural was given an array and pads it to requested
3276 * amount of forms by copying the last one.
3278 * @param $count Integer: How many forms should there be at least
3279 * @param $forms Array of forms given to convertPlural
3280 * @return array Padded array of forms or an exception if not an array
3282 protected function preConvertPlural( /* Array */ $forms, $count ) {
3283 while ( count( $forms ) < $count ) {
3284 $forms[] = $forms[count( $forms ) - 1];
3290 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3291 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3292 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3293 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3296 * @param $str String: the validated block duration in English
3297 * @return string Somehow translated block duration
3298 * @see LanguageFi.php for example implementation
3300 function translateBlockExpiry( $str ) {
3301 $duration = SpecialBlock
::getSuggestedDurations( $this );
3302 foreach ( $duration as $show => $value ) {
3303 if ( strcmp( $str, $value ) == 0 ) {
3304 return htmlspecialchars( trim( $show ) );
3308 // Since usually only infinite or indefinite is only on list, so try
3309 // equivalents if still here.
3310 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3311 if ( in_array( $str, $indefs ) ) {
3312 foreach ( $indefs as $val ) {
3313 $show = array_search( $val, $duration, true );
3314 if ( $show !== false ) {
3315 return htmlspecialchars( trim( $show ) );
3319 // If all else fails, return the original string.
3324 * languages like Chinese need to be segmented in order for the diff
3327 * @param $text String
3330 public function segmentForDiff( $text ) {
3335 * and unsegment to show the result
3337 * @param $text String
3340 public function unsegmentForDiff( $text ) {
3345 * Return the LanguageConverter used in the Language
3348 * @return LanguageConverter
3350 public function getConverter() {
3351 return $this->mConverter
;
3355 * convert text to all supported variants
3357 * @param $text string
3360 public function autoConvertToAllVariants( $text ) {
3361 return $this->mConverter
->autoConvertToAllVariants( $text );
3365 * convert text to different variants of a language.
3367 * @param $text string
3370 public function convert( $text ) {
3371 return $this->mConverter
->convert( $text );
3375 * Convert a Title object to a string in the preferred variant
3377 * @param $title Title
3380 public function convertTitle( $title ) {
3381 return $this->mConverter
->convertTitle( $title );
3385 * Check if this is a language with variants
3389 public function hasVariants() {
3390 return sizeof( $this->getVariants() ) > 1;
3394 * Check if the language has the specific variant
3397 * @param $variant string
3400 public function hasVariant( $variant ) {
3401 return (bool)$this->mConverter
->validateVariant( $variant );
3405 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3407 * @param $text string
3410 public function armourMath( $text ) {
3411 return $this->mConverter
->armourMath( $text );
3415 * Perform output conversion on a string, and encode for safe HTML output.
3416 * @param $text String text to be converted
3417 * @param $isTitle Bool whether this conversion is for the article title
3419 * @todo this should get integrated somewhere sane
3421 public function convertHtml( $text, $isTitle = false ) {
3422 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3426 * @param $key string
3429 public function convertCategoryKey( $key ) {
3430 return $this->mConverter
->convertCategoryKey( $key );
3434 * Get the list of variants supported by this language
3435 * see sample implementation in LanguageZh.php
3437 * @return array an array of language codes
3439 public function getVariants() {
3440 return $this->mConverter
->getVariants();
3446 public function getPreferredVariant() {
3447 return $this->mConverter
->getPreferredVariant();
3453 public function getDefaultVariant() {
3454 return $this->mConverter
->getDefaultVariant();
3460 public function getURLVariant() {
3461 return $this->mConverter
->getURLVariant();
3465 * If a language supports multiple variants, it is
3466 * possible that non-existing link in one variant
3467 * actually exists in another variant. this function
3468 * tries to find it. See e.g. LanguageZh.php
3470 * @param $link String: the name of the link
3471 * @param $nt Mixed: the title object of the link
3472 * @param $ignoreOtherCond Boolean: to disable other conditions when
3473 * we need to transclude a template or update a category's link
3474 * @return null the input parameters may be modified upon return
3476 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3477 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3481 * If a language supports multiple variants, converts text
3482 * into an array of all possible variants of the text:
3483 * 'variant' => text in that variant
3485 * @deprecated since 1.17 Use autoConvertToAllVariants()
3487 * @param $text string
3491 public function convertLinkToAllVariants( $text ) {
3492 return $this->mConverter
->convertLinkToAllVariants( $text );
3496 * returns language specific options used by User::getPageRenderHash()
3497 * for example, the preferred language variant
3501 function getExtraHashOptions() {
3502 return $this->mConverter
->getExtraHashOptions();
3506 * For languages that support multiple variants, the title of an
3507 * article may be displayed differently in different variants. this
3508 * function returns the apporiate title defined in the body of the article.
3512 public function getParsedTitle() {
3513 return $this->mConverter
->getParsedTitle();
3517 * Enclose a string with the "no conversion" tag. This is used by
3518 * various functions in the Parser
3520 * @param $text String: text to be tagged for no conversion
3521 * @param $noParse bool
3522 * @return string the tagged text
3524 public function markNoConversion( $text, $noParse = false ) {
3525 return $this->mConverter
->markNoConversion( $text, $noParse );
3529 * A regular expression to match legal word-trailing characters
3530 * which should be merged onto a link of the form [[foo]]bar.
3534 public function linkTrail() {
3535 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3541 function getLangObj() {
3546 * Get the RFC 3066 code for this language object
3550 public function getCode() {
3551 return $this->mCode
;
3555 * Get the code in Bcp47 format which we can use
3556 * inside of html lang="" tags.
3560 public function getHtmlCode() {
3561 if ( is_null( $this->mHtmlCode
) ) {
3562 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3564 return $this->mHtmlCode
;
3568 * @param $code string
3570 public function setCode( $code ) {
3571 $this->mCode
= $code;
3572 // Ensure we don't leave an incorrect html code lying around
3573 $this->mHtmlCode
= null;
3577 * Get the name of a file for a certain language code
3578 * @param $prefix string Prepend this to the filename
3579 * @param $code string Language code
3580 * @param $suffix string Append this to the filename
3581 * @throws MWException
3582 * @return string $prefix . $mangledCode . $suffix
3584 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3585 // Protect against path traversal
3586 if ( !Language
::isValidCode( $code )
3587 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3589 throw new MWException( "Invalid language code \"$code\"" );
3592 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3596 * Get the language code from a file name. Inverse of getFileName()
3597 * @param $filename string $prefix . $languageCode . $suffix
3598 * @param $prefix string Prefix before the language code
3599 * @param $suffix string Suffix after the language code
3600 * @return string Language code, or false if $prefix or $suffix isn't found
3602 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3604 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3605 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3606 if ( !count( $m ) ) {
3609 return str_replace( '_', '-', strtolower( $m[1] ) );
3613 * @param $code string
3616 public static function getMessagesFileName( $code ) {
3618 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3619 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3624 * @param $code string
3627 public static function getClassFileName( $code ) {
3629 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3633 * Get the first fallback for a given language.
3635 * @param $code string
3637 * @return bool|string
3639 public static function getFallbackFor( $code ) {
3640 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3643 $fallbacks = self
::getFallbacksFor( $code );
3644 $first = array_shift( $fallbacks );
3650 * Get the ordered list of fallback languages.
3653 * @param $code string Language code
3656 public static function getFallbacksFor( $code ) {
3657 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3660 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3661 $v = array_map( 'trim', explode( ',', $v ) );
3662 if ( $v[count( $v ) - 1] !== 'en' ) {
3670 * Get all messages for a given language
3671 * WARNING: this may take a long time. If you just need all message *keys*
3672 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3674 * @param $code string
3678 public static function getMessagesFor( $code ) {
3679 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3683 * Get a message for a given language
3685 * @param $key string
3686 * @param $code string
3690 public static function getMessageFor( $key, $code ) {
3691 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3695 * Get all message keys for a given language. This is a faster alternative to
3696 * array_keys( Language::getMessagesFor( $code ) )
3699 * @param $code string Language code
3700 * @return array of message keys (strings)
3702 public static function getMessageKeysFor( $code ) {
3703 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3710 function fixVariableInNamespace( $talk ) {
3711 if ( strpos( $talk, '$1' ) === false ) {
3715 global $wgMetaNamespace;
3716 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3718 # Allow grammar transformations
3719 # Allowing full message-style parsing would make simple requests
3720 # such as action=raw much more expensive than they need to be.
3721 # This will hopefully cover most cases.
3722 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3723 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3724 return str_replace( ' ', '_', $talk );
3731 function replaceGrammarInNamespace( $m ) {
3732 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3736 * @throws MWException
3739 static function getCaseMaps() {
3740 static $wikiUpperChars, $wikiLowerChars;
3741 if ( isset( $wikiUpperChars ) ) {
3742 return array( $wikiUpperChars, $wikiLowerChars );
3745 wfProfileIn( __METHOD__
);
3746 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3747 if ( $arr === false ) {
3748 throw new MWException(
3749 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3751 $wikiUpperChars = $arr['wikiUpperChars'];
3752 $wikiLowerChars = $arr['wikiLowerChars'];
3753 wfProfileOut( __METHOD__
);
3754 return array( $wikiUpperChars, $wikiLowerChars );
3758 * Decode an expiry (block, protection, etc) which has come from the DB
3760 * @FIXME: why are we returnings DBMS-dependent strings???
3762 * @param $expiry String: Database expiry String
3763 * @param $format Bool|Int true to process using language functions, or TS_ constant
3764 * to return the expiry in a given timestamp
3767 public function formatExpiry( $expiry, $format = true ) {
3768 static $infinity, $infinityMsg;
3769 if ( $infinity === null ) {
3770 $infinityMsg = wfMessage( 'infiniteblock' );
3771 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3774 if ( $expiry == '' ||
$expiry == $infinity ) {
3775 return $format === true
3779 return $format === true
3780 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3781 : wfTimestamp( $format, $expiry );
3787 * @param $seconds int|float
3788 * @param $format Array Optional
3789 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3790 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3791 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3792 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3795 function formatTimePeriod( $seconds, $format = array() ) {
3796 if ( !is_array( $format ) ) {
3797 $format = array( 'avoid' => $format ); // For backwards compatibility
3799 if ( !isset( $format['avoid'] ) ) {
3800 $format['avoid'] = false;
3802 if ( !isset( $format['noabbrevs' ] ) ) {
3803 $format['noabbrevs'] = false;
3805 $secondsMsg = wfMessage(
3806 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3807 $minutesMsg = wfMessage(
3808 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3809 $hoursMsg = wfMessage(
3810 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3811 $daysMsg = wfMessage(
3812 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3814 if ( round( $seconds * 10 ) < 100 ) {
3815 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3816 $s = $secondsMsg->params( $s )->text();
3817 } elseif ( round( $seconds ) < 60 ) {
3818 $s = $this->formatNum( round( $seconds ) );
3819 $s = $secondsMsg->params( $s )->text();
3820 } elseif ( round( $seconds ) < 3600 ) {
3821 $minutes = floor( $seconds / 60 );
3822 $secondsPart = round( fmod( $seconds, 60 ) );
3823 if ( $secondsPart == 60 ) {
3827 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3829 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3830 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3831 $hours = floor( $seconds / 3600 );
3832 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3833 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3834 if ( $secondsPart == 60 ) {
3838 if ( $minutes == 60 ) {
3842 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3844 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3845 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3846 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3849 $days = floor( $seconds / 86400 );
3850 if ( $format['avoid'] === 'avoidminutes' ) {
3851 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3852 if ( $hours == 24 ) {
3856 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3858 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3859 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3860 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3861 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3862 if ( $minutes == 60 ) {
3866 if ( $hours == 24 ) {
3870 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3872 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3874 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3876 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3878 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3885 * Format a bitrate for output, using an appropriate
3886 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3888 * This use base 1000. For base 1024 use formatSize(), for another base
3889 * see formatComputingNumbers()
3894 function formatBitrate( $bps ) {
3895 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3899 * @param $size int Size of the unit
3900 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3901 * @param $messageKey string Message key to be uesd
3904 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3906 return str_replace( '$1', $this->formatNum( $size ),
3907 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3910 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3913 $maxIndex = count( $sizes ) - 1;
3914 while ( $size >= $boundary && $index < $maxIndex ) {
3919 // For small sizes no decimal places necessary
3922 // For MB and bigger two decimal places are smarter
3925 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3927 $size = round( $size, $round );
3928 $text = $this->getMessageFromDB( $msg );
3929 return str_replace( '$1', $this->formatNum( $size ), $text );
3933 * Format a size in bytes for output, using an appropriate
3934 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3936 * This method use base 1024. For base 1000 use formatBitrate(), for
3937 * another base see formatComputingNumbers()
3939 * @param $size int Size to format
3940 * @return string Plain text (not HTML)
3942 function formatSize( $size ) {
3943 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3947 * Make a list item, used by various special pages
3949 * @param $page String Page link
3950 * @param $details String Text between brackets
3951 * @param $oppositedm Boolean Add the direction mark opposite to your
3952 * language, to display text properly
3955 function specialList( $page, $details, $oppositedm = true ) {
3956 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3957 $this->getDirMark();
3958 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3959 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3960 return $page . $details;
3964 * Generate (prev x| next x) (20|50|100...) type links for paging
3966 * @param $title Title object to link
3967 * @param $offset Integer offset parameter
3968 * @param $limit Integer limit parameter
3969 * @param $query String optional URL query parameter string
3970 * @param $atend Bool optional param for specified if this is the last page
3973 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3974 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3976 # Make 'previous' link
3977 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3978 if ( $offset > 0 ) {
3979 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3980 $query, $prev, 'prevn-title', 'mw-prevlink' );
3982 $plink = htmlspecialchars( $prev );
3986 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3988 $nlink = htmlspecialchars( $next );
3990 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3991 $query, $next, 'prevn-title', 'mw-nextlink' );
3994 # Make links to set number of items per page
3995 $numLinks = array();
3996 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
3997 $numLinks[] = $this->numLink( $title, $offset, $num,
3998 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4001 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4002 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4006 * Helper function for viewPrevNext() that generates links
4008 * @param $title Title object to link
4009 * @param $offset Integer offset parameter
4010 * @param $limit Integer limit parameter
4011 * @param $query Array extra query parameters
4012 * @param $link String text to use for the link; will be escaped
4013 * @param $tooltipMsg String name of the message to use as tooltip
4014 * @param $class String value of the "class" attribute of the link
4015 * @return String HTML fragment
4017 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4018 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4019 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4020 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4021 'title' => $tooltip, 'class' => $class ), $link );
4025 * Get the conversion rule title, if any.
4029 public function getConvRuleTitle() {
4030 return $this->mConverter
->getConvRuleTitle();