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
693 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
694 global $wgExtraLanguageNames;
695 static $coreLanguageNames;
697 if ( $coreLanguageNames === null ) {
698 include( MWInit
::compiledPath( 'languages/Names.php' ) );
704 # TODO: also include when $inLanguage is null, when this code is more efficient
705 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
708 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
709 foreach ( $mwNames as $mwCode => $mwName ) {
710 # - Prefer own MediaWiki native name when not using the hook
711 # TODO: prefer it always to make it consistent, but casing is different in CLDR
712 # - For other names just add if not added through the hook
713 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
714 $names[$mwCode] = $mwName;
718 if ( $include === 'all' ) {
723 $coreCodes = array_keys( $mwNames );
724 foreach( $coreCodes as $coreCode ) {
725 $returnMw[$coreCode] = $names[$coreCode];
728 if( $include === 'mw' ) {
730 } elseif( $include === 'mwfile' ) {
731 $namesMwFile = array();
732 # We do this using a foreach over the codes instead of a directory
733 # loop so that messages files in extensions will work correctly.
734 foreach ( $returnMw as $code => $value ) {
735 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
736 $namesMwFile[$code] = $names[$code];
745 * @param $code string: The code of the language for which to get the name
746 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
747 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
748 * @return string: Language name or empty
751 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
752 $array = self
::fetchLanguageNames( $inLanguage, $include );
753 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
757 * Get a message from the MediaWiki namespace.
759 * @param $msg String: message name
762 function getMessageFromDB( $msg ) {
763 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
767 * Get the native language name of $code.
768 * Only if defined in MediaWiki, no other data like CLDR.
769 * @param $code string
771 * @deprecated in 1.20, use fetchLanguageName()
773 function getLanguageName( $code ) {
774 return self
::fetchLanguageName( $code );
781 function getMonthName( $key ) {
782 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
788 function getMonthNamesArray() {
789 $monthNames = array( '' );
790 for ( $i = 1; $i < 13; $i++
) {
791 $monthNames[] = $this->getMonthName( $i );
800 function getMonthNameGen( $key ) {
801 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
808 function getMonthAbbreviation( $key ) {
809 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
815 function getMonthAbbreviationsArray() {
816 $monthNames = array( '' );
817 for ( $i = 1; $i < 13; $i++
) {
818 $monthNames[] = $this->getMonthAbbreviation( $i );
827 function getWeekdayName( $key ) {
828 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
835 function getWeekdayAbbreviation( $key ) {
836 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
843 function getIranianCalendarMonthName( $key ) {
844 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
851 function getHebrewCalendarMonthName( $key ) {
852 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
859 function getHebrewCalendarMonthNameGen( $key ) {
860 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
867 function getHijriCalendarMonthName( $key ) {
868 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
872 * This is a workalike of PHP's date() function, but with better
873 * internationalisation, a reduced set of format characters, and a better
876 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
877 * PHP manual for definitions. There are a number of extensions, which
880 * xn Do not translate digits of the next numeric format character
881 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
882 * xr Use roman numerals for the next numeric format character
883 * xh Use hebrew numerals for the next numeric format character
885 * xg Genitive month name
887 * xij j (day number) in Iranian calendar
888 * xiF F (month name) in Iranian calendar
889 * xin n (month number) in Iranian calendar
890 * xiy y (two digit year) in Iranian calendar
891 * xiY Y (full year) in Iranian calendar
893 * xjj j (day number) in Hebrew calendar
894 * xjF F (month name) in Hebrew calendar
895 * xjt t (days in month) in Hebrew calendar
896 * xjx xg (genitive month name) in Hebrew calendar
897 * xjn n (month number) in Hebrew calendar
898 * xjY Y (full year) in Hebrew calendar
900 * xmj j (day number) in Hijri calendar
901 * xmF F (month name) in Hijri calendar
902 * xmn n (month number) in Hijri calendar
903 * xmY Y (full year) in Hijri calendar
905 * xkY Y (full year) in Thai solar calendar. Months and days are
906 * identical to the Gregorian calendar
907 * xoY Y (full year) in Minguo calendar or Juche year.
908 * Months and days are identical to the
910 * xtY Y (full year) in Japanese nengo. Months and days are
911 * identical to the Gregorian calendar
913 * Characters enclosed in double quotes will be considered literal (with
914 * the quotes themselves removed). Unmatched quotes will be considered
915 * literal quotes. Example:
917 * "The month is" F => The month is January
920 * Backslash escaping is also supported.
922 * Input timestamp is assumed to be pre-normalized to the desired local
925 * @param $format String
926 * @param $ts String: 14-character timestamp
929 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
933 function sprintfDate( $format, $ts ) {
946 for ( $p = 0; $p < strlen( $format ); $p++
) {
949 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
950 $code .= $format[++
$p];
953 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
954 $code .= $format[++
$p];
965 $rawToggle = !$rawToggle;
974 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
977 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
978 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
981 $num = substr( $ts, 6, 2 );
984 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
985 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
988 $num = intval( substr( $ts, 6, 2 ) );
992 $iranian = self
::tsToIranian( $ts );
998 $hijri = self
::tsToHijri( $ts );
1004 $hebrew = self
::tsToHebrew( $ts );
1010 $unix = wfTimestamp( TS_UNIX
, $ts );
1012 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1016 $unix = wfTimestamp( TS_UNIX
, $ts );
1018 $w = gmdate( 'w', $unix );
1023 $unix = wfTimestamp( TS_UNIX
, $ts );
1025 $num = gmdate( 'w', $unix );
1029 $unix = wfTimestamp( TS_UNIX
, $ts );
1031 $num = gmdate( 'z', $unix );
1035 $unix = wfTimestamp( TS_UNIX
, $ts );
1037 $num = gmdate( 'W', $unix );
1040 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1044 $iranian = self
::tsToIranian( $ts );
1046 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1050 $hijri = self
::tsToHijri( $ts );
1052 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1056 $hebrew = self
::tsToHebrew( $ts );
1058 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1061 $num = substr( $ts, 4, 2 );
1064 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1067 $num = intval( substr( $ts, 4, 2 ) );
1071 $iranian = self
::tsToIranian( $ts );
1077 $hijri = self
::tsToHijri ( $ts );
1083 $hebrew = self
::tsToHebrew( $ts );
1089 $unix = wfTimestamp( TS_UNIX
, $ts );
1091 $num = gmdate( 't', $unix );
1095 $hebrew = self
::tsToHebrew( $ts );
1101 $unix = wfTimestamp( TS_UNIX
, $ts );
1103 $num = gmdate( 'L', $unix );
1107 $unix = wfTimestamp( TS_UNIX
, $ts );
1109 $num = gmdate( 'o', $unix );
1112 $num = substr( $ts, 0, 4 );
1116 $iranian = self
::tsToIranian( $ts );
1122 $hijri = self
::tsToHijri( $ts );
1128 $hebrew = self
::tsToHebrew( $ts );
1134 $thai = self
::tsToYear( $ts, 'thai' );
1140 $minguo = self
::tsToYear( $ts, 'minguo' );
1146 $tenno = self
::tsToYear( $ts, 'tenno' );
1151 $num = substr( $ts, 2, 2 );
1155 $iranian = self
::tsToIranian( $ts );
1157 $num = substr( $iranian[0], -2 );
1160 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1163 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1166 $h = substr( $ts, 8, 2 );
1167 $num = $h %
12 ?
$h %
12 : 12;
1170 $num = intval( substr( $ts, 8, 2 ) );
1173 $h = substr( $ts, 8, 2 );
1174 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1177 $num = substr( $ts, 8, 2 );
1180 $num = substr( $ts, 10, 2 );
1183 $num = substr( $ts, 12, 2 );
1187 $unix = wfTimestamp( TS_UNIX
, $ts );
1189 $s .= gmdate( 'c', $unix );
1193 $unix = wfTimestamp( TS_UNIX
, $ts );
1195 $s .= gmdate( 'r', $unix );
1199 $unix = wfTimestamp( TS_UNIX
, $ts );
1204 # Backslash escaping
1205 if ( $p < strlen( $format ) - 1 ) {
1206 $s .= $format[++
$p];
1213 if ( $p < strlen( $format ) - 1 ) {
1214 $endQuote = strpos( $format, '"', $p +
1 );
1215 if ( $endQuote === false ) {
1216 # No terminating quote, assume literal "
1219 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1223 # Quote at end of string, assume literal "
1230 if ( $num !== false ) {
1231 if ( $rawToggle ||
$raw ) {
1234 } elseif ( $roman ) {
1235 $s .= self
::romanNumeral( $num );
1237 } elseif ( $hebrewNum ) {
1238 $s .= self
::hebrewNumeral( $num );
1241 $s .= $this->formatNum( $num, true );
1248 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1249 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1252 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1253 * Gregorian dates to Iranian dates. Originally written in C, it
1254 * is released under the terms of GNU Lesser General Public
1255 * License. Conversion to PHP was performed by Niklas Laxström.
1257 * Link: http://www.farsiweb.info/jalali/jalali.c
1263 private static function tsToIranian( $ts ) {
1264 $gy = substr( $ts, 0, 4 ) -1600;
1265 $gm = substr( $ts, 4, 2 ) -1;
1266 $gd = substr( $ts, 6, 2 ) -1;
1268 # Days passed from the beginning (including leap years)
1270 +
floor( ( $gy +
3 ) / 4 )
1271 - floor( ( $gy +
99 ) / 100 )
1272 +
floor( ( $gy +
399 ) / 400 );
1274 // Add days of the past months of this year
1275 for ( $i = 0; $i < $gm; $i++
) {
1276 $gDayNo +
= self
::$GREG_DAYS[$i];
1280 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1284 // Days passed in current month
1285 $gDayNo +
= (int)$gd;
1287 $jDayNo = $gDayNo - 79;
1289 $jNp = floor( $jDayNo / 12053 );
1292 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1295 if ( $jDayNo >= 366 ) {
1296 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1297 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1300 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1301 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1307 return array( $jy, $jm, $jd );
1311 * Converting Gregorian dates to Hijri dates.
1313 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1315 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1321 private static function tsToHijri( $ts ) {
1322 $year = substr( $ts, 0, 4 );
1323 $month = substr( $ts, 4, 2 );
1324 $day = substr( $ts, 6, 2 );
1332 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1333 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1336 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1337 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1338 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1341 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1342 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1345 $zl = $zjd -1948440 +
10632;
1346 $zn = (int)( ( $zl - 1 ) / 10631 );
1347 $zl = $zl - 10631 * $zn +
354;
1348 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1349 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1350 $zm = (int)( ( 24 * $zl ) / 709 );
1351 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1352 $zy = 30 * $zn +
$zj - 30;
1354 return array( $zy, $zm, $zd );
1358 * Converting Gregorian dates to Hebrew dates.
1360 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1361 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1362 * to translate the relevant functions into PHP and release them under
1365 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1366 * and Adar II is 14. In a non-leap year, Adar is 6.
1372 private static function tsToHebrew( $ts ) {
1374 $year = substr( $ts, 0, 4 );
1375 $month = substr( $ts, 4, 2 );
1376 $day = substr( $ts, 6, 2 );
1378 # Calculate Hebrew year
1379 $hebrewYear = $year +
3760;
1381 # Month number when September = 1, August = 12
1383 if ( $month > 12 ) {
1390 # Calculate day of year from 1 September
1392 for ( $i = 1; $i < $month; $i++
) {
1396 # Check if the year is leap
1397 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1400 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1407 # Calculate the start of the Hebrew year
1408 $start = self
::hebrewYearStart( $hebrewYear );
1410 # Calculate next year's start
1411 if ( $dayOfYear <= $start ) {
1412 # Day is before the start of the year - it is the previous year
1414 $nextStart = $start;
1418 # Add days since previous year's 1 September
1420 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1424 # Start of the new (previous) year
1425 $start = self
::hebrewYearStart( $hebrewYear );
1428 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1431 # Calculate Hebrew day of year
1432 $hebrewDayOfYear = $dayOfYear - $start;
1434 # Difference between year's days
1435 $diff = $nextStart - $start;
1436 # Add 12 (or 13 for leap years) days to ignore the difference between
1437 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1438 # difference is only about the year type
1439 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1445 # Check the year pattern, and is leap year
1446 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1447 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1448 # and non-leap years
1449 $yearPattern = $diff %
30;
1450 # Check if leap year
1451 $isLeap = $diff >= 30;
1453 # Calculate day in the month from number of day in the Hebrew year
1454 # Don't check Adar - if the day is not in Adar, we will stop before;
1455 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1456 $hebrewDay = $hebrewDayOfYear;
1459 while ( $hebrewMonth <= 12 ) {
1460 # Calculate days in this month
1461 if ( $isLeap && $hebrewMonth == 6 ) {
1462 # Adar in a leap year
1464 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1466 if ( $hebrewDay <= $days ) {
1470 # Subtract the days of Adar I
1471 $hebrewDay -= $days;
1474 if ( $hebrewDay <= $days ) {
1480 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1481 # Cheshvan in a complete year (otherwise as the rule below)
1483 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1484 # Kislev in an incomplete year (otherwise as the rule below)
1487 # Odd months have 30 days, even have 29
1488 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1490 if ( $hebrewDay <= $days ) {
1491 # In the current month
1494 # Subtract the days of the current month
1495 $hebrewDay -= $days;
1496 # Try in the next month
1501 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1505 * This calculates the Hebrew year start, as days since 1 September.
1506 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1507 * Used for Hebrew date.
1513 private static function hebrewYearStart( $year ) {
1514 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1515 $b = intval( ( $year - 1 ) %
4 );
1516 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1520 $Mar = intval( $m );
1526 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1527 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1529 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1531 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1535 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1540 * Algorithm to convert Gregorian dates to Thai solar dates,
1541 * Minguo dates or Minguo dates.
1543 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1544 * http://en.wikipedia.org/wiki/Minguo_calendar
1545 * http://en.wikipedia.org/wiki/Japanese_era_name
1547 * @param $ts String: 14-character timestamp
1548 * @param $cName String: calender name
1549 * @return Array: converted year, month, day
1551 private static function tsToYear( $ts, $cName ) {
1552 $gy = substr( $ts, 0, 4 );
1553 $gm = substr( $ts, 4, 2 );
1554 $gd = substr( $ts, 6, 2 );
1556 if ( !strcmp( $cName, 'thai' ) ) {
1558 # Add 543 years to the Gregorian calendar
1559 # Months and days are identical
1560 $gy_offset = $gy +
543;
1561 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1563 # Deduct 1911 years from the Gregorian calendar
1564 # Months and days are identical
1565 $gy_offset = $gy - 1911;
1566 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1567 # Nengō dates up to Meiji period
1568 # Deduct years from the Gregorian calendar
1569 # depending on the nengo periods
1570 # Months and days are identical
1571 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1573 $gy_gannen = $gy - 1868 +
1;
1574 $gy_offset = $gy_gannen;
1575 if ( $gy_gannen == 1 ) {
1578 $gy_offset = '明治' . $gy_offset;
1580 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1581 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1582 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1583 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1584 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1588 $gy_gannen = $gy - 1912 +
1;
1589 $gy_offset = $gy_gannen;
1590 if ( $gy_gannen == 1 ) {
1593 $gy_offset = '大正' . $gy_offset;
1595 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1596 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1597 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1601 $gy_gannen = $gy - 1926 +
1;
1602 $gy_offset = $gy_gannen;
1603 if ( $gy_gannen == 1 ) {
1606 $gy_offset = '昭和' . $gy_offset;
1609 $gy_gannen = $gy - 1989 +
1;
1610 $gy_offset = $gy_gannen;
1611 if ( $gy_gannen == 1 ) {
1614 $gy_offset = '平成' . $gy_offset;
1620 return array( $gy_offset, $gm, $gd );
1624 * Roman number formatting up to 3000
1630 static function romanNumeral( $num ) {
1631 static $table = array(
1632 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1633 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1634 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1635 array( '', 'M', 'MM', 'MMM' )
1638 $num = intval( $num );
1639 if ( $num > 3000 ||
$num <= 0 ) {
1644 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1645 if ( $num >= $pow10 ) {
1646 $s .= $table[$i][(int)floor( $num / $pow10 )];
1648 $num = $num %
$pow10;
1654 * Hebrew Gematria number formatting up to 9999
1660 static function hebrewNumeral( $num ) {
1661 static $table = array(
1662 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1663 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1664 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1665 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1668 $num = intval( $num );
1669 if ( $num > 9999 ||
$num <= 0 ) {
1674 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1675 if ( $num >= $pow10 ) {
1676 if ( $num == 15 ||
$num == 16 ) {
1677 $s .= $table[0][9] . $table[0][$num - 9];
1680 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1681 if ( $pow10 == 1000 ) {
1686 $num = $num %
$pow10;
1688 if ( strlen( $s ) == 2 ) {
1691 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1692 $str .= substr( $s, strlen( $s ) - 2, 2 );
1694 $start = substr( $str, 0, strlen( $str ) - 2 );
1695 $end = substr( $str, strlen( $str ) - 2 );
1698 $str = $start . 'ך';
1701 $str = $start . 'ם';
1704 $str = $start . 'ן';
1707 $str = $start . 'ף';
1710 $str = $start . 'ץ';
1717 * Used by date() and time() to adjust the time output.
1719 * @param $ts Int the time in date('YmdHis') format
1720 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1721 * get user timecorrection setting)
1724 function userAdjust( $ts, $tz = false ) {
1725 global $wgUser, $wgLocalTZoffset;
1727 if ( $tz === false ) {
1728 $tz = $wgUser->getOption( 'timecorrection' );
1731 $data = explode( '|', $tz, 3 );
1733 if ( $data[0] == 'ZoneInfo' ) {
1734 wfSuppressWarnings();
1735 $userTZ = timezone_open( $data[2] );
1736 wfRestoreWarnings();
1737 if ( $userTZ !== false ) {
1738 $date = date_create( $ts, timezone_open( 'UTC' ) );
1739 date_timezone_set( $date, $userTZ );
1740 $date = date_format( $date, 'YmdHis' );
1743 # Unrecognized timezone, default to 'Offset' with the stored offset.
1744 $data[0] = 'Offset';
1748 if ( $data[0] == 'System' ||
$tz == '' ) {
1749 # Global offset in minutes.
1750 if ( isset( $wgLocalTZoffset ) ) {
1751 $minDiff = $wgLocalTZoffset;
1753 } elseif ( $data[0] == 'Offset' ) {
1754 $minDiff = intval( $data[1] );
1756 $data = explode( ':', $tz );
1757 if ( count( $data ) == 2 ) {
1758 $data[0] = intval( $data[0] );
1759 $data[1] = intval( $data[1] );
1760 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1761 if ( $data[0] < 0 ) {
1762 $minDiff = -$minDiff;
1765 $minDiff = intval( $data[0] ) * 60;
1769 # No difference ? Return time unchanged
1770 if ( 0 == $minDiff ) {
1774 wfSuppressWarnings(); // E_STRICT system time bitching
1775 # Generate an adjusted date; take advantage of the fact that mktime
1776 # will normalize out-of-range values so we don't have to split $minDiff
1777 # into hours and minutes.
1779 (int)substr( $ts, 8, 2 ) ), # Hours
1780 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1781 (int)substr( $ts, 12, 2 ), # Seconds
1782 (int)substr( $ts, 4, 2 ), # Month
1783 (int)substr( $ts, 6, 2 ), # Day
1784 (int)substr( $ts, 0, 4 ) ); # Year
1786 $date = date( 'YmdHis', $t );
1787 wfRestoreWarnings();
1793 * This is meant to be used by time(), date(), and timeanddate() to get
1794 * the date preference they're supposed to use, it should be used in
1798 * function timeanddate([...], $format = true) {
1799 * $datePreference = $this->dateFormat($format);
1804 * @param $usePrefs Mixed: if true, the user's preference is used
1805 * if false, the site/language default is used
1806 * if int/string, assumed to be a format.
1809 function dateFormat( $usePrefs = true ) {
1812 if ( is_bool( $usePrefs ) ) {
1814 $datePreference = $wgUser->getDatePreference();
1816 $datePreference = (string)User
::getDefaultOption( 'date' );
1819 $datePreference = (string)$usePrefs;
1823 if ( $datePreference == '' ) {
1827 return $datePreference;
1831 * Get a format string for a given type and preference
1832 * @param $type string May be date, time or both
1833 * @param $pref string The format name as it appears in Messages*.php
1837 function getDateFormatString( $type, $pref ) {
1838 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1839 if ( $pref == 'default' ) {
1840 $pref = $this->getDefaultDateFormat();
1841 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1843 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1844 if ( is_null( $df ) ) {
1845 $pref = $this->getDefaultDateFormat();
1846 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1849 $this->dateFormatStrings
[$type][$pref] = $df;
1851 return $this->dateFormatStrings
[$type][$pref];
1855 * @param $ts Mixed: the time format which needs to be turned into a
1856 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1857 * @param $adj Bool: whether to adjust the time output according to the
1858 * user configured offset ($timecorrection)
1859 * @param $format Mixed: true to use user's date format preference
1860 * @param $timecorrection String|bool the time offset as returned by
1861 * validateTimeZone() in Special:Preferences
1864 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1865 $ts = wfTimestamp( TS_MW
, $ts );
1867 $ts = $this->userAdjust( $ts, $timecorrection );
1869 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1870 return $this->sprintfDate( $df, $ts );
1874 * @param $ts Mixed: the time format which needs to be turned into a
1875 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1876 * @param $adj Bool: whether to adjust the time output according to the
1877 * user configured offset ($timecorrection)
1878 * @param $format Mixed: true to use user's date format preference
1879 * @param $timecorrection String|bool the time offset as returned by
1880 * validateTimeZone() in Special:Preferences
1883 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1884 $ts = wfTimestamp( TS_MW
, $ts );
1886 $ts = $this->userAdjust( $ts, $timecorrection );
1888 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1889 return $this->sprintfDate( $df, $ts );
1893 * @param $ts Mixed: the time format which needs to be turned into a
1894 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1895 * @param $adj Bool: whether to adjust the time output according to the
1896 * user configured offset ($timecorrection)
1897 * @param $format Mixed: what format to return, if it's false output the
1898 * default one (default true)
1899 * @param $timecorrection String|bool the time offset as returned by
1900 * validateTimeZone() in Special:Preferences
1903 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1904 $ts = wfTimestamp( TS_MW
, $ts );
1906 $ts = $this->userAdjust( $ts, $timecorrection );
1908 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1909 return $this->sprintfDate( $df, $ts );
1913 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1917 * @param integer $seconds The amount of seconds.
1918 * @param array $chosenIntervals The intervals to enable.
1922 public function duration( $seconds, array $chosenIntervals = array( 'years', 'days', 'hours', 'minutes', 'seconds' ) ) {
1924 'years' => 31557600, // 86400 * 365.25
1932 if ( !empty( $chosenIntervals ) ) {
1933 $intervals = array_intersect_key( $intervals, array_flip( $chosenIntervals ) );
1936 $segments = array();
1938 foreach ( $intervals as $name => $length ) {
1939 $value = floor( $seconds / $length );
1941 if ( $value > 0 ||
( $name == 'seconds' && empty( $segments ) ) ) {
1942 $seconds -= $value * $length;
1943 $message = new Message( 'duration-' . $name, array( $value ) );
1944 $segments[] = $message->inLanguage( $this )->escaped();
1948 return $this->listToText( $segments );
1952 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1954 * @param $type String: can be 'date', 'time' or 'both'
1955 * @param $ts Mixed: the time format which needs to be turned into a
1956 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1957 * @param $user User object used to get preferences for timezone and format
1958 * @param $options Array, can contain the following keys:
1959 * - 'timecorrection': time correction, can have the following values:
1960 * - true: use user's preference
1961 * - false: don't use time correction
1962 * - integer: value of time correction in minutes
1963 * - 'format': format to use, can have the following values:
1964 * - true: use user's preference
1965 * - false: use default preference
1966 * - string: format to use
1970 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1971 $ts = wfTimestamp( TS_MW
, $ts );
1972 $options +
= array( 'timecorrection' => true, 'format' => true );
1973 if ( $options['timecorrection'] !== false ) {
1974 if ( $options['timecorrection'] === true ) {
1975 $offset = $user->getOption( 'timecorrection' );
1977 $offset = $options['timecorrection'];
1979 $ts = $this->userAdjust( $ts, $offset );
1981 if ( $options['format'] === true ) {
1982 $format = $user->getDatePreference();
1984 $format = $options['format'];
1986 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1987 return $this->sprintfDate( $df, $ts );
1991 * Get the formatted date for the given timestamp and formatted for
1994 * @param $ts Mixed: the time format which needs to be turned into a
1995 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1996 * @param $user User object used to get preferences for timezone and format
1997 * @param $options Array, can contain the following keys:
1998 * - 'timecorrection': time correction, can have the following values:
1999 * - true: use user's preference
2000 * - false: don't use time correction
2001 * - integer: value of time correction in minutes
2002 * - 'format': format to use, can have the following values:
2003 * - true: use user's preference
2004 * - false: use default preference
2005 * - string: format to use
2009 public function userDate( $ts, User
$user, array $options = array() ) {
2010 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2014 * Get the formatted time for the given timestamp and formatted for
2017 * @param $ts Mixed: the time format which needs to be turned into a
2018 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2019 * @param $user User object used to get preferences for timezone and format
2020 * @param $options Array, can contain the following keys:
2021 * - 'timecorrection': time correction, can have the following values:
2022 * - true: use user's preference
2023 * - false: don't use time correction
2024 * - integer: value of time correction in minutes
2025 * - 'format': format to use, can have the following values:
2026 * - true: use user's preference
2027 * - false: use default preference
2028 * - string: format to use
2032 public function userTime( $ts, User
$user, array $options = array() ) {
2033 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2037 * Get the formatted date and time for the given timestamp and formatted for
2040 * @param $ts Mixed: the time format which needs to be turned into a
2041 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2042 * @param $user User object used to get preferences for timezone and format
2043 * @param $options Array, can contain the following keys:
2044 * - 'timecorrection': time correction, can have the following values:
2045 * - true: use user's preference
2046 * - false: don't use time correction
2047 * - integer: value of time correction in minutes
2048 * - 'format': format to use, can have the following values:
2049 * - true: use user's preference
2050 * - false: use default preference
2051 * - string: format to use
2055 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2056 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2060 * @param $key string
2061 * @return array|null
2063 function getMessage( $key ) {
2064 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2070 function getAllMessages() {
2071 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2080 function iconv( $in, $out, $string ) {
2081 # This is a wrapper for iconv in all languages except esperanto,
2082 # which does some nasty x-conversions beforehand
2084 # Even with //IGNORE iconv can whine about illegal characters in
2085 # *input* string. We just ignore those too.
2086 # REF: http://bugs.php.net/bug.php?id=37166
2087 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2088 wfSuppressWarnings();
2089 $text = iconv( $in, $out . '//IGNORE', $string );
2090 wfRestoreWarnings();
2094 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2097 * @param $matches array
2098 * @return mixed|string
2100 function ucwordbreaksCallbackAscii( $matches ) {
2101 return $this->ucfirst( $matches[1] );
2105 * @param $matches array
2108 function ucwordbreaksCallbackMB( $matches ) {
2109 return mb_strtoupper( $matches[0] );
2113 * @param $matches array
2116 function ucCallback( $matches ) {
2117 list( $wikiUpperChars ) = self
::getCaseMaps();
2118 return strtr( $matches[1], $wikiUpperChars );
2122 * @param $matches array
2125 function lcCallback( $matches ) {
2126 list( , $wikiLowerChars ) = self
::getCaseMaps();
2127 return strtr( $matches[1], $wikiLowerChars );
2131 * @param $matches array
2134 function ucwordsCallbackMB( $matches ) {
2135 return mb_strtoupper( $matches[0] );
2139 * @param $matches array
2142 function ucwordsCallbackWiki( $matches ) {
2143 list( $wikiUpperChars ) = self
::getCaseMaps();
2144 return strtr( $matches[0], $wikiUpperChars );
2148 * Make a string's first character uppercase
2150 * @param $str string
2154 function ucfirst( $str ) {
2156 if ( $o < 96 ) { // if already uppercase...
2158 } elseif ( $o < 128 ) {
2159 return ucfirst( $str ); // use PHP's ucfirst()
2161 // fall back to more complex logic in case of multibyte strings
2162 return $this->uc( $str, true );
2167 * Convert a string to uppercase
2169 * @param $str string
2170 * @param $first bool
2174 function uc( $str, $first = false ) {
2175 if ( function_exists( 'mb_strtoupper' ) ) {
2177 if ( $this->isMultibyte( $str ) ) {
2178 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2180 return ucfirst( $str );
2183 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2186 if ( $this->isMultibyte( $str ) ) {
2187 $x = $first ?
'^' : '';
2188 return preg_replace_callback(
2189 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2190 array( $this, 'ucCallback' ),
2194 return $first ?
ucfirst( $str ) : strtoupper( $str );
2200 * @param $str string
2201 * @return mixed|string
2203 function lcfirst( $str ) {
2206 return strval( $str );
2207 } elseif ( $o >= 128 ) {
2208 return $this->lc( $str, true );
2209 } elseif ( $o > 96 ) {
2212 $str[0] = strtolower( $str[0] );
2218 * @param $str string
2219 * @param $first bool
2220 * @return mixed|string
2222 function lc( $str, $first = false ) {
2223 if ( function_exists( 'mb_strtolower' ) ) {
2225 if ( $this->isMultibyte( $str ) ) {
2226 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2228 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2231 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2234 if ( $this->isMultibyte( $str ) ) {
2235 $x = $first ?
'^' : '';
2236 return preg_replace_callback(
2237 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2238 array( $this, 'lcCallback' ),
2242 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2248 * @param $str string
2251 function isMultibyte( $str ) {
2252 return (bool)preg_match( '/[\x80-\xff]/', $str );
2256 * @param $str string
2257 * @return mixed|string
2259 function ucwords( $str ) {
2260 if ( $this->isMultibyte( $str ) ) {
2261 $str = $this->lc( $str );
2263 // regexp to find first letter in each word (i.e. after each space)
2264 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2266 // function to use to capitalize a single char
2267 if ( function_exists( 'mb_strtoupper' ) ) {
2268 return preg_replace_callback(
2270 array( $this, 'ucwordsCallbackMB' ),
2274 return preg_replace_callback(
2276 array( $this, 'ucwordsCallbackWiki' ),
2281 return ucwords( strtolower( $str ) );
2286 * capitalize words at word breaks
2288 * @param $str string
2291 function ucwordbreaks( $str ) {
2292 if ( $this->isMultibyte( $str ) ) {
2293 $str = $this->lc( $str );
2295 // since \b doesn't work for UTF-8, we explicitely define word break chars
2296 $breaks = "[ \-\(\)\}\{\.,\?!]";
2298 // find first letter after word break
2299 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2301 if ( function_exists( 'mb_strtoupper' ) ) {
2302 return preg_replace_callback(
2304 array( $this, 'ucwordbreaksCallbackMB' ),
2308 return preg_replace_callback(
2310 array( $this, 'ucwordsCallbackWiki' ),
2315 return preg_replace_callback(
2316 '/\b([\w\x80-\xff]+)\b/',
2317 array( $this, 'ucwordbreaksCallbackAscii' ),
2324 * Return a case-folded representation of $s
2326 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2327 * and $s2 are the same except for the case of their characters. It is not
2328 * necessary for the value returned to make sense when displayed.
2330 * Do *not* perform any other normalisation in this function. If a caller
2331 * uses this function when it should be using a more general normalisation
2332 * function, then fix the caller.
2338 function caseFold( $s ) {
2339 return $this->uc( $s );
2346 function checkTitleEncoding( $s ) {
2347 if ( is_array( $s ) ) {
2348 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2350 # Check for non-UTF-8 URLs
2351 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2356 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2357 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2362 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2368 function fallback8bitEncoding() {
2369 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2373 * Most writing systems use whitespace to break up words.
2374 * Some languages such as Chinese don't conventionally do this,
2375 * which requires special handling when breaking up words for
2380 function hasWordBreaks() {
2385 * Some languages such as Chinese require word segmentation,
2386 * Specify such segmentation when overridden in derived class.
2388 * @param $string String
2391 function segmentByWord( $string ) {
2396 * Some languages have special punctuation need to be normalized.
2397 * Make such changes here.
2399 * @param $string String
2402 function normalizeForSearch( $string ) {
2403 return self
::convertDoubleWidth( $string );
2407 * convert double-width roman characters to single-width.
2408 * range: ff00-ff5f ~= 0020-007f
2410 * @param $string string
2414 protected static function convertDoubleWidth( $string ) {
2415 static $full = null;
2416 static $half = null;
2418 if ( $full === null ) {
2419 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2420 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2421 $full = str_split( $fullWidth, 3 );
2422 $half = str_split( $halfWidth );
2425 $string = str_replace( $full, $half, $string );
2430 * @param $string string
2431 * @param $pattern string
2434 protected static function insertSpace( $string, $pattern ) {
2435 $string = preg_replace( $pattern, " $1 ", $string );
2436 $string = preg_replace( '/ +/', ' ', $string );
2441 * @param $termsArray array
2444 function convertForSearchResult( $termsArray ) {
2445 # some languages, e.g. Chinese, need to do a conversion
2446 # in order for search results to be displayed correctly
2451 * Get the first character of a string.
2456 function firstChar( $s ) {
2459 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2460 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2465 if ( isset( $matches[1] ) ) {
2466 if ( strlen( $matches[1] ) != 3 ) {
2470 // Break down Hangul syllables to grab the first jamo
2471 $code = utf8ToCodepoint( $matches[1] );
2472 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2474 } elseif ( $code < 0xb098 ) {
2475 return "\xe3\x84\xb1";
2476 } elseif ( $code < 0xb2e4 ) {
2477 return "\xe3\x84\xb4";
2478 } elseif ( $code < 0xb77c ) {
2479 return "\xe3\x84\xb7";
2480 } elseif ( $code < 0xb9c8 ) {
2481 return "\xe3\x84\xb9";
2482 } elseif ( $code < 0xbc14 ) {
2483 return "\xe3\x85\x81";
2484 } elseif ( $code < 0xc0ac ) {
2485 return "\xe3\x85\x82";
2486 } elseif ( $code < 0xc544 ) {
2487 return "\xe3\x85\x85";
2488 } elseif ( $code < 0xc790 ) {
2489 return "\xe3\x85\x87";
2490 } elseif ( $code < 0xcc28 ) {
2491 return "\xe3\x85\x88";
2492 } elseif ( $code < 0xce74 ) {
2493 return "\xe3\x85\x8a";
2494 } elseif ( $code < 0xd0c0 ) {
2495 return "\xe3\x85\x8b";
2496 } elseif ( $code < 0xd30c ) {
2497 return "\xe3\x85\x8c";
2498 } elseif ( $code < 0xd558 ) {
2499 return "\xe3\x85\x8d";
2501 return "\xe3\x85\x8e";
2508 function initEncoding() {
2509 # Some languages may have an alternate char encoding option
2510 # (Esperanto X-coding, Japanese furigana conversion, etc)
2511 # If this language is used as the primary content language,
2512 # an override to the defaults can be set here on startup.
2519 function recodeForEdit( $s ) {
2520 # For some languages we'll want to explicitly specify
2521 # which characters make it into the edit box raw
2522 # or are converted in some way or another.
2523 global $wgEditEncoding;
2524 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2527 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2535 function recodeInput( $s ) {
2536 # Take the previous into account.
2537 global $wgEditEncoding;
2538 if ( $wgEditEncoding != '' ) {
2539 $enc = $wgEditEncoding;
2543 if ( $enc == 'UTF-8' ) {
2546 return $this->iconv( $enc, 'UTF-8', $s );
2551 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2552 * also cleans up certain backwards-compatible sequences, converting them
2553 * to the modern Unicode equivalent.
2555 * This is language-specific for performance reasons only.
2561 function normalize( $s ) {
2562 global $wgAllUnicodeFixes;
2563 $s = UtfNormal
::cleanUp( $s );
2564 if ( $wgAllUnicodeFixes ) {
2565 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2566 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2573 * Transform a string using serialized data stored in the given file (which
2574 * must be in the serialized subdirectory of $IP). The file contains pairs
2575 * mapping source characters to destination characters.
2577 * The data is cached in process memory. This will go faster if you have the
2578 * FastStringSearch extension.
2580 * @param $file string
2581 * @param $string string
2583 * @throws MWException
2586 function transformUsingPairFile( $file, $string ) {
2587 if ( !isset( $this->transformData
[$file] ) ) {
2588 $data = wfGetPrecompiledData( $file );
2589 if ( $data === false ) {
2590 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2592 $this->transformData
[$file] = new ReplacementArray( $data );
2594 return $this->transformData
[$file]->replace( $string );
2598 * For right-to-left language support
2603 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2607 * Return the correct HTML 'dir' attribute value for this language.
2611 return $this->isRTL() ?
'rtl' : 'ltr';
2615 * Return 'left' or 'right' as appropriate alignment for line-start
2616 * for this language's text direction.
2618 * Should be equivalent to CSS3 'start' text-align value....
2622 function alignStart() {
2623 return $this->isRTL() ?
'right' : 'left';
2627 * Return 'right' or 'left' as appropriate alignment for line-end
2628 * for this language's text direction.
2630 * Should be equivalent to CSS3 'end' text-align value....
2634 function alignEnd() {
2635 return $this->isRTL() ?
'left' : 'right';
2639 * A hidden direction mark (LRM or RLM), depending on the language direction
2641 * @param $opposite Boolean Get the direction mark opposite to your language
2644 function getDirMark( $opposite = false ) {
2645 $rtl = "\xE2\x80\x8F";
2646 $ltr = "\xE2\x80\x8E";
2647 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2648 return $this->isRTL() ?
$rtl : $ltr;
2654 function capitalizeAllNouns() {
2655 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2659 * An arrow, depending on the language direction
2663 function getArrow() {
2664 return $this->isRTL() ?
'←' : '→';
2668 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2672 function linkPrefixExtension() {
2673 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2679 function getMagicWords() {
2680 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2683 protected function doMagicHook() {
2684 if ( $this->mMagicHookDone
) {
2687 $this->mMagicHookDone
= true;
2688 wfProfileIn( 'LanguageGetMagic' );
2689 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2690 wfProfileOut( 'LanguageGetMagic' );
2694 * Fill a MagicWord object with data from here
2698 function getMagic( $mw ) {
2699 $this->doMagicHook();
2701 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2702 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2704 $magicWords = $this->getMagicWords();
2705 if ( isset( $magicWords[$mw->mId
] ) ) {
2706 $rawEntry = $magicWords[$mw->mId
];
2712 if ( !is_array( $rawEntry ) ) {
2713 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2715 $mw->mCaseSensitive
= $rawEntry[0];
2716 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2721 * Add magic words to the extension array
2723 * @param $newWords array
2725 function addMagicWordsByLang( $newWords ) {
2726 $fallbackChain = $this->getFallbackLanguages();
2727 $fallbackChain = array_reverse( $fallbackChain );
2728 foreach ( $fallbackChain as $code ) {
2729 if ( isset( $newWords[$code] ) ) {
2730 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2736 * Get special page names, as an associative array
2737 * case folded alias => real name
2739 function getSpecialPageAliases() {
2740 // Cache aliases because it may be slow to load them
2741 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2743 $this->mExtendedSpecialPageAliases
=
2744 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2745 wfRunHooks( 'LanguageGetSpecialPageAliases',
2746 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2749 return $this->mExtendedSpecialPageAliases
;
2753 * Italic is unsuitable for some languages
2755 * @param $text String: the text to be emphasized.
2758 function emphasize( $text ) {
2759 return "<em>$text</em>";
2763 * Normally we output all numbers in plain en_US style, that is
2764 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2765 * point twohundredthirtyfive. However this is not suitable for all
2766 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2767 * Icelandic just want to use commas instead of dots, and dots instead
2768 * of commas like "293.291,235".
2770 * An example of this function being called:
2772 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2775 * See LanguageGu.php for the Gujarati implementation and
2776 * $separatorTransformTable on MessageIs.php for
2777 * the , => . and . => , implementation.
2779 * @todo check if it's viable to use localeconv() for the decimal
2781 * @param $number Mixed: the string to be formatted, should be an integer
2782 * or a floating point number.
2783 * @param $nocommafy Bool: set to true for special numbers like dates
2786 public function formatNum( $number, $nocommafy = false ) {
2787 global $wgTranslateNumerals;
2788 if ( !$nocommafy ) {
2789 $number = $this->commafy( $number );
2790 $s = $this->separatorTransformTable();
2792 $number = strtr( $number, $s );
2796 if ( $wgTranslateNumerals ) {
2797 $s = $this->digitTransformTable();
2799 $number = strtr( $number, $s );
2807 * @param $number string
2810 function parseFormattedNumber( $number ) {
2811 $s = $this->digitTransformTable();
2813 $number = strtr( $number, array_flip( $s ) );
2816 $s = $this->separatorTransformTable();
2818 $number = strtr( $number, array_flip( $s ) );
2821 $number = strtr( $number, array( ',' => '' ) );
2826 * Adds commas to a given number
2831 function commafy( $_ ) {
2832 $digitGroupingPattern = $this->digitGroupingPattern();
2833 if ( $_ === null ) {
2837 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2838 // default grouping is at thousands, use the same for ###,###,### pattern too.
2839 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2841 // Ref: http://cldr.unicode.org/translation/number-patterns
2843 if ( intval( $_ ) < 0 ) {
2844 // For negative numbers apply the algorithm like positive number and add sign.
2846 $_ = substr( $_, 1 );
2848 $numberpart = array();
2849 $decimalpart = array();
2850 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2851 preg_match( "/\d+/", $_, $numberpart );
2852 preg_match( "/\.\d*/", $_, $decimalpart );
2853 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2854 if ( $groupedNumber === $_ ) {
2855 // the string does not have any number part. Eg: .12345
2856 return $sign . $groupedNumber;
2858 $start = $end = strlen( $numberpart[0] );
2859 while ( $start > 0 ) {
2860 $match = $matches[0][$numMatches -1] ;
2861 $matchLen = strlen( $match );
2862 $start = $end - $matchLen;
2866 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2868 if ( $numMatches > 1 ) {
2869 // use the last pattern for the rest of the number
2873 $groupedNumber = "," . $groupedNumber;
2876 return $sign . $groupedNumber;
2882 function digitGroupingPattern() {
2883 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2889 function digitTransformTable() {
2890 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2896 function separatorTransformTable() {
2897 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2901 * Take a list of strings and build a locale-friendly comma-separated
2902 * list, using the local comma-separator message.
2903 * The last two strings are chained with an "and".
2908 function listToText( array $l ) {
2910 $m = count( $l ) - 1;
2912 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2914 for ( $i = $m; $i >= 0; $i-- ) {
2917 } elseif ( $i == $m - 1 ) {
2918 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2920 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2928 * Take a list of strings and build a locale-friendly comma-separated
2929 * list, using the local comma-separator message.
2930 * @param $list array of strings to put in a comma list
2933 function commaList( array $list ) {
2937 array( 'parsemag', 'escapenoentities', 'language' => $this )
2944 * Take a list of strings and build a locale-friendly semicolon-separated
2945 * list, using the local semicolon-separator message.
2946 * @param $list array of strings to put in a semicolon list
2949 function semicolonList( array $list ) {
2952 'semicolon-separator',
2953 array( 'parsemag', 'escapenoentities', 'language' => $this )
2960 * Same as commaList, but separate it with the pipe instead.
2961 * @param $list array of strings to put in a pipe list
2964 function pipeList( array $list ) {
2968 array( 'escapenoentities', 'language' => $this )
2975 * Truncate a string to a specified length in bytes, appending an optional
2976 * string (e.g. for ellipses)
2978 * The database offers limited byte lengths for some columns in the database;
2979 * multi-byte character sets mean we need to ensure that only whole characters
2980 * are included, otherwise broken characters can be passed to the user
2982 * If $length is negative, the string will be truncated from the beginning
2984 * @param $string String to truncate
2985 * @param $length Int: maximum length (including ellipses)
2986 * @param $ellipsis String to append to the truncated text
2987 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2988 * $adjustLength was introduced in 1.18, before that behaved as if false.
2991 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2992 # Use the localized ellipsis character
2993 if ( $ellipsis == '...' ) {
2994 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2996 # Check if there is no need to truncate
2997 if ( $length == 0 ) {
2998 return $ellipsis; // convention
2999 } elseif ( strlen( $string ) <= abs( $length ) ) {
3000 return $string; // no need to truncate
3002 $stringOriginal = $string;
3003 # If ellipsis length is >= $length then we can't apply $adjustLength
3004 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3005 $string = $ellipsis; // this can be slightly unexpected
3006 # Otherwise, truncate and add ellipsis...
3008 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3009 if ( $length > 0 ) {
3010 $length -= $eLength;
3011 $string = substr( $string, 0, $length ); // xyz...
3012 $string = $this->removeBadCharLast( $string );
3013 $string = $string . $ellipsis;
3015 $length +
= $eLength;
3016 $string = substr( $string, $length ); // ...xyz
3017 $string = $this->removeBadCharFirst( $string );
3018 $string = $ellipsis . $string;
3021 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3022 # This check is *not* redundant if $adjustLength, due to the single case where
3023 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3024 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3027 return $stringOriginal;
3032 * Remove bytes that represent an incomplete Unicode character
3033 * at the end of string (e.g. bytes of the char are missing)
3035 * @param $string String
3038 protected function removeBadCharLast( $string ) {
3039 if ( $string != '' ) {
3040 $char = ord( $string[strlen( $string ) - 1] );
3042 if ( $char >= 0xc0 ) {
3043 # We got the first byte only of a multibyte char; remove it.
3044 $string = substr( $string, 0, -1 );
3045 } elseif ( $char >= 0x80 &&
3046 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3047 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3049 # We chopped in the middle of a character; remove it
3057 * Remove bytes that represent an incomplete Unicode character
3058 * at the start of string (e.g. bytes of the char are missing)
3060 * @param $string String
3063 protected function removeBadCharFirst( $string ) {
3064 if ( $string != '' ) {
3065 $char = ord( $string[0] );
3066 if ( $char >= 0x80 && $char < 0xc0 ) {
3067 # We chopped in the middle of a character; remove the whole thing
3068 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3075 * Truncate a string of valid HTML to a specified length in bytes,
3076 * appending an optional string (e.g. for ellipses), and return valid HTML
3078 * This is only intended for styled/linked text, such as HTML with
3079 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3080 * Also, this will not detect things like "display:none" CSS.
3082 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3084 * @param string $text HTML string to truncate
3085 * @param int $length (zero/positive) Maximum length (including ellipses)
3086 * @param string $ellipsis String to append to the truncated text
3089 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3090 # Use the localized ellipsis character
3091 if ( $ellipsis == '...' ) {
3092 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3094 # Check if there is clearly no need to truncate
3095 if ( $length <= 0 ) {
3096 return $ellipsis; // no text shown, nothing to format (convention)
3097 } elseif ( strlen( $text ) <= $length ) {
3098 return $text; // string short enough even *with* HTML (short-circuit)
3101 $dispLen = 0; // innerHTML legth so far
3102 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3103 $tagType = 0; // 0-open, 1-close
3104 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3105 $entityState = 0; // 0-not entity, 1-entity
3106 $tag = $ret = ''; // accumulated tag name, accumulated result string
3107 $openTags = array(); // open tag stack
3108 $maybeState = null; // possible truncation state
3110 $textLen = strlen( $text );
3111 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3112 for ( $pos = 0; true; ++
$pos ) {
3113 # Consider truncation once the display length has reached the maximim.
3114 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3115 # Check that we're not in the middle of a bracket/entity...
3116 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3117 if ( !$testingEllipsis ) {
3118 $testingEllipsis = true;
3119 # Save where we are; we will truncate here unless there turn out to
3120 # be so few remaining characters that truncation is not necessary.
3121 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3122 $maybeState = array( $ret, $openTags ); // save state
3124 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3125 # String in fact does need truncation, the truncation point was OK.
3126 list( $ret, $openTags ) = $maybeState; // reload state
3127 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3128 $ret .= $ellipsis; // add ellipsis
3132 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3134 # Read the next char...
3136 $lastCh = $pos ?
$text[$pos - 1] : '';
3137 $ret .= $ch; // add to result string
3139 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3140 $entityState = 0; // for bad HTML
3141 $bracketState = 1; // tag started (checking for backslash)
3142 } elseif ( $ch == '>' ) {
3143 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3144 $entityState = 0; // for bad HTML
3145 $bracketState = 0; // out of brackets
3146 } elseif ( $bracketState == 1 ) {
3148 $tagType = 1; // close tag (e.g. "</span>")
3150 $tagType = 0; // open tag (e.g. "<span>")
3153 $bracketState = 2; // building tag name
3154 } elseif ( $bracketState == 2 ) {
3158 // Name found (e.g. "<a href=..."), add on tag attributes...
3159 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3161 } elseif ( $bracketState == 0 ) {
3162 if ( $entityState ) {
3165 $dispLen++
; // entity is one displayed char
3168 if ( $neLength == 0 && !$maybeState ) {
3169 // Save state without $ch. We want to *hit* the first
3170 // display char (to get tags) but not *use* it if truncating.
3171 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3174 $entityState = 1; // entity found, (e.g. " ")
3176 $dispLen++
; // this char is displayed
3177 // Add the next $max display text chars after this in one swoop...
3178 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3179 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3180 $dispLen +
= $skipped;
3186 // Close the last tag if left unclosed by bad HTML
3187 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3188 while ( count( $openTags ) > 0 ) {
3189 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3195 * truncateHtml() helper function
3196 * like strcspn() but adds the skipped chars to $ret
3205 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3206 if ( $len === null ) {
3207 $len = -1; // -1 means "no limit" for strcspn
3208 } elseif ( $len < 0 ) {
3212 if ( $start < strlen( $text ) ) {
3213 $skipCount = strcspn( $text, $search, $start, $len );
3214 $ret .= substr( $text, $start, $skipCount );
3220 * truncateHtml() helper function
3221 * (a) push or pop $tag from $openTags as needed
3222 * (b) clear $tag value
3223 * @param &$tag string Current HTML tag name we are looking at
3224 * @param $tagType int (0-open tag, 1-close tag)
3225 * @param $lastCh string Character before the '>' that ended this tag
3226 * @param &$openTags array Open tag stack (not accounting for $tag)
3228 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3229 $tag = ltrim( $tag );
3231 if ( $tagType == 0 && $lastCh != '/' ) {
3232 $openTags[] = $tag; // tag opened (didn't close itself)
3233 } elseif ( $tagType == 1 ) {
3234 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3235 array_pop( $openTags ); // tag closed
3243 * Grammatical transformations, needed for inflected languages
3244 * Invoked by putting {{grammar:case|word}} in a message
3246 * @param $word string
3247 * @param $case string
3250 function convertGrammar( $word, $case ) {
3251 global $wgGrammarForms;
3252 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3253 return $wgGrammarForms[$this->getCode()][$case][$word];
3259 * Provides an alternative text depending on specified gender.
3260 * Usage {{gender:username|masculine|feminine|neutral}}.
3261 * username is optional, in which case the gender of current user is used,
3262 * but only in (some) interface messages; otherwise default gender is used.
3264 * If no forms are given, an empty string is returned. If only one form is
3265 * given, it will be returned unconditionally. These details are implied by
3266 * the caller and cannot be overridden in subclasses.
3268 * If more than one form is given, the default is to use the neutral one
3269 * if it is specified, and to use the masculine one otherwise. These
3270 * details can be overridden in subclasses.
3272 * @param $gender string
3273 * @param $forms array
3277 function gender( $gender, $forms ) {
3278 if ( !count( $forms ) ) {
3281 $forms = $this->preConvertPlural( $forms, 2 );
3282 if ( $gender === 'male' ) {
3285 if ( $gender === 'female' ) {
3288 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3292 * Plural form transformations, needed for some languages.
3293 * For example, there are 3 form of plural in Russian and Polish,
3294 * depending on "count mod 10". See [[w:Plural]]
3295 * For English it is pretty simple.
3297 * Invoked by putting {{plural:count|wordform1|wordform2}}
3298 * or {{plural:count|wordform1|wordform2|wordform3}}
3300 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3302 * @param $count Integer: non-localized number
3303 * @param $forms Array: different plural forms
3304 * @return string Correct form of plural for $count in this language
3306 function convertPlural( $count, $forms ) {
3307 if ( !count( $forms ) ) {
3310 $forms = $this->preConvertPlural( $forms, 2 );
3312 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3316 * Checks that convertPlural was given an array and pads it to requested
3317 * amount of forms by copying the last one.
3319 * @param $count Integer: How many forms should there be at least
3320 * @param $forms Array of forms given to convertPlural
3321 * @return array Padded array of forms or an exception if not an array
3323 protected function preConvertPlural( /* Array */ $forms, $count ) {
3324 while ( count( $forms ) < $count ) {
3325 $forms[] = $forms[count( $forms ) - 1];
3331 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3332 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3333 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3334 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3337 * @param $str String: the validated block duration in English
3338 * @return string Somehow translated block duration
3339 * @see LanguageFi.php for example implementation
3341 function translateBlockExpiry( $str ) {
3342 $duration = SpecialBlock
::getSuggestedDurations( $this );
3343 foreach ( $duration as $show => $value ) {
3344 if ( strcmp( $str, $value ) == 0 ) {
3345 return htmlspecialchars( trim( $show ) );
3349 // Since usually only infinite or indefinite is only on list, so try
3350 // equivalents if still here.
3351 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3352 if ( in_array( $str, $indefs ) ) {
3353 foreach ( $indefs as $val ) {
3354 $show = array_search( $val, $duration, true );
3355 if ( $show !== false ) {
3356 return htmlspecialchars( trim( $show ) );
3360 // If all else fails, return the original string.
3365 * languages like Chinese need to be segmented in order for the diff
3368 * @param $text String
3371 public function segmentForDiff( $text ) {
3376 * and unsegment to show the result
3378 * @param $text String
3381 public function unsegmentForDiff( $text ) {
3386 * Return the LanguageConverter used in the Language
3389 * @return LanguageConverter
3391 public function getConverter() {
3392 return $this->mConverter
;
3396 * convert text to all supported variants
3398 * @param $text string
3401 public function autoConvertToAllVariants( $text ) {
3402 return $this->mConverter
->autoConvertToAllVariants( $text );
3406 * convert text to different variants of a language.
3408 * @param $text string
3411 public function convert( $text ) {
3412 return $this->mConverter
->convert( $text );
3416 * Convert a Title object to a string in the preferred variant
3418 * @param $title Title
3421 public function convertTitle( $title ) {
3422 return $this->mConverter
->convertTitle( $title );
3426 * Check if this is a language with variants
3430 public function hasVariants() {
3431 return sizeof( $this->getVariants() ) > 1;
3435 * Check if the language has the specific variant
3438 * @param $variant string
3441 public function hasVariant( $variant ) {
3442 return (bool)$this->mConverter
->validateVariant( $variant );
3446 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3448 * @param $text string
3451 public function armourMath( $text ) {
3452 return $this->mConverter
->armourMath( $text );
3456 * Perform output conversion on a string, and encode for safe HTML output.
3457 * @param $text String text to be converted
3458 * @param $isTitle Bool whether this conversion is for the article title
3460 * @todo this should get integrated somewhere sane
3462 public function convertHtml( $text, $isTitle = false ) {
3463 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3467 * @param $key string
3470 public function convertCategoryKey( $key ) {
3471 return $this->mConverter
->convertCategoryKey( $key );
3475 * Get the list of variants supported by this language
3476 * see sample implementation in LanguageZh.php
3478 * @return array an array of language codes
3480 public function getVariants() {
3481 return $this->mConverter
->getVariants();
3487 public function getPreferredVariant() {
3488 return $this->mConverter
->getPreferredVariant();
3494 public function getDefaultVariant() {
3495 return $this->mConverter
->getDefaultVariant();
3501 public function getURLVariant() {
3502 return $this->mConverter
->getURLVariant();
3506 * If a language supports multiple variants, it is
3507 * possible that non-existing link in one variant
3508 * actually exists in another variant. this function
3509 * tries to find it. See e.g. LanguageZh.php
3511 * @param $link String: the name of the link
3512 * @param $nt Mixed: the title object of the link
3513 * @param $ignoreOtherCond Boolean: to disable other conditions when
3514 * we need to transclude a template or update a category's link
3515 * @return null the input parameters may be modified upon return
3517 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3518 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3522 * If a language supports multiple variants, converts text
3523 * into an array of all possible variants of the text:
3524 * 'variant' => text in that variant
3526 * @deprecated since 1.17 Use autoConvertToAllVariants()
3528 * @param $text string
3532 public function convertLinkToAllVariants( $text ) {
3533 return $this->mConverter
->convertLinkToAllVariants( $text );
3537 * returns language specific options used by User::getPageRenderHash()
3538 * for example, the preferred language variant
3542 function getExtraHashOptions() {
3543 return $this->mConverter
->getExtraHashOptions();
3547 * For languages that support multiple variants, the title of an
3548 * article may be displayed differently in different variants. this
3549 * function returns the apporiate title defined in the body of the article.
3553 public function getParsedTitle() {
3554 return $this->mConverter
->getParsedTitle();
3558 * Enclose a string with the "no conversion" tag. This is used by
3559 * various functions in the Parser
3561 * @param $text String: text to be tagged for no conversion
3562 * @param $noParse bool
3563 * @return string the tagged text
3565 public function markNoConversion( $text, $noParse = false ) {
3566 return $this->mConverter
->markNoConversion( $text, $noParse );
3570 * A regular expression to match legal word-trailing characters
3571 * which should be merged onto a link of the form [[foo]]bar.
3575 public function linkTrail() {
3576 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3582 function getLangObj() {
3587 * Get the RFC 3066 code for this language object
3591 public function getCode() {
3592 return $this->mCode
;
3596 * Get the code in Bcp47 format which we can use
3597 * inside of html lang="" tags.
3601 public function getHtmlCode() {
3602 if ( is_null( $this->mHtmlCode
) ) {
3603 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3605 return $this->mHtmlCode
;
3609 * @param $code string
3611 public function setCode( $code ) {
3612 $this->mCode
= $code;
3613 // Ensure we don't leave an incorrect html code lying around
3614 $this->mHtmlCode
= null;
3618 * Get the name of a file for a certain language code
3619 * @param $prefix string Prepend this to the filename
3620 * @param $code string Language code
3621 * @param $suffix string Append this to the filename
3622 * @throws MWException
3623 * @return string $prefix . $mangledCode . $suffix
3625 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3626 // Protect against path traversal
3627 if ( !Language
::isValidCode( $code )
3628 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3630 throw new MWException( "Invalid language code \"$code\"" );
3633 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3637 * Get the language code from a file name. Inverse of getFileName()
3638 * @param $filename string $prefix . $languageCode . $suffix
3639 * @param $prefix string Prefix before the language code
3640 * @param $suffix string Suffix after the language code
3641 * @return string Language code, or false if $prefix or $suffix isn't found
3643 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3645 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3646 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3647 if ( !count( $m ) ) {
3650 return str_replace( '_', '-', strtolower( $m[1] ) );
3654 * @param $code string
3657 public static function getMessagesFileName( $code ) {
3659 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3660 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3665 * @param $code string
3668 public static function getClassFileName( $code ) {
3670 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3674 * Get the first fallback for a given language.
3676 * @param $code string
3678 * @return bool|string
3680 public static function getFallbackFor( $code ) {
3681 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3684 $fallbacks = self
::getFallbacksFor( $code );
3685 $first = array_shift( $fallbacks );
3691 * Get the ordered list of fallback languages.
3694 * @param $code string Language code
3697 public static function getFallbacksFor( $code ) {
3698 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3701 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3702 $v = array_map( 'trim', explode( ',', $v ) );
3703 if ( $v[count( $v ) - 1] !== 'en' ) {
3711 * Get all messages for a given language
3712 * WARNING: this may take a long time. If you just need all message *keys*
3713 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3715 * @param $code string
3719 public static function getMessagesFor( $code ) {
3720 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3724 * Get a message for a given language
3726 * @param $key string
3727 * @param $code string
3731 public static function getMessageFor( $key, $code ) {
3732 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3736 * Get all message keys for a given language. This is a faster alternative to
3737 * array_keys( Language::getMessagesFor( $code ) )
3740 * @param $code string Language code
3741 * @return array of message keys (strings)
3743 public static function getMessageKeysFor( $code ) {
3744 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3751 function fixVariableInNamespace( $talk ) {
3752 if ( strpos( $talk, '$1' ) === false ) {
3756 global $wgMetaNamespace;
3757 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3759 # Allow grammar transformations
3760 # Allowing full message-style parsing would make simple requests
3761 # such as action=raw much more expensive than they need to be.
3762 # This will hopefully cover most cases.
3763 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3764 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3765 return str_replace( ' ', '_', $talk );
3772 function replaceGrammarInNamespace( $m ) {
3773 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3777 * @throws MWException
3780 static function getCaseMaps() {
3781 static $wikiUpperChars, $wikiLowerChars;
3782 if ( isset( $wikiUpperChars ) ) {
3783 return array( $wikiUpperChars, $wikiLowerChars );
3786 wfProfileIn( __METHOD__
);
3787 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3788 if ( $arr === false ) {
3789 throw new MWException(
3790 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3792 $wikiUpperChars = $arr['wikiUpperChars'];
3793 $wikiLowerChars = $arr['wikiLowerChars'];
3794 wfProfileOut( __METHOD__
);
3795 return array( $wikiUpperChars, $wikiLowerChars );
3799 * Decode an expiry (block, protection, etc) which has come from the DB
3801 * @FIXME: why are we returnings DBMS-dependent strings???
3803 * @param $expiry String: Database expiry String
3804 * @param $format Bool|Int true to process using language functions, or TS_ constant
3805 * to return the expiry in a given timestamp
3808 public function formatExpiry( $expiry, $format = true ) {
3809 static $infinity, $infinityMsg;
3810 if ( $infinity === null ) {
3811 $infinityMsg = wfMessage( 'infiniteblock' );
3812 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3815 if ( $expiry == '' ||
$expiry == $infinity ) {
3816 return $format === true
3820 return $format === true
3821 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3822 : wfTimestamp( $format, $expiry );
3828 * @param $seconds int|float
3829 * @param $format Array Optional
3830 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3831 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3832 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3833 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3836 function formatTimePeriod( $seconds, $format = array() ) {
3837 if ( !is_array( $format ) ) {
3838 $format = array( 'avoid' => $format ); // For backwards compatibility
3840 if ( !isset( $format['avoid'] ) ) {
3841 $format['avoid'] = false;
3843 if ( !isset( $format['noabbrevs' ] ) ) {
3844 $format['noabbrevs'] = false;
3846 $secondsMsg = wfMessage(
3847 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3848 $minutesMsg = wfMessage(
3849 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3850 $hoursMsg = wfMessage(
3851 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3852 $daysMsg = wfMessage(
3853 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3855 if ( round( $seconds * 10 ) < 100 ) {
3856 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3857 $s = $secondsMsg->params( $s )->text();
3858 } elseif ( round( $seconds ) < 60 ) {
3859 $s = $this->formatNum( round( $seconds ) );
3860 $s = $secondsMsg->params( $s )->text();
3861 } elseif ( round( $seconds ) < 3600 ) {
3862 $minutes = floor( $seconds / 60 );
3863 $secondsPart = round( fmod( $seconds, 60 ) );
3864 if ( $secondsPart == 60 ) {
3868 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3870 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3871 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3872 $hours = floor( $seconds / 3600 );
3873 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3874 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3875 if ( $secondsPart == 60 ) {
3879 if ( $minutes == 60 ) {
3883 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3885 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3886 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3887 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3890 $days = floor( $seconds / 86400 );
3891 if ( $format['avoid'] === 'avoidminutes' ) {
3892 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3893 if ( $hours == 24 ) {
3897 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3899 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3900 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3901 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3902 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3903 if ( $minutes == 60 ) {
3907 if ( $hours == 24 ) {
3911 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3913 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3915 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3917 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3919 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3926 * Format a bitrate for output, using an appropriate
3927 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3929 * This use base 1000. For base 1024 use formatSize(), for another base
3930 * see formatComputingNumbers()
3935 function formatBitrate( $bps ) {
3936 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3940 * @param $size int Size of the unit
3941 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3942 * @param $messageKey string Message key to be uesd
3945 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3947 return str_replace( '$1', $this->formatNum( $size ),
3948 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3951 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3954 $maxIndex = count( $sizes ) - 1;
3955 while ( $size >= $boundary && $index < $maxIndex ) {
3960 // For small sizes no decimal places necessary
3963 // For MB and bigger two decimal places are smarter
3966 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3968 $size = round( $size, $round );
3969 $text = $this->getMessageFromDB( $msg );
3970 return str_replace( '$1', $this->formatNum( $size ), $text );
3974 * Format a size in bytes for output, using an appropriate
3975 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3977 * This method use base 1024. For base 1000 use formatBitrate(), for
3978 * another base see formatComputingNumbers()
3980 * @param $size int Size to format
3981 * @return string Plain text (not HTML)
3983 function formatSize( $size ) {
3984 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3988 * Make a list item, used by various special pages
3990 * @param $page String Page link
3991 * @param $details String Text between brackets
3992 * @param $oppositedm Boolean Add the direction mark opposite to your
3993 * language, to display text properly
3996 function specialList( $page, $details, $oppositedm = true ) {
3997 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3998 $this->getDirMark();
3999 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4000 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4001 return $page . $details;
4005 * Generate (prev x| next x) (20|50|100...) type links for paging
4007 * @param $title Title object to link
4008 * @param $offset Integer offset parameter
4009 * @param $limit Integer limit parameter
4010 * @param $query String optional URL query parameter string
4011 * @param $atend Bool optional param for specified if this is the last page
4014 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4015 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4017 # Make 'previous' link
4018 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4019 if ( $offset > 0 ) {
4020 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4021 $query, $prev, 'prevn-title', 'mw-prevlink' );
4023 $plink = htmlspecialchars( $prev );
4027 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4029 $nlink = htmlspecialchars( $next );
4031 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4032 $query, $next, 'prevn-title', 'mw-nextlink' );
4035 # Make links to set number of items per page
4036 $numLinks = array();
4037 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4038 $numLinks[] = $this->numLink( $title, $offset, $num,
4039 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4042 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4043 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4047 * Helper function for viewPrevNext() that generates links
4049 * @param $title Title object to link
4050 * @param $offset Integer offset parameter
4051 * @param $limit Integer limit parameter
4052 * @param $query Array extra query parameters
4053 * @param $link String text to use for the link; will be escaped
4054 * @param $tooltipMsg String name of the message to use as tooltip
4055 * @param $class String value of the "class" attribute of the link
4056 * @return String HTML fragment
4058 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4059 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4060 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4061 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4062 'title' => $tooltip, 'class' => $class ), $link );
4066 * Get the conversion rule title, if any.
4070 public function getConvRuleTitle() {
4071 return $this->mConverter
->getConvRuleTitle();