3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
37 function __construct( $langobj ) { $this->mLang
= $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang
->getCode() ); }
43 function getPreferredVariant() { return $this->mLang
->getCode(); }
44 function getDefaultVariant() { return $this->mLang
->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
57 * Internationalisation code
63 * @var LanguageConverter
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
77 * ReplacementArray object caches
79 var $transformData = array();
82 * @var LocalisationCache
84 static public $dataCache;
86 static public $mLangObjCache = array();
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
143 * Get a cached language object for a given language code
144 * @param $code String
147 static function factory( $code ) {
148 if ( !isset( self
::$mLangObjCache[$code] ) ) {
149 if ( count( self
::$mLangObjCache ) > 10 ) {
150 // Don't keep a billion objects around, that's stupid.
151 self
::$mLangObjCache = array();
153 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
155 return self
::$mLangObjCache[$code];
159 * Create a language object for a given language code
160 * @param $code String
163 protected static function newFromCode( $code ) {
164 // Protect against path traversal below
165 if ( !Language
::isValidCode( $code )
166 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
168 throw new MWException( "Invalid language code \"$code\"" );
171 if ( !Language
::isValidBuiltInCode( $code ) ) {
172 // It's not possible to customise this code with class files, so
173 // just return a Language object. This is to support uselang= hacks.
174 $lang = new Language
;
175 $lang->setCode( $code );
179 // Check if there is a language class for the code
180 $class = self
::classFromCode( $code );
181 self
::preloadLanguageClass( $class );
182 if ( MWInit
::classExists( $class ) ) {
187 // Keep trying the fallback list until we find an existing class
188 $fallbacks = Language
::getFallbacksFor( $code );
189 foreach ( $fallbacks as $fallbackCode ) {
190 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
191 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
194 $class = self
::classFromCode( $fallbackCode );
195 self
::preloadLanguageClass( $class );
196 if ( MWInit
::classExists( $class ) ) {
197 $lang = Language
::newFromCode( $fallbackCode );
198 $lang->setCode( $code );
203 throw new MWException( "Invalid fallback sequence for language '$code'" );
207 * Returns true if a language code string is of a valid form, whether or
208 * not it exists. This includes codes which are used solely for
209 * customisation via the MediaWiki namespace.
211 * @param $code string
215 public static function isValidCode( $code ) {
217 strcspn( $code, ":/\\\000" ) === strlen( $code )
218 && !preg_match( Title
::getTitleInvalidRegex(), $code );
222 * Returns true if a language code is of a valid form for the purposes of
223 * internal customisation of MediaWiki, via Messages*.php.
225 * @param $code string
230 public static function isValidBuiltInCode( $code ) {
231 return preg_match( '/^[a-z0-9-]+$/i', $code );
236 * @return String Name of the language class
238 public static function classFromCode( $code ) {
239 if ( $code == 'en' ) {
242 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
247 * Includes language class files
249 * @param $class string Name of the language class
251 public static function preloadLanguageClass( $class ) {
254 if ( $class === 'Language' ) {
258 if ( !defined( 'MW_COMPILED' ) ) {
259 // Preload base classes to work around APC/PHP5 bug
260 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
261 include_once( "$IP/languages/classes/$class.deps.php" );
263 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
264 include_once( "$IP/languages/classes/$class.php" );
270 * Get the LocalisationCache instance
272 * @return LocalisationCache
274 public static function getLocalisationCache() {
275 if ( is_null( self
::$dataCache ) ) {
276 global $wgLocalisationCacheConf;
277 $class = $wgLocalisationCacheConf['class'];
278 self
::$dataCache = new $class( $wgLocalisationCacheConf );
280 return self
::$dataCache;
283 function __construct() {
284 $this->mConverter
= new FakeConverter( $this );
285 // Set the code to the name of the descendant
286 if ( get_class( $this ) == 'Language' ) {
289 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
291 self
::getLocalisationCache();
295 * Reduce memory usage
297 function __destruct() {
298 foreach ( $this as $name => $value ) {
299 unset( $this->$name );
304 * Hook which will be called if this is the content language.
305 * Descendants can use this to register hook functions or modify globals
307 function initContLang() { }
310 * Same as getFallbacksFor for current language.
312 * @deprecated in 1.19
314 function getFallbackLanguageCode() {
315 wfDeprecated( __METHOD__
);
316 return self
::getFallbackFor( $this->mCode
);
323 function getFallbackLanguages() {
324 return self
::getFallbacksFor( $this->mCode
);
328 * Exports $wgBookstoreListEn
331 function getBookstoreList() {
332 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
338 public function getNamespaces() {
339 if ( is_null( $this->namespaceNames
) ) {
340 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
342 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
343 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
345 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
347 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
348 if ( $wgMetaNamespaceTalk ) {
349 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
351 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
352 $this->namespaceNames
[NS_PROJECT_TALK
] =
353 $this->fixVariableInNamespace( $talk );
356 # Sometimes a language will be localised but not actually exist on this wiki.
357 foreach ( $this->namespaceNames
as $key => $text ) {
358 if ( !isset( $validNamespaces[$key] ) ) {
359 unset( $this->namespaceNames
[$key] );
363 # The above mixing may leave namespaces out of canonical order.
364 # Re-order by namespace ID number...
365 ksort( $this->namespaceNames
);
367 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
369 return $this->namespaceNames
;
373 * Arbitrarily set all of the namespace names at once. Mainly used for testing
374 * @param $namespaces Array of namespaces (id => name)
376 public function setNamespaces( array $namespaces ) {
377 $this->namespaceNames
= $namespaces;
381 * A convenience function that returns the same thing as
382 * getNamespaces() except with the array values changed to ' '
383 * where it found '_', useful for producing output to be displayed
384 * e.g. in <select> forms.
388 function getFormattedNamespaces() {
389 $ns = $this->getNamespaces();
390 foreach ( $ns as $k => $v ) {
391 $ns[$k] = strtr( $v, '_', ' ' );
397 * Get a namespace value by key
399 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
400 * echo $mw_ns; // prints 'MediaWiki'
403 * @param $index Int: the array key of the namespace to return
404 * @return mixed, string if the namespace value exists, otherwise false
406 function getNsText( $index ) {
407 $ns = $this->getNamespaces();
408 return isset( $ns[$index] ) ?
$ns[$index] : false;
412 * A convenience function that returns the same thing as
413 * getNsText() except with '_' changed to ' ', useful for
416 * @param $index string
420 function getFormattedNsText( $index ) {
421 $ns = $this->getNsText( $index );
422 return strtr( $ns, '_', ' ' );
426 * Returns gender-dependent namespace alias if available.
427 * @param $index Int: namespace index
428 * @param $gender String: gender key (male, female... )
432 function getGenderNsText( $index, $gender ) {
433 global $wgExtraGenderNamespaces;
435 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
436 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
440 * Whether this language makes distinguishes genders for example in
445 function needsGenderDistinction() {
446 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
447 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
448 // $wgExtraGenderNamespaces overrides everything
450 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
451 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
452 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
455 // Check what is in i18n files
456 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
457 return count( $aliases ) > 0;
462 * Get a namespace key by value, case insensitive.
463 * Only matches namespace names for the current language, not the
464 * canonical ones defined in Namespace.php.
466 * @param $text String
467 * @return mixed An integer if $text is a valid value otherwise false
469 function getLocalNsIndex( $text ) {
470 $lctext = $this->lc( $text );
471 $ids = $this->getNamespaceIds();
472 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
478 function getNamespaceAliases() {
479 if ( is_null( $this->namespaceAliases
) ) {
480 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
484 foreach ( $aliases as $name => $index ) {
485 if ( $index === NS_PROJECT_TALK
) {
486 unset( $aliases[$name] );
487 $name = $this->fixVariableInNamespace( $name );
488 $aliases[$name] = $index;
493 global $wgExtraGenderNamespaces;
494 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
495 foreach ( $genders as $index => $forms ) {
496 foreach ( $forms as $alias ) {
497 $aliases[$alias] = $index;
501 $this->namespaceAliases
= $aliases;
503 return $this->namespaceAliases
;
509 function getNamespaceIds() {
510 if ( is_null( $this->mNamespaceIds
) ) {
511 global $wgNamespaceAliases;
512 # Put namespace names and aliases into a hashtable.
513 # If this is too slow, then we should arrange it so that it is done
514 # before caching. The catch is that at pre-cache time, the above
515 # class-specific fixup hasn't been done.
516 $this->mNamespaceIds
= array();
517 foreach ( $this->getNamespaces() as $index => $name ) {
518 $this->mNamespaceIds
[$this->lc( $name )] = $index;
520 foreach ( $this->getNamespaceAliases() as $name => $index ) {
521 $this->mNamespaceIds
[$this->lc( $name )] = $index;
523 if ( $wgNamespaceAliases ) {
524 foreach ( $wgNamespaceAliases as $name => $index ) {
525 $this->mNamespaceIds
[$this->lc( $name )] = $index;
529 return $this->mNamespaceIds
;
533 * Get a namespace key by value, case insensitive. Canonical namespace
534 * names override custom ones defined for the current language.
536 * @param $text String
537 * @return mixed An integer if $text is a valid value otherwise false
539 function getNsIndex( $text ) {
540 $lctext = $this->lc( $text );
541 $ns = MWNamespace
::getCanonicalIndex( $lctext );
542 if ( $ns !== null ) {
545 $ids = $this->getNamespaceIds();
546 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
550 * short names for language variants used for language conversion links.
552 * @param $code String
553 * @param $usemsg bool Use the "variantname-xyz" message if it exists
556 function getVariantname( $code, $usemsg = true ) {
557 $msg = "variantname-$code";
558 list( $rootCode ) = explode( '-', $code );
559 if ( $usemsg && wfMessage( $msg )->exists() ) {
560 return $this->getMessageFromDB( $msg );
562 $name = self
::getLanguageName( $code );
564 return $name; # if it's defined as a language name, show that
566 # otherwise, output the language code
572 * @param $name string
575 function specialPage( $name ) {
576 $aliases = $this->getSpecialPageAliases();
577 if ( isset( $aliases[$name][0] ) ) {
578 $name = $aliases[$name][0];
580 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
586 function getQuickbarSettings() {
588 $this->getMessage( 'qbsettings-none' ),
589 $this->getMessage( 'qbsettings-fixedleft' ),
590 $this->getMessage( 'qbsettings-fixedright' ),
591 $this->getMessage( 'qbsettings-floatingleft' ),
592 $this->getMessage( 'qbsettings-floatingright' ),
593 $this->getMessage( 'qbsettings-directionality' )
600 function getDatePreferences() {
601 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
607 function getDateFormats() {
608 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
612 * @return array|string
614 function getDefaultDateFormat() {
615 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
616 if ( $df === 'dmy or mdy' ) {
617 global $wgAmericanDates;
618 return $wgAmericanDates ?
'mdy' : 'dmy';
627 function getDatePreferenceMigrationMap() {
628 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
635 function getImageFile( $image ) {
636 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
642 function getExtraUserToggles() {
643 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
650 function getUserToggle( $tog ) {
651 return $this->getMessageFromDB( "tog-$tog" );
655 * Get native language names, indexed by code.
656 * Only those defined in MediaWiki, no other data like CLDR.
657 * If $customisedOnly is true, only returns codes with a messages file
659 * @param $customisedOnly bool
662 * @deprecated in 1.20, use fetchLanguageNames()
664 public static function getLanguageNames( $customisedOnly = false ) {
665 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
669 * Get translated language names. This is done on best effort and
670 * by default this is exactly the same as Language::getLanguageNames.
671 * The CLDR extension provides translated names.
672 * @param $code String Language code.
673 * @return Array language code => language name
675 * @deprecated in 1.20, use fetchLanguageNames()
677 public static function getTranslatedLanguageNames( $code ) {
678 return self
::fetchLanguageNames( $code, 'all' );
682 * Get an array of language names, indexed by code.
683 * @param $inLanguage null|string: Code of language in which to return the names
684 * Use null for autonyms (native names)
685 * @param $include string:
686 * 'all' all available languages
687 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames
688 * 'mwfile' only if the language is in 'mw' *and* has a message file
689 * @return array|bool: language code => language name, false if $include is wrong
691 public static function fetchLanguageNames( $inLanguage = null, $include = 'all' ) {
692 global $wgExtraLanguageNames;
693 static $coreLanguageNames;
695 if ( $coreLanguageNames === null ) {
696 include( MWInit
::compiledPath( 'languages/Names.php' ) );
702 # TODO: also include when $inLanguage is null, when this code is more efficient
703 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
706 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
707 foreach ( $mwNames as $mwCode => $mwName ) {
708 # - Prefer own MediaWiki native name when not using the hook
709 # TODO: prefer it always to make it consistent, but casing is different in CLDR
710 # - For other names just add if not added through the hook
711 if ( ( $mwCode === $inLanguage && !$inLanguage ) ||
!isset( $names[$mwCode] ) ) {
712 $names[$mwCode] = $mwName;
716 if ( $include === 'all' ) {
721 $coreCodes = array_keys( $mwNames );
722 foreach( $coreCodes as $coreCode ) {
723 $returnMw[$coreCode] = $names[$coreCode];
726 if( $include === 'mw' ) {
728 } elseif( $include === 'mwfile' ) {
729 $namesMwFile = array();
730 # We do this using a foreach over the codes instead of a directory
731 # loop so that messages files in extensions will work correctly.
732 foreach ( $returnMw as $code => $value ) {
733 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
734 $namesMwFile[$code] = $names[$code];
743 * @param $code string: The code of the language for which to get the name
744 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
745 * @return string: Language name or empty
748 public static function fetchLanguageName( $code, $inLanguage = null ) {
749 $array = self
::fetchLanguageNames( $inLanguage, 'all' );
750 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
754 * Get a message from the MediaWiki namespace.
756 * @param $msg String: message name
759 function getMessageFromDB( $msg ) {
760 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
764 * Get the native language name of $code.
765 * Only if defined in MediaWiki, no other data like CLDR.
766 * @param $code string
768 * @deprecated in 1.20, use fetchLanguageName()
770 function getLanguageName( $code ) {
771 return self
::fetchLanguageName( $code );
778 function getMonthName( $key ) {
779 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
785 function getMonthNamesArray() {
786 $monthNames = array( '' );
787 for ( $i = 1; $i < 13; $i++
) {
788 $monthNames[] = $this->getMonthName( $i );
797 function getMonthNameGen( $key ) {
798 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
805 function getMonthAbbreviation( $key ) {
806 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
812 function getMonthAbbreviationsArray() {
813 $monthNames = array( '' );
814 for ( $i = 1; $i < 13; $i++
) {
815 $monthNames[] = $this->getMonthAbbreviation( $i );
824 function getWeekdayName( $key ) {
825 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
832 function getWeekdayAbbreviation( $key ) {
833 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
840 function getIranianCalendarMonthName( $key ) {
841 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
848 function getHebrewCalendarMonthName( $key ) {
849 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
856 function getHebrewCalendarMonthNameGen( $key ) {
857 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
864 function getHijriCalendarMonthName( $key ) {
865 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
869 * This is a workalike of PHP's date() function, but with better
870 * internationalisation, a reduced set of format characters, and a better
873 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
874 * PHP manual for definitions. There are a number of extensions, which
877 * xn Do not translate digits of the next numeric format character
878 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
879 * xr Use roman numerals for the next numeric format character
880 * xh Use hebrew numerals for the next numeric format character
882 * xg Genitive month name
884 * xij j (day number) in Iranian calendar
885 * xiF F (month name) in Iranian calendar
886 * xin n (month number) in Iranian calendar
887 * xiy y (two digit year) in Iranian calendar
888 * xiY Y (full year) in Iranian calendar
890 * xjj j (day number) in Hebrew calendar
891 * xjF F (month name) in Hebrew calendar
892 * xjt t (days in month) in Hebrew calendar
893 * xjx xg (genitive month name) in Hebrew calendar
894 * xjn n (month number) in Hebrew calendar
895 * xjY Y (full year) in Hebrew calendar
897 * xmj j (day number) in Hijri calendar
898 * xmF F (month name) in Hijri calendar
899 * xmn n (month number) in Hijri calendar
900 * xmY Y (full year) in Hijri calendar
902 * xkY Y (full year) in Thai solar calendar. Months and days are
903 * identical to the Gregorian calendar
904 * xoY Y (full year) in Minguo calendar or Juche year.
905 * Months and days are identical to the
907 * xtY Y (full year) in Japanese nengo. Months and days are
908 * identical to the Gregorian calendar
910 * Characters enclosed in double quotes will be considered literal (with
911 * the quotes themselves removed). Unmatched quotes will be considered
912 * literal quotes. Example:
914 * "The month is" F => The month is January
917 * Backslash escaping is also supported.
919 * Input timestamp is assumed to be pre-normalized to the desired local
922 * @param $format String
923 * @param $ts String: 14-character timestamp
926 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
930 function sprintfDate( $format, $ts ) {
943 for ( $p = 0; $p < strlen( $format ); $p++
) {
946 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
947 $code .= $format[++
$p];
950 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
951 $code .= $format[++
$p];
962 $rawToggle = !$rawToggle;
971 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
974 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
975 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
978 $num = substr( $ts, 6, 2 );
981 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
982 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
985 $num = intval( substr( $ts, 6, 2 ) );
989 $iranian = self
::tsToIranian( $ts );
995 $hijri = self
::tsToHijri( $ts );
1001 $hebrew = self
::tsToHebrew( $ts );
1007 $unix = wfTimestamp( TS_UNIX
, $ts );
1009 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1013 $unix = wfTimestamp( TS_UNIX
, $ts );
1015 $w = gmdate( 'w', $unix );
1020 $unix = wfTimestamp( TS_UNIX
, $ts );
1022 $num = gmdate( 'w', $unix );
1026 $unix = wfTimestamp( TS_UNIX
, $ts );
1028 $num = gmdate( 'z', $unix );
1032 $unix = wfTimestamp( TS_UNIX
, $ts );
1034 $num = gmdate( 'W', $unix );
1037 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1041 $iranian = self
::tsToIranian( $ts );
1043 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1047 $hijri = self
::tsToHijri( $ts );
1049 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1053 $hebrew = self
::tsToHebrew( $ts );
1055 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1058 $num = substr( $ts, 4, 2 );
1061 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1064 $num = intval( substr( $ts, 4, 2 ) );
1068 $iranian = self
::tsToIranian( $ts );
1074 $hijri = self
::tsToHijri ( $ts );
1080 $hebrew = self
::tsToHebrew( $ts );
1086 $unix = wfTimestamp( TS_UNIX
, $ts );
1088 $num = gmdate( 't', $unix );
1092 $hebrew = self
::tsToHebrew( $ts );
1098 $unix = wfTimestamp( TS_UNIX
, $ts );
1100 $num = gmdate( 'L', $unix );
1104 $unix = wfTimestamp( TS_UNIX
, $ts );
1106 $num = gmdate( 'o', $unix );
1109 $num = substr( $ts, 0, 4 );
1113 $iranian = self
::tsToIranian( $ts );
1119 $hijri = self
::tsToHijri( $ts );
1125 $hebrew = self
::tsToHebrew( $ts );
1131 $thai = self
::tsToYear( $ts, 'thai' );
1137 $minguo = self
::tsToYear( $ts, 'minguo' );
1143 $tenno = self
::tsToYear( $ts, 'tenno' );
1148 $num = substr( $ts, 2, 2 );
1152 $iranian = self
::tsToIranian( $ts );
1154 $num = substr( $iranian[0], -2 );
1157 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1160 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1163 $h = substr( $ts, 8, 2 );
1164 $num = $h %
12 ?
$h %
12 : 12;
1167 $num = intval( substr( $ts, 8, 2 ) );
1170 $h = substr( $ts, 8, 2 );
1171 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1174 $num = substr( $ts, 8, 2 );
1177 $num = substr( $ts, 10, 2 );
1180 $num = substr( $ts, 12, 2 );
1184 $unix = wfTimestamp( TS_UNIX
, $ts );
1186 $s .= gmdate( 'c', $unix );
1190 $unix = wfTimestamp( TS_UNIX
, $ts );
1192 $s .= gmdate( 'r', $unix );
1196 $unix = wfTimestamp( TS_UNIX
, $ts );
1201 # Backslash escaping
1202 if ( $p < strlen( $format ) - 1 ) {
1203 $s .= $format[++
$p];
1210 if ( $p < strlen( $format ) - 1 ) {
1211 $endQuote = strpos( $format, '"', $p +
1 );
1212 if ( $endQuote === false ) {
1213 # No terminating quote, assume literal "
1216 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1220 # Quote at end of string, assume literal "
1227 if ( $num !== false ) {
1228 if ( $rawToggle ||
$raw ) {
1231 } elseif ( $roman ) {
1232 $s .= self
::romanNumeral( $num );
1234 } elseif ( $hebrewNum ) {
1235 $s .= self
::hebrewNumeral( $num );
1238 $s .= $this->formatNum( $num, true );
1245 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1246 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1249 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1250 * Gregorian dates to Iranian dates. Originally written in C, it
1251 * is released under the terms of GNU Lesser General Public
1252 * License. Conversion to PHP was performed by Niklas Laxström.
1254 * Link: http://www.farsiweb.info/jalali/jalali.c
1260 private static function tsToIranian( $ts ) {
1261 $gy = substr( $ts, 0, 4 ) -1600;
1262 $gm = substr( $ts, 4, 2 ) -1;
1263 $gd = substr( $ts, 6, 2 ) -1;
1265 # Days passed from the beginning (including leap years)
1267 +
floor( ( $gy +
3 ) / 4 )
1268 - floor( ( $gy +
99 ) / 100 )
1269 +
floor( ( $gy +
399 ) / 400 );
1271 // Add days of the past months of this year
1272 for ( $i = 0; $i < $gm; $i++
) {
1273 $gDayNo +
= self
::$GREG_DAYS[$i];
1277 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1281 // Days passed in current month
1282 $gDayNo +
= (int)$gd;
1284 $jDayNo = $gDayNo - 79;
1286 $jNp = floor( $jDayNo / 12053 );
1289 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1292 if ( $jDayNo >= 366 ) {
1293 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1294 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1297 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1298 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1304 return array( $jy, $jm, $jd );
1308 * Converting Gregorian dates to Hijri dates.
1310 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1312 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1318 private static function tsToHijri( $ts ) {
1319 $year = substr( $ts, 0, 4 );
1320 $month = substr( $ts, 4, 2 );
1321 $day = substr( $ts, 6, 2 );
1329 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1330 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1333 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1334 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1335 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1338 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1339 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1342 $zl = $zjd -1948440 +
10632;
1343 $zn = (int)( ( $zl - 1 ) / 10631 );
1344 $zl = $zl - 10631 * $zn +
354;
1345 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1346 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1347 $zm = (int)( ( 24 * $zl ) / 709 );
1348 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1349 $zy = 30 * $zn +
$zj - 30;
1351 return array( $zy, $zm, $zd );
1355 * Converting Gregorian dates to Hebrew dates.
1357 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1358 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1359 * to translate the relevant functions into PHP and release them under
1362 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1363 * and Adar II is 14. In a non-leap year, Adar is 6.
1369 private static function tsToHebrew( $ts ) {
1371 $year = substr( $ts, 0, 4 );
1372 $month = substr( $ts, 4, 2 );
1373 $day = substr( $ts, 6, 2 );
1375 # Calculate Hebrew year
1376 $hebrewYear = $year +
3760;
1378 # Month number when September = 1, August = 12
1380 if ( $month > 12 ) {
1387 # Calculate day of year from 1 September
1389 for ( $i = 1; $i < $month; $i++
) {
1393 # Check if the year is leap
1394 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1397 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1404 # Calculate the start of the Hebrew year
1405 $start = self
::hebrewYearStart( $hebrewYear );
1407 # Calculate next year's start
1408 if ( $dayOfYear <= $start ) {
1409 # Day is before the start of the year - it is the previous year
1411 $nextStart = $start;
1415 # Add days since previous year's 1 September
1417 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1421 # Start of the new (previous) year
1422 $start = self
::hebrewYearStart( $hebrewYear );
1425 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1428 # Calculate Hebrew day of year
1429 $hebrewDayOfYear = $dayOfYear - $start;
1431 # Difference between year's days
1432 $diff = $nextStart - $start;
1433 # Add 12 (or 13 for leap years) days to ignore the difference between
1434 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1435 # difference is only about the year type
1436 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1442 # Check the year pattern, and is leap year
1443 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1444 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1445 # and non-leap years
1446 $yearPattern = $diff %
30;
1447 # Check if leap year
1448 $isLeap = $diff >= 30;
1450 # Calculate day in the month from number of day in the Hebrew year
1451 # Don't check Adar - if the day is not in Adar, we will stop before;
1452 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1453 $hebrewDay = $hebrewDayOfYear;
1456 while ( $hebrewMonth <= 12 ) {
1457 # Calculate days in this month
1458 if ( $isLeap && $hebrewMonth == 6 ) {
1459 # Adar in a leap year
1461 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1463 if ( $hebrewDay <= $days ) {
1467 # Subtract the days of Adar I
1468 $hebrewDay -= $days;
1471 if ( $hebrewDay <= $days ) {
1477 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1478 # Cheshvan in a complete year (otherwise as the rule below)
1480 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1481 # Kislev in an incomplete year (otherwise as the rule below)
1484 # Odd months have 30 days, even have 29
1485 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1487 if ( $hebrewDay <= $days ) {
1488 # In the current month
1491 # Subtract the days of the current month
1492 $hebrewDay -= $days;
1493 # Try in the next month
1498 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1502 * This calculates the Hebrew year start, as days since 1 September.
1503 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1504 * Used for Hebrew date.
1510 private static function hebrewYearStart( $year ) {
1511 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1512 $b = intval( ( $year - 1 ) %
4 );
1513 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1517 $Mar = intval( $m );
1523 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1524 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1526 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1528 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1532 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1537 * Algorithm to convert Gregorian dates to Thai solar dates,
1538 * Minguo dates or Minguo dates.
1540 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1541 * http://en.wikipedia.org/wiki/Minguo_calendar
1542 * http://en.wikipedia.org/wiki/Japanese_era_name
1544 * @param $ts String: 14-character timestamp
1545 * @param $cName String: calender name
1546 * @return Array: converted year, month, day
1548 private static function tsToYear( $ts, $cName ) {
1549 $gy = substr( $ts, 0, 4 );
1550 $gm = substr( $ts, 4, 2 );
1551 $gd = substr( $ts, 6, 2 );
1553 if ( !strcmp( $cName, 'thai' ) ) {
1555 # Add 543 years to the Gregorian calendar
1556 # Months and days are identical
1557 $gy_offset = $gy +
543;
1558 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1560 # Deduct 1911 years from the Gregorian calendar
1561 # Months and days are identical
1562 $gy_offset = $gy - 1911;
1563 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1564 # Nengō dates up to Meiji period
1565 # Deduct years from the Gregorian calendar
1566 # depending on the nengo periods
1567 # Months and days are identical
1568 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1570 $gy_gannen = $gy - 1868 +
1;
1571 $gy_offset = $gy_gannen;
1572 if ( $gy_gannen == 1 ) {
1575 $gy_offset = '明治' . $gy_offset;
1577 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1578 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1579 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1580 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1581 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1585 $gy_gannen = $gy - 1912 +
1;
1586 $gy_offset = $gy_gannen;
1587 if ( $gy_gannen == 1 ) {
1590 $gy_offset = '大正' . $gy_offset;
1592 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1593 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1594 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1598 $gy_gannen = $gy - 1926 +
1;
1599 $gy_offset = $gy_gannen;
1600 if ( $gy_gannen == 1 ) {
1603 $gy_offset = '昭和' . $gy_offset;
1606 $gy_gannen = $gy - 1989 +
1;
1607 $gy_offset = $gy_gannen;
1608 if ( $gy_gannen == 1 ) {
1611 $gy_offset = '平成' . $gy_offset;
1617 return array( $gy_offset, $gm, $gd );
1621 * Roman number formatting up to 3000
1627 static function romanNumeral( $num ) {
1628 static $table = array(
1629 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1630 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1631 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1632 array( '', 'M', 'MM', 'MMM' )
1635 $num = intval( $num );
1636 if ( $num > 3000 ||
$num <= 0 ) {
1641 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1642 if ( $num >= $pow10 ) {
1643 $s .= $table[$i][(int)floor( $num / $pow10 )];
1645 $num = $num %
$pow10;
1651 * Hebrew Gematria number formatting up to 9999
1657 static function hebrewNumeral( $num ) {
1658 static $table = array(
1659 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1660 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1661 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1662 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1665 $num = intval( $num );
1666 if ( $num > 9999 ||
$num <= 0 ) {
1671 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1672 if ( $num >= $pow10 ) {
1673 if ( $num == 15 ||
$num == 16 ) {
1674 $s .= $table[0][9] . $table[0][$num - 9];
1677 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1678 if ( $pow10 == 1000 ) {
1683 $num = $num %
$pow10;
1685 if ( strlen( $s ) == 2 ) {
1688 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1689 $str .= substr( $s, strlen( $s ) - 2, 2 );
1691 $start = substr( $str, 0, strlen( $str ) - 2 );
1692 $end = substr( $str, strlen( $str ) - 2 );
1695 $str = $start . 'ך';
1698 $str = $start . 'ם';
1701 $str = $start . 'ן';
1704 $str = $start . 'ף';
1707 $str = $start . 'ץ';
1714 * Used by date() and time() to adjust the time output.
1716 * @param $ts Int the time in date('YmdHis') format
1717 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1718 * get user timecorrection setting)
1721 function userAdjust( $ts, $tz = false ) {
1722 global $wgUser, $wgLocalTZoffset;
1724 if ( $tz === false ) {
1725 $tz = $wgUser->getOption( 'timecorrection' );
1728 $data = explode( '|', $tz, 3 );
1730 if ( $data[0] == 'ZoneInfo' ) {
1731 wfSuppressWarnings();
1732 $userTZ = timezone_open( $data[2] );
1733 wfRestoreWarnings();
1734 if ( $userTZ !== false ) {
1735 $date = date_create( $ts, timezone_open( 'UTC' ) );
1736 date_timezone_set( $date, $userTZ );
1737 $date = date_format( $date, 'YmdHis' );
1740 # Unrecognized timezone, default to 'Offset' with the stored offset.
1741 $data[0] = 'Offset';
1745 if ( $data[0] == 'System' ||
$tz == '' ) {
1746 # Global offset in minutes.
1747 if ( isset( $wgLocalTZoffset ) ) {
1748 $minDiff = $wgLocalTZoffset;
1750 } elseif ( $data[0] == 'Offset' ) {
1751 $minDiff = intval( $data[1] );
1753 $data = explode( ':', $tz );
1754 if ( count( $data ) == 2 ) {
1755 $data[0] = intval( $data[0] );
1756 $data[1] = intval( $data[1] );
1757 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1758 if ( $data[0] < 0 ) {
1759 $minDiff = -$minDiff;
1762 $minDiff = intval( $data[0] ) * 60;
1766 # No difference ? Return time unchanged
1767 if ( 0 == $minDiff ) {
1771 wfSuppressWarnings(); // E_STRICT system time bitching
1772 # Generate an adjusted date; take advantage of the fact that mktime
1773 # will normalize out-of-range values so we don't have to split $minDiff
1774 # into hours and minutes.
1776 (int)substr( $ts, 8, 2 ) ), # Hours
1777 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1778 (int)substr( $ts, 12, 2 ), # Seconds
1779 (int)substr( $ts, 4, 2 ), # Month
1780 (int)substr( $ts, 6, 2 ), # Day
1781 (int)substr( $ts, 0, 4 ) ); # Year
1783 $date = date( 'YmdHis', $t );
1784 wfRestoreWarnings();
1790 * This is meant to be used by time(), date(), and timeanddate() to get
1791 * the date preference they're supposed to use, it should be used in
1795 * function timeanddate([...], $format = true) {
1796 * $datePreference = $this->dateFormat($format);
1801 * @param $usePrefs Mixed: if true, the user's preference is used
1802 * if false, the site/language default is used
1803 * if int/string, assumed to be a format.
1806 function dateFormat( $usePrefs = true ) {
1809 if ( is_bool( $usePrefs ) ) {
1811 $datePreference = $wgUser->getDatePreference();
1813 $datePreference = (string)User
::getDefaultOption( 'date' );
1816 $datePreference = (string)$usePrefs;
1820 if ( $datePreference == '' ) {
1824 return $datePreference;
1828 * Get a format string for a given type and preference
1829 * @param $type string May be date, time or both
1830 * @param $pref string The format name as it appears in Messages*.php
1834 function getDateFormatString( $type, $pref ) {
1835 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1836 if ( $pref == 'default' ) {
1837 $pref = $this->getDefaultDateFormat();
1838 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1840 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1841 if ( is_null( $df ) ) {
1842 $pref = $this->getDefaultDateFormat();
1843 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1846 $this->dateFormatStrings
[$type][$pref] = $df;
1848 return $this->dateFormatStrings
[$type][$pref];
1852 * @param $ts Mixed: the time format which needs to be turned into a
1853 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1854 * @param $adj Bool: whether to adjust the time output according to the
1855 * user configured offset ($timecorrection)
1856 * @param $format Mixed: true to use user's date format preference
1857 * @param $timecorrection String|bool the time offset as returned by
1858 * validateTimeZone() in Special:Preferences
1861 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1862 $ts = wfTimestamp( TS_MW
, $ts );
1864 $ts = $this->userAdjust( $ts, $timecorrection );
1866 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1867 return $this->sprintfDate( $df, $ts );
1871 * @param $ts Mixed: the time format which needs to be turned into a
1872 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1873 * @param $adj Bool: whether to adjust the time output according to the
1874 * user configured offset ($timecorrection)
1875 * @param $format Mixed: true to use user's date format preference
1876 * @param $timecorrection String|bool the time offset as returned by
1877 * validateTimeZone() in Special:Preferences
1880 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1881 $ts = wfTimestamp( TS_MW
, $ts );
1883 $ts = $this->userAdjust( $ts, $timecorrection );
1885 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1886 return $this->sprintfDate( $df, $ts );
1890 * @param $ts Mixed: the time format which needs to be turned into a
1891 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1892 * @param $adj Bool: whether to adjust the time output according to the
1893 * user configured offset ($timecorrection)
1894 * @param $format Mixed: what format to return, if it's false output the
1895 * default one (default true)
1896 * @param $timecorrection String|bool the time offset as returned by
1897 * validateTimeZone() in Special:Preferences
1900 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1901 $ts = wfTimestamp( TS_MW
, $ts );
1903 $ts = $this->userAdjust( $ts, $timecorrection );
1905 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1906 return $this->sprintfDate( $df, $ts );
1910 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1912 * @param $type String: can be 'date', 'time' or 'both'
1913 * @param $ts Mixed: the time format which needs to be turned into a
1914 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1915 * @param $user User object used to get preferences for timezone and format
1916 * @param $options Array, can contain the following keys:
1917 * - 'timecorrection': time correction, can have the following values:
1918 * - true: use user's preference
1919 * - false: don't use time correction
1920 * - integer: value of time correction in minutes
1921 * - 'format': format to use, can have the following values:
1922 * - true: use user's preference
1923 * - false: use default preference
1924 * - string: format to use
1928 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1929 $ts = wfTimestamp( TS_MW
, $ts );
1930 $options +
= array( 'timecorrection' => true, 'format' => true );
1931 if ( $options['timecorrection'] !== false ) {
1932 if ( $options['timecorrection'] === true ) {
1933 $offset = $user->getOption( 'timecorrection' );
1935 $offset = $options['timecorrection'];
1937 $ts = $this->userAdjust( $ts, $offset );
1939 if ( $options['format'] === true ) {
1940 $format = $user->getDatePreference();
1942 $format = $options['format'];
1944 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1945 return $this->sprintfDate( $df, $ts );
1949 * Get the formatted date for the given timestamp and formatted for
1952 * @param $ts Mixed: the time format which needs to be turned into a
1953 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1954 * @param $user User object used to get preferences for timezone and format
1955 * @param $options Array, can contain the following keys:
1956 * - 'timecorrection': time correction, can have the following values:
1957 * - true: use user's preference
1958 * - false: don't use time correction
1959 * - integer: value of time correction in minutes
1960 * - 'format': format to use, can have the following values:
1961 * - true: use user's preference
1962 * - false: use default preference
1963 * - string: format to use
1967 public function userDate( $ts, User
$user, array $options = array() ) {
1968 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1972 * Get the formatted time for the given timestamp and formatted for
1975 * @param $ts Mixed: the time format which needs to be turned into a
1976 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1977 * @param $user User object used to get preferences for timezone and format
1978 * @param $options Array, can contain the following keys:
1979 * - 'timecorrection': time correction, can have the following values:
1980 * - true: use user's preference
1981 * - false: don't use time correction
1982 * - integer: value of time correction in minutes
1983 * - 'format': format to use, can have the following values:
1984 * - true: use user's preference
1985 * - false: use default preference
1986 * - string: format to use
1990 public function userTime( $ts, User
$user, array $options = array() ) {
1991 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1995 * Get the formatted date and time for the given timestamp and formatted for
1998 * @param $ts Mixed: the time format which needs to be turned into a
1999 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2000 * @param $user User object used to get preferences for timezone and format
2001 * @param $options Array, can contain the following keys:
2002 * - 'timecorrection': time correction, can have the following values:
2003 * - true: use user's preference
2004 * - false: don't use time correction
2005 * - integer: value of time correction in minutes
2006 * - 'format': format to use, can have the following values:
2007 * - true: use user's preference
2008 * - false: use default preference
2009 * - string: format to use
2013 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2014 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2018 * @param $key string
2019 * @return array|null
2021 function getMessage( $key ) {
2022 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2028 function getAllMessages() {
2029 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2038 function iconv( $in, $out, $string ) {
2039 # This is a wrapper for iconv in all languages except esperanto,
2040 # which does some nasty x-conversions beforehand
2042 # Even with //IGNORE iconv can whine about illegal characters in
2043 # *input* string. We just ignore those too.
2044 # REF: http://bugs.php.net/bug.php?id=37166
2045 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2046 wfSuppressWarnings();
2047 $text = iconv( $in, $out . '//IGNORE', $string );
2048 wfRestoreWarnings();
2052 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2055 * @param $matches array
2056 * @return mixed|string
2058 function ucwordbreaksCallbackAscii( $matches ) {
2059 return $this->ucfirst( $matches[1] );
2063 * @param $matches array
2066 function ucwordbreaksCallbackMB( $matches ) {
2067 return mb_strtoupper( $matches[0] );
2071 * @param $matches array
2074 function ucCallback( $matches ) {
2075 list( $wikiUpperChars ) = self
::getCaseMaps();
2076 return strtr( $matches[1], $wikiUpperChars );
2080 * @param $matches array
2083 function lcCallback( $matches ) {
2084 list( , $wikiLowerChars ) = self
::getCaseMaps();
2085 return strtr( $matches[1], $wikiLowerChars );
2089 * @param $matches array
2092 function ucwordsCallbackMB( $matches ) {
2093 return mb_strtoupper( $matches[0] );
2097 * @param $matches array
2100 function ucwordsCallbackWiki( $matches ) {
2101 list( $wikiUpperChars ) = self
::getCaseMaps();
2102 return strtr( $matches[0], $wikiUpperChars );
2106 * Make a string's first character uppercase
2108 * @param $str string
2112 function ucfirst( $str ) {
2114 if ( $o < 96 ) { // if already uppercase...
2116 } elseif ( $o < 128 ) {
2117 return ucfirst( $str ); // use PHP's ucfirst()
2119 // fall back to more complex logic in case of multibyte strings
2120 return $this->uc( $str, true );
2125 * Convert a string to uppercase
2127 * @param $str string
2128 * @param $first bool
2132 function uc( $str, $first = false ) {
2133 if ( function_exists( 'mb_strtoupper' ) ) {
2135 if ( $this->isMultibyte( $str ) ) {
2136 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2138 return ucfirst( $str );
2141 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2144 if ( $this->isMultibyte( $str ) ) {
2145 $x = $first ?
'^' : '';
2146 return preg_replace_callback(
2147 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2148 array( $this, 'ucCallback' ),
2152 return $first ?
ucfirst( $str ) : strtoupper( $str );
2158 * @param $str string
2159 * @return mixed|string
2161 function lcfirst( $str ) {
2164 return strval( $str );
2165 } elseif ( $o >= 128 ) {
2166 return $this->lc( $str, true );
2167 } elseif ( $o > 96 ) {
2170 $str[0] = strtolower( $str[0] );
2176 * @param $str string
2177 * @param $first bool
2178 * @return mixed|string
2180 function lc( $str, $first = false ) {
2181 if ( function_exists( 'mb_strtolower' ) ) {
2183 if ( $this->isMultibyte( $str ) ) {
2184 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2186 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2189 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2192 if ( $this->isMultibyte( $str ) ) {
2193 $x = $first ?
'^' : '';
2194 return preg_replace_callback(
2195 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2196 array( $this, 'lcCallback' ),
2200 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2206 * @param $str string
2209 function isMultibyte( $str ) {
2210 return (bool)preg_match( '/[\x80-\xff]/', $str );
2214 * @param $str string
2215 * @return mixed|string
2217 function ucwords( $str ) {
2218 if ( $this->isMultibyte( $str ) ) {
2219 $str = $this->lc( $str );
2221 // regexp to find first letter in each word (i.e. after each space)
2222 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2224 // function to use to capitalize a single char
2225 if ( function_exists( 'mb_strtoupper' ) ) {
2226 return preg_replace_callback(
2228 array( $this, 'ucwordsCallbackMB' ),
2232 return preg_replace_callback(
2234 array( $this, 'ucwordsCallbackWiki' ),
2239 return ucwords( strtolower( $str ) );
2244 * capitalize words at word breaks
2246 * @param $str string
2249 function ucwordbreaks( $str ) {
2250 if ( $this->isMultibyte( $str ) ) {
2251 $str = $this->lc( $str );
2253 // since \b doesn't work for UTF-8, we explicitely define word break chars
2254 $breaks = "[ \-\(\)\}\{\.,\?!]";
2256 // find first letter after word break
2257 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2259 if ( function_exists( 'mb_strtoupper' ) ) {
2260 return preg_replace_callback(
2262 array( $this, 'ucwordbreaksCallbackMB' ),
2266 return preg_replace_callback(
2268 array( $this, 'ucwordsCallbackWiki' ),
2273 return preg_replace_callback(
2274 '/\b([\w\x80-\xff]+)\b/',
2275 array( $this, 'ucwordbreaksCallbackAscii' ),
2282 * Return a case-folded representation of $s
2284 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2285 * and $s2 are the same except for the case of their characters. It is not
2286 * necessary for the value returned to make sense when displayed.
2288 * Do *not* perform any other normalisation in this function. If a caller
2289 * uses this function when it should be using a more general normalisation
2290 * function, then fix the caller.
2296 function caseFold( $s ) {
2297 return $this->uc( $s );
2304 function checkTitleEncoding( $s ) {
2305 if ( is_array( $s ) ) {
2306 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2308 # Check for non-UTF-8 URLs
2309 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2314 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2315 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2320 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2326 function fallback8bitEncoding() {
2327 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2331 * Most writing systems use whitespace to break up words.
2332 * Some languages such as Chinese don't conventionally do this,
2333 * which requires special handling when breaking up words for
2338 function hasWordBreaks() {
2343 * Some languages such as Chinese require word segmentation,
2344 * Specify such segmentation when overridden in derived class.
2346 * @param $string String
2349 function segmentByWord( $string ) {
2354 * Some languages have special punctuation need to be normalized.
2355 * Make such changes here.
2357 * @param $string String
2360 function normalizeForSearch( $string ) {
2361 return self
::convertDoubleWidth( $string );
2365 * convert double-width roman characters to single-width.
2366 * range: ff00-ff5f ~= 0020-007f
2368 * @param $string string
2372 protected static function convertDoubleWidth( $string ) {
2373 static $full = null;
2374 static $half = null;
2376 if ( $full === null ) {
2377 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2378 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2379 $full = str_split( $fullWidth, 3 );
2380 $half = str_split( $halfWidth );
2383 $string = str_replace( $full, $half, $string );
2388 * @param $string string
2389 * @param $pattern string
2392 protected static function insertSpace( $string, $pattern ) {
2393 $string = preg_replace( $pattern, " $1 ", $string );
2394 $string = preg_replace( '/ +/', ' ', $string );
2399 * @param $termsArray array
2402 function convertForSearchResult( $termsArray ) {
2403 # some languages, e.g. Chinese, need to do a conversion
2404 # in order for search results to be displayed correctly
2409 * Get the first character of a string.
2414 function firstChar( $s ) {
2417 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2418 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2423 if ( isset( $matches[1] ) ) {
2424 if ( strlen( $matches[1] ) != 3 ) {
2428 // Break down Hangul syllables to grab the first jamo
2429 $code = utf8ToCodepoint( $matches[1] );
2430 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2432 } elseif ( $code < 0xb098 ) {
2433 return "\xe3\x84\xb1";
2434 } elseif ( $code < 0xb2e4 ) {
2435 return "\xe3\x84\xb4";
2436 } elseif ( $code < 0xb77c ) {
2437 return "\xe3\x84\xb7";
2438 } elseif ( $code < 0xb9c8 ) {
2439 return "\xe3\x84\xb9";
2440 } elseif ( $code < 0xbc14 ) {
2441 return "\xe3\x85\x81";
2442 } elseif ( $code < 0xc0ac ) {
2443 return "\xe3\x85\x82";
2444 } elseif ( $code < 0xc544 ) {
2445 return "\xe3\x85\x85";
2446 } elseif ( $code < 0xc790 ) {
2447 return "\xe3\x85\x87";
2448 } elseif ( $code < 0xcc28 ) {
2449 return "\xe3\x85\x88";
2450 } elseif ( $code < 0xce74 ) {
2451 return "\xe3\x85\x8a";
2452 } elseif ( $code < 0xd0c0 ) {
2453 return "\xe3\x85\x8b";
2454 } elseif ( $code < 0xd30c ) {
2455 return "\xe3\x85\x8c";
2456 } elseif ( $code < 0xd558 ) {
2457 return "\xe3\x85\x8d";
2459 return "\xe3\x85\x8e";
2466 function initEncoding() {
2467 # Some languages may have an alternate char encoding option
2468 # (Esperanto X-coding, Japanese furigana conversion, etc)
2469 # If this language is used as the primary content language,
2470 # an override to the defaults can be set here on startup.
2477 function recodeForEdit( $s ) {
2478 # For some languages we'll want to explicitly specify
2479 # which characters make it into the edit box raw
2480 # or are converted in some way or another.
2481 global $wgEditEncoding;
2482 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2485 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2493 function recodeInput( $s ) {
2494 # Take the previous into account.
2495 global $wgEditEncoding;
2496 if ( $wgEditEncoding != '' ) {
2497 $enc = $wgEditEncoding;
2501 if ( $enc == 'UTF-8' ) {
2504 return $this->iconv( $enc, 'UTF-8', $s );
2509 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2510 * also cleans up certain backwards-compatible sequences, converting them
2511 * to the modern Unicode equivalent.
2513 * This is language-specific for performance reasons only.
2519 function normalize( $s ) {
2520 global $wgAllUnicodeFixes;
2521 $s = UtfNormal
::cleanUp( $s );
2522 if ( $wgAllUnicodeFixes ) {
2523 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2524 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2531 * Transform a string using serialized data stored in the given file (which
2532 * must be in the serialized subdirectory of $IP). The file contains pairs
2533 * mapping source characters to destination characters.
2535 * The data is cached in process memory. This will go faster if you have the
2536 * FastStringSearch extension.
2538 * @param $file string
2539 * @param $string string
2543 function transformUsingPairFile( $file, $string ) {
2544 if ( !isset( $this->transformData
[$file] ) ) {
2545 $data = wfGetPrecompiledData( $file );
2546 if ( $data === false ) {
2547 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2549 $this->transformData
[$file] = new ReplacementArray( $data );
2551 return $this->transformData
[$file]->replace( $string );
2555 * For right-to-left language support
2560 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2564 * Return the correct HTML 'dir' attribute value for this language.
2568 return $this->isRTL() ?
'rtl' : 'ltr';
2572 * Return 'left' or 'right' as appropriate alignment for line-start
2573 * for this language's text direction.
2575 * Should be equivalent to CSS3 'start' text-align value....
2579 function alignStart() {
2580 return $this->isRTL() ?
'right' : 'left';
2584 * Return 'right' or 'left' as appropriate alignment for line-end
2585 * for this language's text direction.
2587 * Should be equivalent to CSS3 'end' text-align value....
2591 function alignEnd() {
2592 return $this->isRTL() ?
'left' : 'right';
2596 * A hidden direction mark (LRM or RLM), depending on the language direction
2598 * @param $opposite Boolean Get the direction mark opposite to your language
2601 function getDirMark( $opposite = false ) {
2602 $rtl = "\xE2\x80\x8F";
2603 $ltr = "\xE2\x80\x8E";
2604 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2605 return $this->isRTL() ?
$rtl : $ltr;
2611 function capitalizeAllNouns() {
2612 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2616 * An arrow, depending on the language direction
2620 function getArrow() {
2621 return $this->isRTL() ?
'←' : '→';
2625 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2629 function linkPrefixExtension() {
2630 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2636 function getMagicWords() {
2637 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2640 protected function doMagicHook() {
2641 if ( $this->mMagicHookDone
) {
2644 $this->mMagicHookDone
= true;
2645 wfProfileIn( 'LanguageGetMagic' );
2646 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2647 wfProfileOut( 'LanguageGetMagic' );
2651 * Fill a MagicWord object with data from here
2655 function getMagic( $mw ) {
2656 $this->doMagicHook();
2658 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2659 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2661 $magicWords = $this->getMagicWords();
2662 if ( isset( $magicWords[$mw->mId
] ) ) {
2663 $rawEntry = $magicWords[$mw->mId
];
2669 if ( !is_array( $rawEntry ) ) {
2670 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2672 $mw->mCaseSensitive
= $rawEntry[0];
2673 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2678 * Add magic words to the extension array
2680 * @param $newWords array
2682 function addMagicWordsByLang( $newWords ) {
2683 $fallbackChain = $this->getFallbackLanguages();
2684 $fallbackChain = array_reverse( $fallbackChain );
2685 foreach ( $fallbackChain as $code ) {
2686 if ( isset( $newWords[$code] ) ) {
2687 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2693 * Get special page names, as an associative array
2694 * case folded alias => real name
2696 function getSpecialPageAliases() {
2697 // Cache aliases because it may be slow to load them
2698 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2700 $this->mExtendedSpecialPageAliases
=
2701 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2702 wfRunHooks( 'LanguageGetSpecialPageAliases',
2703 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2706 return $this->mExtendedSpecialPageAliases
;
2710 * Italic is unsuitable for some languages
2712 * @param $text String: the text to be emphasized.
2715 function emphasize( $text ) {
2716 return "<em>$text</em>";
2720 * Normally we output all numbers in plain en_US style, that is
2721 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2722 * point twohundredthirtyfive. However this is not suitable for all
2723 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2724 * Icelandic just want to use commas instead of dots, and dots instead
2725 * of commas like "293.291,235".
2727 * An example of this function being called:
2729 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2732 * See LanguageGu.php for the Gujarati implementation and
2733 * $separatorTransformTable on MessageIs.php for
2734 * the , => . and . => , implementation.
2736 * @todo check if it's viable to use localeconv() for the decimal
2738 * @param $number Mixed: the string to be formatted, should be an integer
2739 * or a floating point number.
2740 * @param $nocommafy Bool: set to true for special numbers like dates
2743 public function formatNum( $number, $nocommafy = false ) {
2744 global $wgTranslateNumerals;
2745 if ( !$nocommafy ) {
2746 $number = $this->commafy( $number );
2747 $s = $this->separatorTransformTable();
2749 $number = strtr( $number, $s );
2753 if ( $wgTranslateNumerals ) {
2754 $s = $this->digitTransformTable();
2756 $number = strtr( $number, $s );
2764 * @param $number string
2767 function parseFormattedNumber( $number ) {
2768 $s = $this->digitTransformTable();
2770 $number = strtr( $number, array_flip( $s ) );
2773 $s = $this->separatorTransformTable();
2775 $number = strtr( $number, array_flip( $s ) );
2778 $number = strtr( $number, array( ',' => '' ) );
2783 * Adds commas to a given number
2788 function commafy( $_ ) {
2789 $digitGroupingPattern = $this->digitGroupingPattern();
2790 if ( $_ === null ) {
2794 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2795 // default grouping is at thousands, use the same for ###,###,### pattern too.
2796 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2798 // Ref: http://cldr.unicode.org/translation/number-patterns
2800 if ( intval( $_ ) < 0 ) {
2801 // For negative numbers apply the algorithm like positive number and add sign.
2803 $_ = substr( $_, 1 );
2805 $numberpart = array();
2806 $decimalpart = array();
2807 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2808 preg_match( "/\d+/", $_, $numberpart );
2809 preg_match( "/\.\d*/", $_, $decimalpart );
2810 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2811 if ( $groupedNumber === $_ ) {
2812 // the string does not have any number part. Eg: .12345
2813 return $sign . $groupedNumber;
2815 $start = $end = strlen( $numberpart[0] );
2816 while ( $start > 0 ) {
2817 $match = $matches[0][$numMatches -1] ;
2818 $matchLen = strlen( $match );
2819 $start = $end - $matchLen;
2823 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2825 if ( $numMatches > 1 ) {
2826 // use the last pattern for the rest of the number
2830 $groupedNumber = "," . $groupedNumber;
2833 return $sign . $groupedNumber;
2839 function digitGroupingPattern() {
2840 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2846 function digitTransformTable() {
2847 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2853 function separatorTransformTable() {
2854 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2858 * Take a list of strings and build a locale-friendly comma-separated
2859 * list, using the local comma-separator message.
2860 * The last two strings are chained with an "and".
2865 function listToText( array $l ) {
2867 $m = count( $l ) - 1;
2869 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2871 for ( $i = $m; $i >= 0; $i-- ) {
2874 } elseif ( $i == $m - 1 ) {
2875 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2877 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2885 * Take a list of strings and build a locale-friendly comma-separated
2886 * list, using the local comma-separator message.
2887 * @param $list array of strings to put in a comma list
2890 function commaList( array $list ) {
2894 array( 'parsemag', 'escapenoentities', 'language' => $this )
2901 * Take a list of strings and build a locale-friendly semicolon-separated
2902 * list, using the local semicolon-separator message.
2903 * @param $list array of strings to put in a semicolon list
2906 function semicolonList( array $list ) {
2909 'semicolon-separator',
2910 array( 'parsemag', 'escapenoentities', 'language' => $this )
2917 * Same as commaList, but separate it with the pipe instead.
2918 * @param $list array of strings to put in a pipe list
2921 function pipeList( array $list ) {
2925 array( 'escapenoentities', 'language' => $this )
2932 * Truncate a string to a specified length in bytes, appending an optional
2933 * string (e.g. for ellipses)
2935 * The database offers limited byte lengths for some columns in the database;
2936 * multi-byte character sets mean we need to ensure that only whole characters
2937 * are included, otherwise broken characters can be passed to the user
2939 * If $length is negative, the string will be truncated from the beginning
2941 * @param $string String to truncate
2942 * @param $length Int: maximum length (including ellipses)
2943 * @param $ellipsis String to append to the truncated text
2944 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2945 * $adjustLength was introduced in 1.18, before that behaved as if false.
2948 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2949 # Use the localized ellipsis character
2950 if ( $ellipsis == '...' ) {
2951 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2953 # Check if there is no need to truncate
2954 if ( $length == 0 ) {
2955 return $ellipsis; // convention
2956 } elseif ( strlen( $string ) <= abs( $length ) ) {
2957 return $string; // no need to truncate
2959 $stringOriginal = $string;
2960 # If ellipsis length is >= $length then we can't apply $adjustLength
2961 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2962 $string = $ellipsis; // this can be slightly unexpected
2963 # Otherwise, truncate and add ellipsis...
2965 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2966 if ( $length > 0 ) {
2967 $length -= $eLength;
2968 $string = substr( $string, 0, $length ); // xyz...
2969 $string = $this->removeBadCharLast( $string );
2970 $string = $string . $ellipsis;
2972 $length +
= $eLength;
2973 $string = substr( $string, $length ); // ...xyz
2974 $string = $this->removeBadCharFirst( $string );
2975 $string = $ellipsis . $string;
2978 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2979 # This check is *not* redundant if $adjustLength, due to the single case where
2980 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2981 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2984 return $stringOriginal;
2989 * Remove bytes that represent an incomplete Unicode character
2990 * at the end of string (e.g. bytes of the char are missing)
2992 * @param $string String
2995 protected function removeBadCharLast( $string ) {
2996 if ( $string != '' ) {
2997 $char = ord( $string[strlen( $string ) - 1] );
2999 if ( $char >= 0xc0 ) {
3000 # We got the first byte only of a multibyte char; remove it.
3001 $string = substr( $string, 0, -1 );
3002 } elseif ( $char >= 0x80 &&
3003 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3004 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3006 # We chopped in the middle of a character; remove it
3014 * Remove bytes that represent an incomplete Unicode character
3015 * at the start of string (e.g. bytes of the char are missing)
3017 * @param $string String
3020 protected function removeBadCharFirst( $string ) {
3021 if ( $string != '' ) {
3022 $char = ord( $string[0] );
3023 if ( $char >= 0x80 && $char < 0xc0 ) {
3024 # We chopped in the middle of a character; remove the whole thing
3025 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3032 * Truncate a string of valid HTML to a specified length in bytes,
3033 * appending an optional string (e.g. for ellipses), and return valid HTML
3035 * This is only intended for styled/linked text, such as HTML with
3036 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3037 * Also, this will not detect things like "display:none" CSS.
3039 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3041 * @param string $text HTML string to truncate
3042 * @param int $length (zero/positive) Maximum length (including ellipses)
3043 * @param string $ellipsis String to append to the truncated text
3046 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3047 # Use the localized ellipsis character
3048 if ( $ellipsis == '...' ) {
3049 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3051 # Check if there is clearly no need to truncate
3052 if ( $length <= 0 ) {
3053 return $ellipsis; // no text shown, nothing to format (convention)
3054 } elseif ( strlen( $text ) <= $length ) {
3055 return $text; // string short enough even *with* HTML (short-circuit)
3058 $dispLen = 0; // innerHTML legth so far
3059 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3060 $tagType = 0; // 0-open, 1-close
3061 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3062 $entityState = 0; // 0-not entity, 1-entity
3063 $tag = $ret = ''; // accumulated tag name, accumulated result string
3064 $openTags = array(); // open tag stack
3065 $maybeState = null; // possible truncation state
3067 $textLen = strlen( $text );
3068 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3069 for ( $pos = 0; true; ++
$pos ) {
3070 # Consider truncation once the display length has reached the maximim.
3071 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3072 # Check that we're not in the middle of a bracket/entity...
3073 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3074 if ( !$testingEllipsis ) {
3075 $testingEllipsis = true;
3076 # Save where we are; we will truncate here unless there turn out to
3077 # be so few remaining characters that truncation is not necessary.
3078 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3079 $maybeState = array( $ret, $openTags ); // save state
3081 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3082 # String in fact does need truncation, the truncation point was OK.
3083 list( $ret, $openTags ) = $maybeState; // reload state
3084 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3085 $ret .= $ellipsis; // add ellipsis
3089 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3091 # Read the next char...
3093 $lastCh = $pos ?
$text[$pos - 1] : '';
3094 $ret .= $ch; // add to result string
3096 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3097 $entityState = 0; // for bad HTML
3098 $bracketState = 1; // tag started (checking for backslash)
3099 } elseif ( $ch == '>' ) {
3100 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3101 $entityState = 0; // for bad HTML
3102 $bracketState = 0; // out of brackets
3103 } elseif ( $bracketState == 1 ) {
3105 $tagType = 1; // close tag (e.g. "</span>")
3107 $tagType = 0; // open tag (e.g. "<span>")
3110 $bracketState = 2; // building tag name
3111 } elseif ( $bracketState == 2 ) {
3115 // Name found (e.g. "<a href=..."), add on tag attributes...
3116 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3118 } elseif ( $bracketState == 0 ) {
3119 if ( $entityState ) {
3122 $dispLen++
; // entity is one displayed char
3125 if ( $neLength == 0 && !$maybeState ) {
3126 // Save state without $ch. We want to *hit* the first
3127 // display char (to get tags) but not *use* it if truncating.
3128 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3131 $entityState = 1; // entity found, (e.g. " ")
3133 $dispLen++
; // this char is displayed
3134 // Add the next $max display text chars after this in one swoop...
3135 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3136 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3137 $dispLen +
= $skipped;
3143 // Close the last tag if left unclosed by bad HTML
3144 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3145 while ( count( $openTags ) > 0 ) {
3146 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3152 * truncateHtml() helper function
3153 * like strcspn() but adds the skipped chars to $ret
3162 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3163 if ( $len === null ) {
3164 $len = -1; // -1 means "no limit" for strcspn
3165 } elseif ( $len < 0 ) {
3169 if ( $start < strlen( $text ) ) {
3170 $skipCount = strcspn( $text, $search, $start, $len );
3171 $ret .= substr( $text, $start, $skipCount );
3177 * truncateHtml() helper function
3178 * (a) push or pop $tag from $openTags as needed
3179 * (b) clear $tag value
3180 * @param &$tag string Current HTML tag name we are looking at
3181 * @param $tagType int (0-open tag, 1-close tag)
3182 * @param $lastCh string Character before the '>' that ended this tag
3183 * @param &$openTags array Open tag stack (not accounting for $tag)
3185 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3186 $tag = ltrim( $tag );
3188 if ( $tagType == 0 && $lastCh != '/' ) {
3189 $openTags[] = $tag; // tag opened (didn't close itself)
3190 } elseif ( $tagType == 1 ) {
3191 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3192 array_pop( $openTags ); // tag closed
3200 * Grammatical transformations, needed for inflected languages
3201 * Invoked by putting {{grammar:case|word}} in a message
3203 * @param $word string
3204 * @param $case string
3207 function convertGrammar( $word, $case ) {
3208 global $wgGrammarForms;
3209 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3210 return $wgGrammarForms[$this->getCode()][$case][$word];
3216 * Provides an alternative text depending on specified gender.
3217 * Usage {{gender:username|masculine|feminine|neutral}}.
3218 * username is optional, in which case the gender of current user is used,
3219 * but only in (some) interface messages; otherwise default gender is used.
3221 * If no forms are given, an empty string is returned. If only one form is
3222 * given, it will be returned unconditionally. These details are implied by
3223 * the caller and cannot be overridden in subclasses.
3225 * If more than one form is given, the default is to use the neutral one
3226 * if it is specified, and to use the masculine one otherwise. These
3227 * details can be overridden in subclasses.
3229 * @param $gender string
3230 * @param $forms array
3234 function gender( $gender, $forms ) {
3235 if ( !count( $forms ) ) {
3238 $forms = $this->preConvertPlural( $forms, 2 );
3239 if ( $gender === 'male' ) {
3242 if ( $gender === 'female' ) {
3245 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3249 * Plural form transformations, needed for some languages.
3250 * For example, there are 3 form of plural in Russian and Polish,
3251 * depending on "count mod 10". See [[w:Plural]]
3252 * For English it is pretty simple.
3254 * Invoked by putting {{plural:count|wordform1|wordform2}}
3255 * or {{plural:count|wordform1|wordform2|wordform3}}
3257 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3259 * @param $count Integer: non-localized number
3260 * @param $forms Array: different plural forms
3261 * @return string Correct form of plural for $count in this language
3263 function convertPlural( $count, $forms ) {
3264 if ( !count( $forms ) ) {
3267 $forms = $this->preConvertPlural( $forms, 2 );
3269 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3273 * Checks that convertPlural was given an array and pads it to requested
3274 * amount of forms by copying the last one.
3276 * @param $count Integer: How many forms should there be at least
3277 * @param $forms Array of forms given to convertPlural
3278 * @return array Padded array of forms or an exception if not an array
3280 protected function preConvertPlural( /* Array */ $forms, $count ) {
3281 while ( count( $forms ) < $count ) {
3282 $forms[] = $forms[count( $forms ) - 1];
3288 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3289 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3290 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3291 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3294 * @param $str String: the validated block duration in English
3295 * @return string Somehow translated block duration
3296 * @see LanguageFi.php for example implementation
3298 function translateBlockExpiry( $str ) {
3299 $duration = SpecialBlock
::getSuggestedDurations( $this );
3300 foreach ( $duration as $show => $value ) {
3301 if ( strcmp( $str, $value ) == 0 ) {
3302 return htmlspecialchars( trim( $show ) );
3306 // Since usually only infinite or indefinite is only on list, so try
3307 // equivalents if still here.
3308 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3309 if ( in_array( $str, $indefs ) ) {
3310 foreach ( $indefs as $val ) {
3311 $show = array_search( $val, $duration, true );
3312 if ( $show !== false ) {
3313 return htmlspecialchars( trim( $show ) );
3317 // If all else fails, return the original string.
3322 * languages like Chinese need to be segmented in order for the diff
3325 * @param $text String
3328 public function segmentForDiff( $text ) {
3333 * and unsegment to show the result
3335 * @param $text String
3338 public function unsegmentForDiff( $text ) {
3343 * Return the LanguageConverter used in the Language
3346 * @return LanguageConverter
3348 public function getConverter() {
3349 return $this->mConverter
;
3353 * convert text to all supported variants
3355 * @param $text string
3358 public function autoConvertToAllVariants( $text ) {
3359 return $this->mConverter
->autoConvertToAllVariants( $text );
3363 * convert text to different variants of a language.
3365 * @param $text string
3368 public function convert( $text ) {
3369 return $this->mConverter
->convert( $text );
3373 * Convert a Title object to a string in the preferred variant
3375 * @param $title Title
3378 public function convertTitle( $title ) {
3379 return $this->mConverter
->convertTitle( $title );
3383 * Check if this is a language with variants
3387 public function hasVariants() {
3388 return sizeof( $this->getVariants() ) > 1;
3392 * Check if the language has the specific variant
3395 * @param $variant string
3398 public function hasVariant( $variant ) {
3399 return (bool)$this->mConverter
->validateVariant( $variant );
3403 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3405 * @param $text string
3408 public function armourMath( $text ) {
3409 return $this->mConverter
->armourMath( $text );
3413 * Perform output conversion on a string, and encode for safe HTML output.
3414 * @param $text String text to be converted
3415 * @param $isTitle Bool whether this conversion is for the article title
3417 * @todo this should get integrated somewhere sane
3419 public function convertHtml( $text, $isTitle = false ) {
3420 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3424 * @param $key string
3427 public function convertCategoryKey( $key ) {
3428 return $this->mConverter
->convertCategoryKey( $key );
3432 * Get the list of variants supported by this language
3433 * see sample implementation in LanguageZh.php
3435 * @return array an array of language codes
3437 public function getVariants() {
3438 return $this->mConverter
->getVariants();
3444 public function getPreferredVariant() {
3445 return $this->mConverter
->getPreferredVariant();
3451 public function getDefaultVariant() {
3452 return $this->mConverter
->getDefaultVariant();
3458 public function getURLVariant() {
3459 return $this->mConverter
->getURLVariant();
3463 * If a language supports multiple variants, it is
3464 * possible that non-existing link in one variant
3465 * actually exists in another variant. this function
3466 * tries to find it. See e.g. LanguageZh.php
3468 * @param $link String: the name of the link
3469 * @param $nt Mixed: the title object of the link
3470 * @param $ignoreOtherCond Boolean: to disable other conditions when
3471 * we need to transclude a template or update a category's link
3472 * @return null the input parameters may be modified upon return
3474 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3475 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3479 * If a language supports multiple variants, converts text
3480 * into an array of all possible variants of the text:
3481 * 'variant' => text in that variant
3483 * @deprecated since 1.17 Use autoConvertToAllVariants()
3485 * @param $text string
3489 public function convertLinkToAllVariants( $text ) {
3490 return $this->mConverter
->convertLinkToAllVariants( $text );
3494 * returns language specific options used by User::getPageRenderHash()
3495 * for example, the preferred language variant
3499 function getExtraHashOptions() {
3500 return $this->mConverter
->getExtraHashOptions();
3504 * For languages that support multiple variants, the title of an
3505 * article may be displayed differently in different variants. this
3506 * function returns the apporiate title defined in the body of the article.
3510 public function getParsedTitle() {
3511 return $this->mConverter
->getParsedTitle();
3515 * Enclose a string with the "no conversion" tag. This is used by
3516 * various functions in the Parser
3518 * @param $text String: text to be tagged for no conversion
3519 * @param $noParse bool
3520 * @return string the tagged text
3522 public function markNoConversion( $text, $noParse = false ) {
3523 return $this->mConverter
->markNoConversion( $text, $noParse );
3527 * A regular expression to match legal word-trailing characters
3528 * which should be merged onto a link of the form [[foo]]bar.
3532 public function linkTrail() {
3533 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3539 function getLangObj() {
3544 * Get the RFC 3066 code for this language object
3548 public function getCode() {
3549 return $this->mCode
;
3553 * Get the code in Bcp47 format which we can use
3554 * inside of html lang="" tags.
3558 public function getHtmlCode() {
3559 if ( is_null( $this->mHtmlCode
) ) {
3560 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3562 return $this->mHtmlCode
;
3566 * @param $code string
3568 public function setCode( $code ) {
3569 $this->mCode
= $code;
3570 // Ensure we don't leave an incorrect html code lying around
3571 $this->mHtmlCode
= null;
3575 * Get the name of a file for a certain language code
3576 * @param $prefix string Prepend this to the filename
3577 * @param $code string Language code
3578 * @param $suffix string Append this to the filename
3579 * @return string $prefix . $mangledCode . $suffix
3581 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3582 // Protect against path traversal
3583 if ( !Language
::isValidCode( $code )
3584 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3586 throw new MWException( "Invalid language code \"$code\"" );
3589 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3593 * Get the language code from a file name. Inverse of getFileName()
3594 * @param $filename string $prefix . $languageCode . $suffix
3595 * @param $prefix string Prefix before the language code
3596 * @param $suffix string Suffix after the language code
3597 * @return string Language code, or false if $prefix or $suffix isn't found
3599 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3601 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3602 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3603 if ( !count( $m ) ) {
3606 return str_replace( '_', '-', strtolower( $m[1] ) );
3610 * @param $code string
3613 public static function getMessagesFileName( $code ) {
3615 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3616 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3621 * @param $code string
3624 public static function getClassFileName( $code ) {
3626 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3630 * Get the first fallback for a given language.
3632 * @param $code string
3634 * @return bool|string
3636 public static function getFallbackFor( $code ) {
3637 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3640 $fallbacks = self
::getFallbacksFor( $code );
3641 $first = array_shift( $fallbacks );
3647 * Get the ordered list of fallback languages.
3650 * @param $code string Language code
3653 public static function getFallbacksFor( $code ) {
3654 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3657 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3658 $v = array_map( 'trim', explode( ',', $v ) );
3659 if ( $v[count( $v ) - 1] !== 'en' ) {
3667 * Get all messages for a given language
3668 * WARNING: this may take a long time. If you just need all message *keys*
3669 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3671 * @param $code string
3675 public static function getMessagesFor( $code ) {
3676 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3680 * Get a message for a given language
3682 * @param $key string
3683 * @param $code string
3687 public static function getMessageFor( $key, $code ) {
3688 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3692 * Get all message keys for a given language. This is a faster alternative to
3693 * array_keys( Language::getMessagesFor( $code ) )
3696 * @param $code string Language code
3697 * @return array of message keys (strings)
3699 public static function getMessageKeysFor( $code ) {
3700 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3707 function fixVariableInNamespace( $talk ) {
3708 if ( strpos( $talk, '$1' ) === false ) {
3712 global $wgMetaNamespace;
3713 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3715 # Allow grammar transformations
3716 # Allowing full message-style parsing would make simple requests
3717 # such as action=raw much more expensive than they need to be.
3718 # This will hopefully cover most cases.
3719 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3720 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3721 return str_replace( ' ', '_', $talk );
3728 function replaceGrammarInNamespace( $m ) {
3729 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3733 * @throws MWException
3736 static function getCaseMaps() {
3737 static $wikiUpperChars, $wikiLowerChars;
3738 if ( isset( $wikiUpperChars ) ) {
3739 return array( $wikiUpperChars, $wikiLowerChars );
3742 wfProfileIn( __METHOD__
);
3743 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3744 if ( $arr === false ) {
3745 throw new MWException(
3746 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3748 $wikiUpperChars = $arr['wikiUpperChars'];
3749 $wikiLowerChars = $arr['wikiLowerChars'];
3750 wfProfileOut( __METHOD__
);
3751 return array( $wikiUpperChars, $wikiLowerChars );
3755 * Decode an expiry (block, protection, etc) which has come from the DB
3757 * @FIXME: why are we returnings DBMS-dependent strings???
3759 * @param $expiry String: Database expiry String
3760 * @param $format Bool|Int true to process using language functions, or TS_ constant
3761 * to return the expiry in a given timestamp
3764 public function formatExpiry( $expiry, $format = true ) {
3765 static $infinity, $infinityMsg;
3766 if ( $infinity === null ) {
3767 $infinityMsg = wfMessage( 'infiniteblock' );
3768 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3771 if ( $expiry == '' ||
$expiry == $infinity ) {
3772 return $format === true
3776 return $format === true
3777 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3778 : wfTimestamp( $format, $expiry );
3784 * @param $seconds int|float
3785 * @param $format Array Optional
3786 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3787 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3788 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3789 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3792 function formatTimePeriod( $seconds, $format = array() ) {
3793 if ( !is_array( $format ) ) {
3794 $format = array( 'avoid' => $format ); // For backwards compatibility
3796 if ( !isset( $format['avoid'] ) ) {
3797 $format['avoid'] = false;
3799 if ( !isset( $format['noabbrevs' ] ) ) {
3800 $format['noabbrevs'] = false;
3802 $secondsMsg = wfMessage(
3803 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3804 $minutesMsg = wfMessage(
3805 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3806 $hoursMsg = wfMessage(
3807 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3808 $daysMsg = wfMessage(
3809 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3811 if ( round( $seconds * 10 ) < 100 ) {
3812 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3813 $s = $secondsMsg->params( $s )->text();
3814 } elseif ( round( $seconds ) < 60 ) {
3815 $s = $this->formatNum( round( $seconds ) );
3816 $s = $secondsMsg->params( $s )->text();
3817 } elseif ( round( $seconds ) < 3600 ) {
3818 $minutes = floor( $seconds / 60 );
3819 $secondsPart = round( fmod( $seconds, 60 ) );
3820 if ( $secondsPart == 60 ) {
3824 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3826 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3827 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3828 $hours = floor( $seconds / 3600 );
3829 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3830 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3831 if ( $secondsPart == 60 ) {
3835 if ( $minutes == 60 ) {
3839 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3841 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3842 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3843 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3846 $days = floor( $seconds / 86400 );
3847 if ( $format['avoid'] === 'avoidminutes' ) {
3848 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3849 if ( $hours == 24 ) {
3853 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3855 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3856 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3857 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3858 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3859 if ( $minutes == 60 ) {
3863 if ( $hours == 24 ) {
3867 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3869 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3871 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3873 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3875 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3882 * Format a bitrate for output, using an appropriate
3883 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3885 * This use base 1000. For base 1024 use formatSize(), for another base
3886 * see formatComputingNumbers()
3891 function formatBitrate( $bps ) {
3892 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3896 * @param $size int Size of the unit
3897 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3898 * @param $messageKey string Message key to be uesd
3901 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3903 return str_replace( '$1', $this->formatNum( $size ),
3904 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3907 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3910 $maxIndex = count( $sizes ) - 1;
3911 while ( $size >= $boundary && $index < $maxIndex ) {
3916 // For small sizes no decimal places necessary
3919 // For MB and bigger two decimal places are smarter
3922 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3924 $size = round( $size, $round );
3925 $text = $this->getMessageFromDB( $msg );
3926 return str_replace( '$1', $this->formatNum( $size ), $text );
3930 * Format a size in bytes for output, using an appropriate
3931 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3933 * This method use base 1024. For base 1000 use formatBitrate(), for
3934 * another base see formatComputingNumbers()
3936 * @param $size int Size to format
3937 * @return string Plain text (not HTML)
3939 function formatSize( $size ) {
3940 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3944 * Make a list item, used by various special pages
3946 * @param $page String Page link
3947 * @param $details String Text between brackets
3948 * @param $oppositedm Boolean Add the direction mark opposite to your
3949 * language, to display text properly
3952 function specialList( $page, $details, $oppositedm = true ) {
3953 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3954 $this->getDirMark();
3955 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3956 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3957 return $page . $details;
3961 * Generate (prev x| next x) (20|50|100...) type links for paging
3963 * @param $title Title object to link
3964 * @param $offset Integer offset parameter
3965 * @param $limit Integer limit parameter
3966 * @param $query String optional URL query parameter string
3967 * @param $atend Bool optional param for specified if this is the last page
3970 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3971 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3973 # Make 'previous' link
3974 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3975 if ( $offset > 0 ) {
3976 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3977 $query, $prev, 'prevn-title', 'mw-prevlink' );
3979 $plink = htmlspecialchars( $prev );
3983 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3985 $nlink = htmlspecialchars( $next );
3987 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3988 $query, $next, 'prevn-title', 'mw-nextlink' );
3991 # Make links to set number of items per page
3992 $numLinks = array();
3993 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
3994 $numLinks[] = $this->numLink( $title, $offset, $num,
3995 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3998 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3999 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4003 * Helper function for viewPrevNext() that generates links
4005 * @param $title Title object to link
4006 * @param $offset Integer offset parameter
4007 * @param $limit Integer limit parameter
4008 * @param $query Array extra query parameters
4009 * @param $link String text to use for the link; will be escaped
4010 * @param $tooltipMsg String name of the message to use as tooltip
4011 * @param $class String value of the "class" attribute of the link
4012 * @return String HTML fragment
4014 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4015 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4016 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4017 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4018 'title' => $tooltip, 'class' => $class ), $link );
4022 * Get the conversion rule title, if any.
4026 public function getConvRuleTitle() {
4027 return $this->mConverter
->getConvRuleTitle();