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
663 public static function getLanguageNames( $customisedOnly = false ) {
664 global $wgExtraLanguageNames;
665 static $coreLanguageNames;
667 if ( $coreLanguageNames === null ) {
668 include( MWInit
::compiledPath( 'languages/Names.php' ) );
671 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
672 if ( !$customisedOnly ) {
677 // We do this using a foreach over the codes instead of a directory
678 // loop so that messages files in extensions will work correctly.
679 foreach ( $allNames as $code => $value ) {
680 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
681 $names[$code] = $allNames[$code];
688 * Get translated language names. This is done on best effort and
689 * by default this is exactly the same as Language::getLanguageNames.
690 * The CLDR extension provides translated names.
691 * @param $code String Language code.
692 * @return Array language code => language name
695 public static function getTranslatedLanguageNames( $code ) {
697 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
699 foreach ( self
::getLanguageNames() as $code => $name ) {
700 if ( !isset( $names[$code] ) ) $names[$code] = $name;
707 * Get a message from the MediaWiki namespace.
709 * @param $msg String: message name
712 function getMessageFromDB( $msg ) {
713 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
717 * Get the native language name of $code.
718 * Only if defined in MediaWiki, no other data like CLDR.
719 * @param $code string
722 function getLanguageName( $code ) {
723 $names = self
::getLanguageNames();
724 if ( !array_key_exists( $code, $names ) ) {
727 return $names[$code];
734 function getMonthName( $key ) {
735 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
741 function getMonthNamesArray() {
742 $monthNames = array( '' );
743 for ( $i = 1; $i < 13; $i++
) {
744 $monthNames[] = $this->getMonthName( $i );
753 function getMonthNameGen( $key ) {
754 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
761 function getMonthAbbreviation( $key ) {
762 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
768 function getMonthAbbreviationsArray() {
769 $monthNames = array( '' );
770 for ( $i = 1; $i < 13; $i++
) {
771 $monthNames[] = $this->getMonthAbbreviation( $i );
780 function getWeekdayName( $key ) {
781 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
788 function getWeekdayAbbreviation( $key ) {
789 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
796 function getIranianCalendarMonthName( $key ) {
797 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
804 function getHebrewCalendarMonthName( $key ) {
805 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
812 function getHebrewCalendarMonthNameGen( $key ) {
813 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
820 function getHijriCalendarMonthName( $key ) {
821 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
825 * This is a workalike of PHP's date() function, but with better
826 * internationalisation, a reduced set of format characters, and a better
829 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
830 * PHP manual for definitions. There are a number of extensions, which
833 * xn Do not translate digits of the next numeric format character
834 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
835 * xr Use roman numerals for the next numeric format character
836 * xh Use hebrew numerals for the next numeric format character
838 * xg Genitive month name
840 * xij j (day number) in Iranian calendar
841 * xiF F (month name) in Iranian calendar
842 * xin n (month number) in Iranian calendar
843 * xiy y (two digit year) in Iranian calendar
844 * xiY Y (full year) in Iranian calendar
846 * xjj j (day number) in Hebrew calendar
847 * xjF F (month name) in Hebrew calendar
848 * xjt t (days in month) in Hebrew calendar
849 * xjx xg (genitive month name) in Hebrew calendar
850 * xjn n (month number) in Hebrew calendar
851 * xjY Y (full year) in Hebrew calendar
853 * xmj j (day number) in Hijri calendar
854 * xmF F (month name) in Hijri calendar
855 * xmn n (month number) in Hijri calendar
856 * xmY Y (full year) in Hijri calendar
858 * xkY Y (full year) in Thai solar calendar. Months and days are
859 * identical to the Gregorian calendar
860 * xoY Y (full year) in Minguo calendar or Juche year.
861 * Months and days are identical to the
863 * xtY Y (full year) in Japanese nengo. Months and days are
864 * identical to the Gregorian calendar
866 * Characters enclosed in double quotes will be considered literal (with
867 * the quotes themselves removed). Unmatched quotes will be considered
868 * literal quotes. Example:
870 * "The month is" F => The month is January
873 * Backslash escaping is also supported.
875 * Input timestamp is assumed to be pre-normalized to the desired local
878 * @param $format String
879 * @param $ts String: 14-character timestamp
882 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
886 function sprintfDate( $format, $ts ) {
899 for ( $p = 0; $p < strlen( $format ); $p++
) {
902 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
903 $code .= $format[++
$p];
906 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
907 $code .= $format[++
$p];
918 $rawToggle = !$rawToggle;
927 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
930 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
931 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
934 $num = substr( $ts, 6, 2 );
937 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
938 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
941 $num = intval( substr( $ts, 6, 2 ) );
945 $iranian = self
::tsToIranian( $ts );
951 $hijri = self
::tsToHijri( $ts );
957 $hebrew = self
::tsToHebrew( $ts );
963 $unix = wfTimestamp( TS_UNIX
, $ts );
965 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
969 $unix = wfTimestamp( TS_UNIX
, $ts );
971 $w = gmdate( 'w', $unix );
976 $unix = wfTimestamp( TS_UNIX
, $ts );
978 $num = gmdate( 'w', $unix );
982 $unix = wfTimestamp( TS_UNIX
, $ts );
984 $num = gmdate( 'z', $unix );
988 $unix = wfTimestamp( TS_UNIX
, $ts );
990 $num = gmdate( 'W', $unix );
993 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
997 $iranian = self
::tsToIranian( $ts );
999 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1003 $hijri = self
::tsToHijri( $ts );
1005 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1009 $hebrew = self
::tsToHebrew( $ts );
1011 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1014 $num = substr( $ts, 4, 2 );
1017 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1020 $num = intval( substr( $ts, 4, 2 ) );
1024 $iranian = self
::tsToIranian( $ts );
1030 $hijri = self
::tsToHijri ( $ts );
1036 $hebrew = self
::tsToHebrew( $ts );
1042 $unix = wfTimestamp( TS_UNIX
, $ts );
1044 $num = gmdate( 't', $unix );
1048 $hebrew = self
::tsToHebrew( $ts );
1054 $unix = wfTimestamp( TS_UNIX
, $ts );
1056 $num = gmdate( 'L', $unix );
1060 $unix = wfTimestamp( TS_UNIX
, $ts );
1062 $num = gmdate( 'o', $unix );
1065 $num = substr( $ts, 0, 4 );
1069 $iranian = self
::tsToIranian( $ts );
1075 $hijri = self
::tsToHijri( $ts );
1081 $hebrew = self
::tsToHebrew( $ts );
1087 $thai = self
::tsToYear( $ts, 'thai' );
1093 $minguo = self
::tsToYear( $ts, 'minguo' );
1099 $tenno = self
::tsToYear( $ts, 'tenno' );
1104 $num = substr( $ts, 2, 2 );
1108 $iranian = self
::tsToIranian( $ts );
1110 $num = substr( $iranian[0], -2 );
1113 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1116 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1119 $h = substr( $ts, 8, 2 );
1120 $num = $h %
12 ?
$h %
12 : 12;
1123 $num = intval( substr( $ts, 8, 2 ) );
1126 $h = substr( $ts, 8, 2 );
1127 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1130 $num = substr( $ts, 8, 2 );
1133 $num = substr( $ts, 10, 2 );
1136 $num = substr( $ts, 12, 2 );
1140 $unix = wfTimestamp( TS_UNIX
, $ts );
1142 $s .= gmdate( 'c', $unix );
1146 $unix = wfTimestamp( TS_UNIX
, $ts );
1148 $s .= gmdate( 'r', $unix );
1152 $unix = wfTimestamp( TS_UNIX
, $ts );
1157 # Backslash escaping
1158 if ( $p < strlen( $format ) - 1 ) {
1159 $s .= $format[++
$p];
1166 if ( $p < strlen( $format ) - 1 ) {
1167 $endQuote = strpos( $format, '"', $p +
1 );
1168 if ( $endQuote === false ) {
1169 # No terminating quote, assume literal "
1172 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1176 # Quote at end of string, assume literal "
1183 if ( $num !== false ) {
1184 if ( $rawToggle ||
$raw ) {
1187 } elseif ( $roman ) {
1188 $s .= self
::romanNumeral( $num );
1190 } elseif ( $hebrewNum ) {
1191 $s .= self
::hebrewNumeral( $num );
1194 $s .= $this->formatNum( $num, true );
1201 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1202 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1205 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1206 * Gregorian dates to Iranian dates. Originally written in C, it
1207 * is released under the terms of GNU Lesser General Public
1208 * License. Conversion to PHP was performed by Niklas Laxström.
1210 * Link: http://www.farsiweb.info/jalali/jalali.c
1216 private static function tsToIranian( $ts ) {
1217 $gy = substr( $ts, 0, 4 ) -1600;
1218 $gm = substr( $ts, 4, 2 ) -1;
1219 $gd = substr( $ts, 6, 2 ) -1;
1221 # Days passed from the beginning (including leap years)
1223 +
floor( ( $gy +
3 ) / 4 )
1224 - floor( ( $gy +
99 ) / 100 )
1225 +
floor( ( $gy +
399 ) / 400 );
1227 // Add days of the past months of this year
1228 for ( $i = 0; $i < $gm; $i++
) {
1229 $gDayNo +
= self
::$GREG_DAYS[$i];
1233 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1237 // Days passed in current month
1238 $gDayNo +
= (int)$gd;
1240 $jDayNo = $gDayNo - 79;
1242 $jNp = floor( $jDayNo / 12053 );
1245 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1248 if ( $jDayNo >= 366 ) {
1249 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1250 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1253 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1254 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1260 return array( $jy, $jm, $jd );
1264 * Converting Gregorian dates to Hijri dates.
1266 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1268 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1274 private static function tsToHijri( $ts ) {
1275 $year = substr( $ts, 0, 4 );
1276 $month = substr( $ts, 4, 2 );
1277 $day = substr( $ts, 6, 2 );
1285 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1286 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1289 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1290 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1291 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1294 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1295 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1298 $zl = $zjd -1948440 +
10632;
1299 $zn = (int)( ( $zl - 1 ) / 10631 );
1300 $zl = $zl - 10631 * $zn +
354;
1301 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1302 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1303 $zm = (int)( ( 24 * $zl ) / 709 );
1304 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1305 $zy = 30 * $zn +
$zj - 30;
1307 return array( $zy, $zm, $zd );
1311 * Converting Gregorian dates to Hebrew dates.
1313 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1314 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1315 * to translate the relevant functions into PHP and release them under
1318 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1319 * and Adar II is 14. In a non-leap year, Adar is 6.
1325 private static function tsToHebrew( $ts ) {
1327 $year = substr( $ts, 0, 4 );
1328 $month = substr( $ts, 4, 2 );
1329 $day = substr( $ts, 6, 2 );
1331 # Calculate Hebrew year
1332 $hebrewYear = $year +
3760;
1334 # Month number when September = 1, August = 12
1336 if ( $month > 12 ) {
1343 # Calculate day of year from 1 September
1345 for ( $i = 1; $i < $month; $i++
) {
1349 # Check if the year is leap
1350 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1353 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1360 # Calculate the start of the Hebrew year
1361 $start = self
::hebrewYearStart( $hebrewYear );
1363 # Calculate next year's start
1364 if ( $dayOfYear <= $start ) {
1365 # Day is before the start of the year - it is the previous year
1367 $nextStart = $start;
1371 # Add days since previous year's 1 September
1373 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1377 # Start of the new (previous) year
1378 $start = self
::hebrewYearStart( $hebrewYear );
1381 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1384 # Calculate Hebrew day of year
1385 $hebrewDayOfYear = $dayOfYear - $start;
1387 # Difference between year's days
1388 $diff = $nextStart - $start;
1389 # Add 12 (or 13 for leap years) days to ignore the difference between
1390 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1391 # difference is only about the year type
1392 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1398 # Check the year pattern, and is leap year
1399 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1400 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1401 # and non-leap years
1402 $yearPattern = $diff %
30;
1403 # Check if leap year
1404 $isLeap = $diff >= 30;
1406 # Calculate day in the month from number of day in the Hebrew year
1407 # Don't check Adar - if the day is not in Adar, we will stop before;
1408 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1409 $hebrewDay = $hebrewDayOfYear;
1412 while ( $hebrewMonth <= 12 ) {
1413 # Calculate days in this month
1414 if ( $isLeap && $hebrewMonth == 6 ) {
1415 # Adar in a leap year
1417 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1419 if ( $hebrewDay <= $days ) {
1423 # Subtract the days of Adar I
1424 $hebrewDay -= $days;
1427 if ( $hebrewDay <= $days ) {
1433 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1434 # Cheshvan in a complete year (otherwise as the rule below)
1436 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1437 # Kislev in an incomplete year (otherwise as the rule below)
1440 # Odd months have 30 days, even have 29
1441 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1443 if ( $hebrewDay <= $days ) {
1444 # In the current month
1447 # Subtract the days of the current month
1448 $hebrewDay -= $days;
1449 # Try in the next month
1454 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1458 * This calculates the Hebrew year start, as days since 1 September.
1459 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1460 * Used for Hebrew date.
1466 private static function hebrewYearStart( $year ) {
1467 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1468 $b = intval( ( $year - 1 ) %
4 );
1469 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1473 $Mar = intval( $m );
1479 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1480 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1482 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1484 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1488 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1493 * Algorithm to convert Gregorian dates to Thai solar dates,
1494 * Minguo dates or Minguo dates.
1496 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1497 * http://en.wikipedia.org/wiki/Minguo_calendar
1498 * http://en.wikipedia.org/wiki/Japanese_era_name
1500 * @param $ts String: 14-character timestamp
1501 * @param $cName String: calender name
1502 * @return Array: converted year, month, day
1504 private static function tsToYear( $ts, $cName ) {
1505 $gy = substr( $ts, 0, 4 );
1506 $gm = substr( $ts, 4, 2 );
1507 $gd = substr( $ts, 6, 2 );
1509 if ( !strcmp( $cName, 'thai' ) ) {
1511 # Add 543 years to the Gregorian calendar
1512 # Months and days are identical
1513 $gy_offset = $gy +
543;
1514 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1516 # Deduct 1911 years from the Gregorian calendar
1517 # Months and days are identical
1518 $gy_offset = $gy - 1911;
1519 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1520 # Nengō dates up to Meiji period
1521 # Deduct years from the Gregorian calendar
1522 # depending on the nengo periods
1523 # Months and days are identical
1524 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1526 $gy_gannen = $gy - 1868 +
1;
1527 $gy_offset = $gy_gannen;
1528 if ( $gy_gannen == 1 ) {
1531 $gy_offset = '明治' . $gy_offset;
1533 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1534 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1535 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1536 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1537 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1541 $gy_gannen = $gy - 1912 +
1;
1542 $gy_offset = $gy_gannen;
1543 if ( $gy_gannen == 1 ) {
1546 $gy_offset = '大正' . $gy_offset;
1548 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1549 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1550 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1554 $gy_gannen = $gy - 1926 +
1;
1555 $gy_offset = $gy_gannen;
1556 if ( $gy_gannen == 1 ) {
1559 $gy_offset = '昭和' . $gy_offset;
1562 $gy_gannen = $gy - 1989 +
1;
1563 $gy_offset = $gy_gannen;
1564 if ( $gy_gannen == 1 ) {
1567 $gy_offset = '平成' . $gy_offset;
1573 return array( $gy_offset, $gm, $gd );
1577 * Roman number formatting up to 3000
1583 static function romanNumeral( $num ) {
1584 static $table = array(
1585 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1586 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1587 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1588 array( '', 'M', 'MM', 'MMM' )
1591 $num = intval( $num );
1592 if ( $num > 3000 ||
$num <= 0 ) {
1597 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1598 if ( $num >= $pow10 ) {
1599 $s .= $table[$i][(int)floor( $num / $pow10 )];
1601 $num = $num %
$pow10;
1607 * Hebrew Gematria number formatting up to 9999
1613 static function hebrewNumeral( $num ) {
1614 static $table = array(
1615 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1616 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1617 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1618 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1621 $num = intval( $num );
1622 if ( $num > 9999 ||
$num <= 0 ) {
1627 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1628 if ( $num >= $pow10 ) {
1629 if ( $num == 15 ||
$num == 16 ) {
1630 $s .= $table[0][9] . $table[0][$num - 9];
1633 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1634 if ( $pow10 == 1000 ) {
1639 $num = $num %
$pow10;
1641 if ( strlen( $s ) == 2 ) {
1644 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1645 $str .= substr( $s, strlen( $s ) - 2, 2 );
1647 $start = substr( $str, 0, strlen( $str ) - 2 );
1648 $end = substr( $str, strlen( $str ) - 2 );
1651 $str = $start . 'ך';
1654 $str = $start . 'ם';
1657 $str = $start . 'ן';
1660 $str = $start . 'ף';
1663 $str = $start . 'ץ';
1670 * Used by date() and time() to adjust the time output.
1672 * @param $ts Int the time in date('YmdHis') format
1673 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1674 * get user timecorrection setting)
1677 function userAdjust( $ts, $tz = false ) {
1678 global $wgUser, $wgLocalTZoffset;
1680 if ( $tz === false ) {
1681 $tz = $wgUser->getOption( 'timecorrection' );
1684 $data = explode( '|', $tz, 3 );
1686 if ( $data[0] == 'ZoneInfo' ) {
1687 wfSuppressWarnings();
1688 $userTZ = timezone_open( $data[2] );
1689 wfRestoreWarnings();
1690 if ( $userTZ !== false ) {
1691 $date = date_create( $ts, timezone_open( 'UTC' ) );
1692 date_timezone_set( $date, $userTZ );
1693 $date = date_format( $date, 'YmdHis' );
1696 # Unrecognized timezone, default to 'Offset' with the stored offset.
1697 $data[0] = 'Offset';
1701 if ( $data[0] == 'System' ||
$tz == '' ) {
1702 # Global offset in minutes.
1703 if ( isset( $wgLocalTZoffset ) ) {
1704 $minDiff = $wgLocalTZoffset;
1706 } elseif ( $data[0] == 'Offset' ) {
1707 $minDiff = intval( $data[1] );
1709 $data = explode( ':', $tz );
1710 if ( count( $data ) == 2 ) {
1711 $data[0] = intval( $data[0] );
1712 $data[1] = intval( $data[1] );
1713 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1714 if ( $data[0] < 0 ) {
1715 $minDiff = -$minDiff;
1718 $minDiff = intval( $data[0] ) * 60;
1722 # No difference ? Return time unchanged
1723 if ( 0 == $minDiff ) {
1727 wfSuppressWarnings(); // E_STRICT system time bitching
1728 # Generate an adjusted date; take advantage of the fact that mktime
1729 # will normalize out-of-range values so we don't have to split $minDiff
1730 # into hours and minutes.
1732 (int)substr( $ts, 8, 2 ) ), # Hours
1733 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1734 (int)substr( $ts, 12, 2 ), # Seconds
1735 (int)substr( $ts, 4, 2 ), # Month
1736 (int)substr( $ts, 6, 2 ), # Day
1737 (int)substr( $ts, 0, 4 ) ); # Year
1739 $date = date( 'YmdHis', $t );
1740 wfRestoreWarnings();
1746 * This is meant to be used by time(), date(), and timeanddate() to get
1747 * the date preference they're supposed to use, it should be used in
1751 * function timeanddate([...], $format = true) {
1752 * $datePreference = $this->dateFormat($format);
1757 * @param $usePrefs Mixed: if true, the user's preference is used
1758 * if false, the site/language default is used
1759 * if int/string, assumed to be a format.
1762 function dateFormat( $usePrefs = true ) {
1765 if ( is_bool( $usePrefs ) ) {
1767 $datePreference = $wgUser->getDatePreference();
1769 $datePreference = (string)User
::getDefaultOption( 'date' );
1772 $datePreference = (string)$usePrefs;
1776 if ( $datePreference == '' ) {
1780 return $datePreference;
1784 * Get a format string for a given type and preference
1785 * @param $type string May be date, time or both
1786 * @param $pref string The format name as it appears in Messages*.php
1790 function getDateFormatString( $type, $pref ) {
1791 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1792 if ( $pref == 'default' ) {
1793 $pref = $this->getDefaultDateFormat();
1794 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1796 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1797 if ( is_null( $df ) ) {
1798 $pref = $this->getDefaultDateFormat();
1799 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1802 $this->dateFormatStrings
[$type][$pref] = $df;
1804 return $this->dateFormatStrings
[$type][$pref];
1808 * @param $ts Mixed: the time format which needs to be turned into a
1809 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1810 * @param $adj Bool: whether to adjust the time output according to the
1811 * user configured offset ($timecorrection)
1812 * @param $format Mixed: true to use user's date format preference
1813 * @param $timecorrection String|bool the time offset as returned by
1814 * validateTimeZone() in Special:Preferences
1817 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1818 $ts = wfTimestamp( TS_MW
, $ts );
1820 $ts = $this->userAdjust( $ts, $timecorrection );
1822 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1823 return $this->sprintfDate( $df, $ts );
1827 * @param $ts Mixed: the time format which needs to be turned into a
1828 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1829 * @param $adj Bool: whether to adjust the time output according to the
1830 * user configured offset ($timecorrection)
1831 * @param $format Mixed: true to use user's date format preference
1832 * @param $timecorrection String|bool the time offset as returned by
1833 * validateTimeZone() in Special:Preferences
1836 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1837 $ts = wfTimestamp( TS_MW
, $ts );
1839 $ts = $this->userAdjust( $ts, $timecorrection );
1841 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1842 return $this->sprintfDate( $df, $ts );
1846 * @param $ts Mixed: the time format which needs to be turned into a
1847 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1848 * @param $adj Bool: whether to adjust the time output according to the
1849 * user configured offset ($timecorrection)
1850 * @param $format Mixed: what format to return, if it's false output the
1851 * default one (default true)
1852 * @param $timecorrection String|bool the time offset as returned by
1853 * validateTimeZone() in Special:Preferences
1856 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1857 $ts = wfTimestamp( TS_MW
, $ts );
1859 $ts = $this->userAdjust( $ts, $timecorrection );
1861 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1862 return $this->sprintfDate( $df, $ts );
1866 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1868 * @param $type String: can be 'date', 'time' or 'both'
1869 * @param $ts Mixed: the time format which needs to be turned into a
1870 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1871 * @param $user User object used to get preferences for timezone and format
1872 * @param $options Array, can contain the following keys:
1873 * - 'timecorrection': time correction, can have the following values:
1874 * - true: use user's preference
1875 * - false: don't use time correction
1876 * - integer: value of time correction in minutes
1877 * - 'format': format to use, can have the following values:
1878 * - true: use user's preference
1879 * - false: use default preference
1880 * - string: format to use
1884 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1885 $ts = wfTimestamp( TS_MW
, $ts );
1886 $options +
= array( 'timecorrection' => true, 'format' => true );
1887 if ( $options['timecorrection'] !== false ) {
1888 if ( $options['timecorrection'] === true ) {
1889 $offset = $user->getOption( 'timecorrection' );
1891 $offset = $options['timecorrection'];
1893 $ts = $this->userAdjust( $ts, $offset );
1895 if ( $options['format'] === true ) {
1896 $format = $user->getDatePreference();
1898 $format = $options['format'];
1900 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1901 return $this->sprintfDate( $df, $ts );
1905 * Get the formatted date for the given timestamp and formatted for
1908 * @param $ts Mixed: the time format which needs to be turned into a
1909 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1910 * @param $user User object used to get preferences for timezone and format
1911 * @param $options Array, can contain the following keys:
1912 * - 'timecorrection': time correction, can have the following values:
1913 * - true: use user's preference
1914 * - false: don't use time correction
1915 * - integer: value of time correction in minutes
1916 * - 'format': format to use, can have the following values:
1917 * - true: use user's preference
1918 * - false: use default preference
1919 * - string: format to use
1923 public function userDate( $ts, User
$user, array $options = array() ) {
1924 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1928 * Get the formatted time for the given timestamp and formatted for
1931 * @param $ts Mixed: the time format which needs to be turned into a
1932 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1933 * @param $user User object used to get preferences for timezone and format
1934 * @param $options Array, can contain the following keys:
1935 * - 'timecorrection': time correction, can have the following values:
1936 * - true: use user's preference
1937 * - false: don't use time correction
1938 * - integer: value of time correction in minutes
1939 * - 'format': format to use, can have the following values:
1940 * - true: use user's preference
1941 * - false: use default preference
1942 * - string: format to use
1946 public function userTime( $ts, User
$user, array $options = array() ) {
1947 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1951 * Get the formatted date and time for the given timestamp and formatted for
1954 * @param $ts Mixed: the time format which needs to be turned into a
1955 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1956 * @param $user User object used to get preferences for timezone and format
1957 * @param $options Array, can contain the following keys:
1958 * - 'timecorrection': time correction, can have the following values:
1959 * - true: use user's preference
1960 * - false: don't use time correction
1961 * - integer: value of time correction in minutes
1962 * - 'format': format to use, can have the following values:
1963 * - true: use user's preference
1964 * - false: use default preference
1965 * - string: format to use
1969 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
1970 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
1974 * @param $key string
1975 * @return array|null
1977 function getMessage( $key ) {
1978 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1984 function getAllMessages() {
1985 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1994 function iconv( $in, $out, $string ) {
1995 # This is a wrapper for iconv in all languages except esperanto,
1996 # which does some nasty x-conversions beforehand
1998 # Even with //IGNORE iconv can whine about illegal characters in
1999 # *input* string. We just ignore those too.
2000 # REF: http://bugs.php.net/bug.php?id=37166
2001 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2002 wfSuppressWarnings();
2003 $text = iconv( $in, $out . '//IGNORE', $string );
2004 wfRestoreWarnings();
2008 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2011 * @param $matches array
2012 * @return mixed|string
2014 function ucwordbreaksCallbackAscii( $matches ) {
2015 return $this->ucfirst( $matches[1] );
2019 * @param $matches array
2022 function ucwordbreaksCallbackMB( $matches ) {
2023 return mb_strtoupper( $matches[0] );
2027 * @param $matches array
2030 function ucCallback( $matches ) {
2031 list( $wikiUpperChars ) = self
::getCaseMaps();
2032 return strtr( $matches[1], $wikiUpperChars );
2036 * @param $matches array
2039 function lcCallback( $matches ) {
2040 list( , $wikiLowerChars ) = self
::getCaseMaps();
2041 return strtr( $matches[1], $wikiLowerChars );
2045 * @param $matches array
2048 function ucwordsCallbackMB( $matches ) {
2049 return mb_strtoupper( $matches[0] );
2053 * @param $matches array
2056 function ucwordsCallbackWiki( $matches ) {
2057 list( $wikiUpperChars ) = self
::getCaseMaps();
2058 return strtr( $matches[0], $wikiUpperChars );
2062 * Make a string's first character uppercase
2064 * @param $str string
2068 function ucfirst( $str ) {
2070 if ( $o < 96 ) { // if already uppercase...
2072 } elseif ( $o < 128 ) {
2073 return ucfirst( $str ); // use PHP's ucfirst()
2075 // fall back to more complex logic in case of multibyte strings
2076 return $this->uc( $str, true );
2081 * Convert a string to uppercase
2083 * @param $str string
2084 * @param $first bool
2088 function uc( $str, $first = false ) {
2089 if ( function_exists( 'mb_strtoupper' ) ) {
2091 if ( $this->isMultibyte( $str ) ) {
2092 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2094 return ucfirst( $str );
2097 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2100 if ( $this->isMultibyte( $str ) ) {
2101 $x = $first ?
'^' : '';
2102 return preg_replace_callback(
2103 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2104 array( $this, 'ucCallback' ),
2108 return $first ?
ucfirst( $str ) : strtoupper( $str );
2114 * @param $str string
2115 * @return mixed|string
2117 function lcfirst( $str ) {
2120 return strval( $str );
2121 } elseif ( $o >= 128 ) {
2122 return $this->lc( $str, true );
2123 } elseif ( $o > 96 ) {
2126 $str[0] = strtolower( $str[0] );
2132 * @param $str string
2133 * @param $first bool
2134 * @return mixed|string
2136 function lc( $str, $first = false ) {
2137 if ( function_exists( 'mb_strtolower' ) ) {
2139 if ( $this->isMultibyte( $str ) ) {
2140 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2142 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2145 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2148 if ( $this->isMultibyte( $str ) ) {
2149 $x = $first ?
'^' : '';
2150 return preg_replace_callback(
2151 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2152 array( $this, 'lcCallback' ),
2156 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2162 * @param $str string
2165 function isMultibyte( $str ) {
2166 return (bool)preg_match( '/[\x80-\xff]/', $str );
2170 * @param $str string
2171 * @return mixed|string
2173 function ucwords( $str ) {
2174 if ( $this->isMultibyte( $str ) ) {
2175 $str = $this->lc( $str );
2177 // regexp to find first letter in each word (i.e. after each space)
2178 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2180 // function to use to capitalize a single char
2181 if ( function_exists( 'mb_strtoupper' ) ) {
2182 return preg_replace_callback(
2184 array( $this, 'ucwordsCallbackMB' ),
2188 return preg_replace_callback(
2190 array( $this, 'ucwordsCallbackWiki' ),
2195 return ucwords( strtolower( $str ) );
2200 * capitalize words at word breaks
2202 * @param $str string
2205 function ucwordbreaks( $str ) {
2206 if ( $this->isMultibyte( $str ) ) {
2207 $str = $this->lc( $str );
2209 // since \b doesn't work for UTF-8, we explicitely define word break chars
2210 $breaks = "[ \-\(\)\}\{\.,\?!]";
2212 // find first letter after word break
2213 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2215 if ( function_exists( 'mb_strtoupper' ) ) {
2216 return preg_replace_callback(
2218 array( $this, 'ucwordbreaksCallbackMB' ),
2222 return preg_replace_callback(
2224 array( $this, 'ucwordsCallbackWiki' ),
2229 return preg_replace_callback(
2230 '/\b([\w\x80-\xff]+)\b/',
2231 array( $this, 'ucwordbreaksCallbackAscii' ),
2238 * Return a case-folded representation of $s
2240 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2241 * and $s2 are the same except for the case of their characters. It is not
2242 * necessary for the value returned to make sense when displayed.
2244 * Do *not* perform any other normalisation in this function. If a caller
2245 * uses this function when it should be using a more general normalisation
2246 * function, then fix the caller.
2252 function caseFold( $s ) {
2253 return $this->uc( $s );
2260 function checkTitleEncoding( $s ) {
2261 if ( is_array( $s ) ) {
2262 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2264 # Check for non-UTF-8 URLs
2265 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2270 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2271 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2276 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2282 function fallback8bitEncoding() {
2283 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2287 * Most writing systems use whitespace to break up words.
2288 * Some languages such as Chinese don't conventionally do this,
2289 * which requires special handling when breaking up words for
2294 function hasWordBreaks() {
2299 * Some languages such as Chinese require word segmentation,
2300 * Specify such segmentation when overridden in derived class.
2302 * @param $string String
2305 function segmentByWord( $string ) {
2310 * Some languages have special punctuation need to be normalized.
2311 * Make such changes here.
2313 * @param $string String
2316 function normalizeForSearch( $string ) {
2317 return self
::convertDoubleWidth( $string );
2321 * convert double-width roman characters to single-width.
2322 * range: ff00-ff5f ~= 0020-007f
2324 * @param $string string
2328 protected static function convertDoubleWidth( $string ) {
2329 static $full = null;
2330 static $half = null;
2332 if ( $full === null ) {
2333 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2334 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2335 $full = str_split( $fullWidth, 3 );
2336 $half = str_split( $halfWidth );
2339 $string = str_replace( $full, $half, $string );
2344 * @param $string string
2345 * @param $pattern string
2348 protected static function insertSpace( $string, $pattern ) {
2349 $string = preg_replace( $pattern, " $1 ", $string );
2350 $string = preg_replace( '/ +/', ' ', $string );
2355 * @param $termsArray array
2358 function convertForSearchResult( $termsArray ) {
2359 # some languages, e.g. Chinese, need to do a conversion
2360 # in order for search results to be displayed correctly
2365 * Get the first character of a string.
2370 function firstChar( $s ) {
2373 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2374 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2379 if ( isset( $matches[1] ) ) {
2380 if ( strlen( $matches[1] ) != 3 ) {
2384 // Break down Hangul syllables to grab the first jamo
2385 $code = utf8ToCodepoint( $matches[1] );
2386 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2388 } elseif ( $code < 0xb098 ) {
2389 return "\xe3\x84\xb1";
2390 } elseif ( $code < 0xb2e4 ) {
2391 return "\xe3\x84\xb4";
2392 } elseif ( $code < 0xb77c ) {
2393 return "\xe3\x84\xb7";
2394 } elseif ( $code < 0xb9c8 ) {
2395 return "\xe3\x84\xb9";
2396 } elseif ( $code < 0xbc14 ) {
2397 return "\xe3\x85\x81";
2398 } elseif ( $code < 0xc0ac ) {
2399 return "\xe3\x85\x82";
2400 } elseif ( $code < 0xc544 ) {
2401 return "\xe3\x85\x85";
2402 } elseif ( $code < 0xc790 ) {
2403 return "\xe3\x85\x87";
2404 } elseif ( $code < 0xcc28 ) {
2405 return "\xe3\x85\x88";
2406 } elseif ( $code < 0xce74 ) {
2407 return "\xe3\x85\x8a";
2408 } elseif ( $code < 0xd0c0 ) {
2409 return "\xe3\x85\x8b";
2410 } elseif ( $code < 0xd30c ) {
2411 return "\xe3\x85\x8c";
2412 } elseif ( $code < 0xd558 ) {
2413 return "\xe3\x85\x8d";
2415 return "\xe3\x85\x8e";
2422 function initEncoding() {
2423 # Some languages may have an alternate char encoding option
2424 # (Esperanto X-coding, Japanese furigana conversion, etc)
2425 # If this language is used as the primary content language,
2426 # an override to the defaults can be set here on startup.
2433 function recodeForEdit( $s ) {
2434 # For some languages we'll want to explicitly specify
2435 # which characters make it into the edit box raw
2436 # or are converted in some way or another.
2437 global $wgEditEncoding;
2438 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2441 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2449 function recodeInput( $s ) {
2450 # Take the previous into account.
2451 global $wgEditEncoding;
2452 if ( $wgEditEncoding != '' ) {
2453 $enc = $wgEditEncoding;
2457 if ( $enc == 'UTF-8' ) {
2460 return $this->iconv( $enc, 'UTF-8', $s );
2465 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2466 * also cleans up certain backwards-compatible sequences, converting them
2467 * to the modern Unicode equivalent.
2469 * This is language-specific for performance reasons only.
2475 function normalize( $s ) {
2476 global $wgAllUnicodeFixes;
2477 $s = UtfNormal
::cleanUp( $s );
2478 if ( $wgAllUnicodeFixes ) {
2479 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2480 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2487 * Transform a string using serialized data stored in the given file (which
2488 * must be in the serialized subdirectory of $IP). The file contains pairs
2489 * mapping source characters to destination characters.
2491 * The data is cached in process memory. This will go faster if you have the
2492 * FastStringSearch extension.
2494 * @param $file string
2495 * @param $string string
2499 function transformUsingPairFile( $file, $string ) {
2500 if ( !isset( $this->transformData
[$file] ) ) {
2501 $data = wfGetPrecompiledData( $file );
2502 if ( $data === false ) {
2503 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2505 $this->transformData
[$file] = new ReplacementArray( $data );
2507 return $this->transformData
[$file]->replace( $string );
2511 * For right-to-left language support
2516 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2520 * Return the correct HTML 'dir' attribute value for this language.
2524 return $this->isRTL() ?
'rtl' : 'ltr';
2528 * Return 'left' or 'right' as appropriate alignment for line-start
2529 * for this language's text direction.
2531 * Should be equivalent to CSS3 'start' text-align value....
2535 function alignStart() {
2536 return $this->isRTL() ?
'right' : 'left';
2540 * Return 'right' or 'left' as appropriate alignment for line-end
2541 * for this language's text direction.
2543 * Should be equivalent to CSS3 'end' text-align value....
2547 function alignEnd() {
2548 return $this->isRTL() ?
'left' : 'right';
2552 * A hidden direction mark (LRM or RLM), depending on the language direction
2554 * @param $opposite Boolean Get the direction mark opposite to your language
2557 function getDirMark( $opposite = false ) {
2558 $rtl = "\xE2\x80\x8F";
2559 $ltr = "\xE2\x80\x8E";
2560 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2561 return $this->isRTL() ?
$rtl : $ltr;
2567 function capitalizeAllNouns() {
2568 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2572 * An arrow, depending on the language direction
2576 function getArrow() {
2577 return $this->isRTL() ?
'←' : '→';
2581 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2585 function linkPrefixExtension() {
2586 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2592 function getMagicWords() {
2593 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2596 protected function doMagicHook() {
2597 if ( $this->mMagicHookDone
) {
2600 $this->mMagicHookDone
= true;
2601 wfProfileIn( 'LanguageGetMagic' );
2602 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2603 wfProfileOut( 'LanguageGetMagic' );
2607 * Fill a MagicWord object with data from here
2611 function getMagic( $mw ) {
2612 $this->doMagicHook();
2614 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2615 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2617 $magicWords = $this->getMagicWords();
2618 if ( isset( $magicWords[$mw->mId
] ) ) {
2619 $rawEntry = $magicWords[$mw->mId
];
2625 if ( !is_array( $rawEntry ) ) {
2626 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2628 $mw->mCaseSensitive
= $rawEntry[0];
2629 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2634 * Add magic words to the extension array
2636 * @param $newWords array
2638 function addMagicWordsByLang( $newWords ) {
2639 $fallbackChain = $this->getFallbackLanguages();
2640 $fallbackChain = array_reverse( $fallbackChain );
2641 foreach ( $fallbackChain as $code ) {
2642 if ( isset( $newWords[$code] ) ) {
2643 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2649 * Get special page names, as an associative array
2650 * case folded alias => real name
2652 function getSpecialPageAliases() {
2653 // Cache aliases because it may be slow to load them
2654 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2656 $this->mExtendedSpecialPageAliases
=
2657 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2658 wfRunHooks( 'LanguageGetSpecialPageAliases',
2659 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2662 return $this->mExtendedSpecialPageAliases
;
2666 * Italic is unsuitable for some languages
2668 * @param $text String: the text to be emphasized.
2671 function emphasize( $text ) {
2672 return "<em>$text</em>";
2676 * Normally we output all numbers in plain en_US style, that is
2677 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2678 * point twohundredthirtyfive. However this is not suitable for all
2679 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2680 * Icelandic just want to use commas instead of dots, and dots instead
2681 * of commas like "293.291,235".
2683 * An example of this function being called:
2685 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2688 * See LanguageGu.php for the Gujarati implementation and
2689 * $separatorTransformTable on MessageIs.php for
2690 * the , => . and . => , implementation.
2692 * @todo check if it's viable to use localeconv() for the decimal
2694 * @param $number Mixed: the string to be formatted, should be an integer
2695 * or a floating point number.
2696 * @param $nocommafy Bool: set to true for special numbers like dates
2699 public function formatNum( $number, $nocommafy = false ) {
2700 global $wgTranslateNumerals;
2701 if ( !$nocommafy ) {
2702 $number = $this->commafy( $number );
2703 $s = $this->separatorTransformTable();
2705 $number = strtr( $number, $s );
2709 if ( $wgTranslateNumerals ) {
2710 $s = $this->digitTransformTable();
2712 $number = strtr( $number, $s );
2720 * @param $number string
2723 function parseFormattedNumber( $number ) {
2724 $s = $this->digitTransformTable();
2726 $number = strtr( $number, array_flip( $s ) );
2729 $s = $this->separatorTransformTable();
2731 $number = strtr( $number, array_flip( $s ) );
2734 $number = strtr( $number, array( ',' => '' ) );
2739 * Adds commas to a given number
2744 function commafy( $_ ) {
2745 $digitGroupingPattern = $this->digitGroupingPattern();
2746 if ( $_ === null ) {
2750 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2751 // default grouping is at thousands, use the same for ###,###,### pattern too.
2752 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2754 // Ref: http://cldr.unicode.org/translation/number-patterns
2756 if ( intval( $_ ) < 0 ) {
2757 // For negative numbers apply the algorithm like positive number and add sign.
2759 $_ = substr( $_, 1 );
2761 $numberpart = array();
2762 $decimalpart = array();
2763 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2764 preg_match( "/\d+/", $_, $numberpart );
2765 preg_match( "/\.\d*/", $_, $decimalpart );
2766 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2767 if ( $groupedNumber === $_ ) {
2768 // the string does not have any number part. Eg: .12345
2769 return $sign . $groupedNumber;
2771 $start = $end = strlen( $numberpart[0] );
2772 while ( $start > 0 ) {
2773 $match = $matches[0][$numMatches -1] ;
2774 $matchLen = strlen( $match );
2775 $start = $end - $matchLen;
2779 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2781 if ( $numMatches > 1 ) {
2782 // use the last pattern for the rest of the number
2786 $groupedNumber = "," . $groupedNumber;
2789 return $sign . $groupedNumber;
2795 function digitGroupingPattern() {
2796 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2802 function digitTransformTable() {
2803 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2809 function separatorTransformTable() {
2810 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2814 * Take a list of strings and build a locale-friendly comma-separated
2815 * list, using the local comma-separator message.
2816 * The last two strings are chained with an "and".
2821 function listToText( array $l ) {
2823 $m = count( $l ) - 1;
2825 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2827 for ( $i = $m; $i >= 0; $i-- ) {
2830 } elseif ( $i == $m - 1 ) {
2831 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2833 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2841 * Take a list of strings and build a locale-friendly comma-separated
2842 * list, using the local comma-separator message.
2843 * @param $list array of strings to put in a comma list
2846 function commaList( array $list ) {
2850 array( 'parsemag', 'escapenoentities', 'language' => $this )
2857 * Take a list of strings and build a locale-friendly semicolon-separated
2858 * list, using the local semicolon-separator message.
2859 * @param $list array of strings to put in a semicolon list
2862 function semicolonList( array $list ) {
2865 'semicolon-separator',
2866 array( 'parsemag', 'escapenoentities', 'language' => $this )
2873 * Same as commaList, but separate it with the pipe instead.
2874 * @param $list array of strings to put in a pipe list
2877 function pipeList( array $list ) {
2881 array( 'escapenoentities', 'language' => $this )
2888 * Truncate a string to a specified length in bytes, appending an optional
2889 * string (e.g. for ellipses)
2891 * The database offers limited byte lengths for some columns in the database;
2892 * multi-byte character sets mean we need to ensure that only whole characters
2893 * are included, otherwise broken characters can be passed to the user
2895 * If $length is negative, the string will be truncated from the beginning
2897 * @param $string String to truncate
2898 * @param $length Int: maximum length (including ellipses)
2899 * @param $ellipsis String to append to the truncated text
2900 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2901 * $adjustLength was introduced in 1.18, before that behaved as if false.
2904 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2905 # Use the localized ellipsis character
2906 if ( $ellipsis == '...' ) {
2907 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2909 # Check if there is no need to truncate
2910 if ( $length == 0 ) {
2911 return $ellipsis; // convention
2912 } elseif ( strlen( $string ) <= abs( $length ) ) {
2913 return $string; // no need to truncate
2915 $stringOriginal = $string;
2916 # If ellipsis length is >= $length then we can't apply $adjustLength
2917 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2918 $string = $ellipsis; // this can be slightly unexpected
2919 # Otherwise, truncate and add ellipsis...
2921 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2922 if ( $length > 0 ) {
2923 $length -= $eLength;
2924 $string = substr( $string, 0, $length ); // xyz...
2925 $string = $this->removeBadCharLast( $string );
2926 $string = $string . $ellipsis;
2928 $length +
= $eLength;
2929 $string = substr( $string, $length ); // ...xyz
2930 $string = $this->removeBadCharFirst( $string );
2931 $string = $ellipsis . $string;
2934 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2935 # This check is *not* redundant if $adjustLength, due to the single case where
2936 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2937 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2940 return $stringOriginal;
2945 * Remove bytes that represent an incomplete Unicode character
2946 * at the end of string (e.g. bytes of the char are missing)
2948 * @param $string String
2951 protected function removeBadCharLast( $string ) {
2952 if ( $string != '' ) {
2953 $char = ord( $string[strlen( $string ) - 1] );
2955 if ( $char >= 0xc0 ) {
2956 # We got the first byte only of a multibyte char; remove it.
2957 $string = substr( $string, 0, -1 );
2958 } elseif ( $char >= 0x80 &&
2959 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2960 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2962 # We chopped in the middle of a character; remove it
2970 * Remove bytes that represent an incomplete Unicode character
2971 * at the start of string (e.g. bytes of the char are missing)
2973 * @param $string String
2976 protected function removeBadCharFirst( $string ) {
2977 if ( $string != '' ) {
2978 $char = ord( $string[0] );
2979 if ( $char >= 0x80 && $char < 0xc0 ) {
2980 # We chopped in the middle of a character; remove the whole thing
2981 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2988 * Truncate a string of valid HTML to a specified length in bytes,
2989 * appending an optional string (e.g. for ellipses), and return valid HTML
2991 * This is only intended for styled/linked text, such as HTML with
2992 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2993 * Also, this will not detect things like "display:none" CSS.
2995 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2997 * @param string $text HTML string to truncate
2998 * @param int $length (zero/positive) Maximum length (including ellipses)
2999 * @param string $ellipsis String to append to the truncated text
3002 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3003 # Use the localized ellipsis character
3004 if ( $ellipsis == '...' ) {
3005 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3007 # Check if there is clearly no need to truncate
3008 if ( $length <= 0 ) {
3009 return $ellipsis; // no text shown, nothing to format (convention)
3010 } elseif ( strlen( $text ) <= $length ) {
3011 return $text; // string short enough even *with* HTML (short-circuit)
3014 $dispLen = 0; // innerHTML legth so far
3015 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3016 $tagType = 0; // 0-open, 1-close
3017 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3018 $entityState = 0; // 0-not entity, 1-entity
3019 $tag = $ret = ''; // accumulated tag name, accumulated result string
3020 $openTags = array(); // open tag stack
3021 $maybeState = null; // possible truncation state
3023 $textLen = strlen( $text );
3024 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3025 for ( $pos = 0; true; ++
$pos ) {
3026 # Consider truncation once the display length has reached the maximim.
3027 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3028 # Check that we're not in the middle of a bracket/entity...
3029 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3030 if ( !$testingEllipsis ) {
3031 $testingEllipsis = true;
3032 # Save where we are; we will truncate here unless there turn out to
3033 # be so few remaining characters that truncation is not necessary.
3034 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3035 $maybeState = array( $ret, $openTags ); // save state
3037 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3038 # String in fact does need truncation, the truncation point was OK.
3039 list( $ret, $openTags ) = $maybeState; // reload state
3040 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3041 $ret .= $ellipsis; // add ellipsis
3045 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3047 # Read the next char...
3049 $lastCh = $pos ?
$text[$pos - 1] : '';
3050 $ret .= $ch; // add to result string
3052 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3053 $entityState = 0; // for bad HTML
3054 $bracketState = 1; // tag started (checking for backslash)
3055 } elseif ( $ch == '>' ) {
3056 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3057 $entityState = 0; // for bad HTML
3058 $bracketState = 0; // out of brackets
3059 } elseif ( $bracketState == 1 ) {
3061 $tagType = 1; // close tag (e.g. "</span>")
3063 $tagType = 0; // open tag (e.g. "<span>")
3066 $bracketState = 2; // building tag name
3067 } elseif ( $bracketState == 2 ) {
3071 // Name found (e.g. "<a href=..."), add on tag attributes...
3072 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3074 } elseif ( $bracketState == 0 ) {
3075 if ( $entityState ) {
3078 $dispLen++
; // entity is one displayed char
3081 if ( $neLength == 0 && !$maybeState ) {
3082 // Save state without $ch. We want to *hit* the first
3083 // display char (to get tags) but not *use* it if truncating.
3084 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3087 $entityState = 1; // entity found, (e.g. " ")
3089 $dispLen++
; // this char is displayed
3090 // Add the next $max display text chars after this in one swoop...
3091 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3092 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3093 $dispLen +
= $skipped;
3099 // Close the last tag if left unclosed by bad HTML
3100 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3101 while ( count( $openTags ) > 0 ) {
3102 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3108 * truncateHtml() helper function
3109 * like strcspn() but adds the skipped chars to $ret
3118 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3119 if ( $len === null ) {
3120 $len = -1; // -1 means "no limit" for strcspn
3121 } elseif ( $len < 0 ) {
3125 if ( $start < strlen( $text ) ) {
3126 $skipCount = strcspn( $text, $search, $start, $len );
3127 $ret .= substr( $text, $start, $skipCount );
3133 * truncateHtml() helper function
3134 * (a) push or pop $tag from $openTags as needed
3135 * (b) clear $tag value
3136 * @param &$tag string Current HTML tag name we are looking at
3137 * @param $tagType int (0-open tag, 1-close tag)
3138 * @param $lastCh string Character before the '>' that ended this tag
3139 * @param &$openTags array Open tag stack (not accounting for $tag)
3141 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3142 $tag = ltrim( $tag );
3144 if ( $tagType == 0 && $lastCh != '/' ) {
3145 $openTags[] = $tag; // tag opened (didn't close itself)
3146 } elseif ( $tagType == 1 ) {
3147 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3148 array_pop( $openTags ); // tag closed
3156 * Grammatical transformations, needed for inflected languages
3157 * Invoked by putting {{grammar:case|word}} in a message
3159 * @param $word string
3160 * @param $case string
3163 function convertGrammar( $word, $case ) {
3164 global $wgGrammarForms;
3165 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3166 return $wgGrammarForms[$this->getCode()][$case][$word];
3172 * Provides an alternative text depending on specified gender.
3173 * Usage {{gender:username|masculine|feminine|neutral}}.
3174 * username is optional, in which case the gender of current user is used,
3175 * but only in (some) interface messages; otherwise default gender is used.
3177 * If no forms are given, an empty string is returned. If only one form is
3178 * given, it will be returned unconditionally. These details are implied by
3179 * the caller and cannot be overridden in subclasses.
3181 * If more than one form is given, the default is to use the neutral one
3182 * if it is specified, and to use the masculine one otherwise. These
3183 * details can be overridden in subclasses.
3185 * @param $gender string
3186 * @param $forms array
3190 function gender( $gender, $forms ) {
3191 if ( !count( $forms ) ) {
3194 $forms = $this->preConvertPlural( $forms, 2 );
3195 if ( $gender === 'male' ) {
3198 if ( $gender === 'female' ) {
3201 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3205 * Plural form transformations, needed for some languages.
3206 * For example, there are 3 form of plural in Russian and Polish,
3207 * depending on "count mod 10". See [[w:Plural]]
3208 * For English it is pretty simple.
3210 * Invoked by putting {{plural:count|wordform1|wordform2}}
3211 * or {{plural:count|wordform1|wordform2|wordform3}}
3213 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3215 * @param $count Integer: non-localized number
3216 * @param $forms Array: different plural forms
3217 * @return string Correct form of plural for $count in this language
3219 function convertPlural( $count, $forms ) {
3220 if ( !count( $forms ) ) {
3223 $forms = $this->preConvertPlural( $forms, 2 );
3225 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3229 * Checks that convertPlural was given an array and pads it to requested
3230 * amount of forms by copying the last one.
3232 * @param $count Integer: How many forms should there be at least
3233 * @param $forms Array of forms given to convertPlural
3234 * @return array Padded array of forms or an exception if not an array
3236 protected function preConvertPlural( /* Array */ $forms, $count ) {
3237 while ( count( $forms ) < $count ) {
3238 $forms[] = $forms[count( $forms ) - 1];
3244 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3245 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3246 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3247 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3250 * @param $str String: the validated block duration in English
3251 * @return string Somehow translated block duration
3252 * @see LanguageFi.php for example implementation
3254 function translateBlockExpiry( $str ) {
3255 $duration = SpecialBlock
::getSuggestedDurations( $this );
3256 foreach ( $duration as $show => $value ) {
3257 if ( strcmp( $str, $value ) == 0 ) {
3258 return htmlspecialchars( trim( $show ) );
3262 // Since usually only infinite or indefinite is only on list, so try
3263 // equivalents if still here.
3264 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3265 if ( in_array( $str, $indefs ) ) {
3266 foreach ( $indefs as $val ) {
3267 $show = array_search( $val, $duration, true );
3268 if ( $show !== false ) {
3269 return htmlspecialchars( trim( $show ) );
3273 // If all else fails, return the original string.
3278 * languages like Chinese need to be segmented in order for the diff
3281 * @param $text String
3284 public function segmentForDiff( $text ) {
3289 * and unsegment to show the result
3291 * @param $text String
3294 public function unsegmentForDiff( $text ) {
3299 * Return the LanguageConverter used in the Language
3302 * @return LanguageConverter
3304 public function getConverter() {
3305 return $this->mConverter
;
3309 * convert text to all supported variants
3311 * @param $text string
3314 public function autoConvertToAllVariants( $text ) {
3315 return $this->mConverter
->autoConvertToAllVariants( $text );
3319 * convert text to different variants of a language.
3321 * @param $text string
3324 public function convert( $text ) {
3325 return $this->mConverter
->convert( $text );
3329 * Convert a Title object to a string in the preferred variant
3331 * @param $title Title
3334 public function convertTitle( $title ) {
3335 return $this->mConverter
->convertTitle( $title );
3339 * Check if this is a language with variants
3343 public function hasVariants() {
3344 return sizeof( $this->getVariants() ) > 1;
3348 * Check if the language has the specific variant
3351 * @param $variant string
3354 public function hasVariant( $variant ) {
3355 return (bool)$this->mConverter
->validateVariant( $variant );
3359 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3361 * @param $text string
3364 public function armourMath( $text ) {
3365 return $this->mConverter
->armourMath( $text );
3369 * Perform output conversion on a string, and encode for safe HTML output.
3370 * @param $text String text to be converted
3371 * @param $isTitle Bool whether this conversion is for the article title
3373 * @todo this should get integrated somewhere sane
3375 public function convertHtml( $text, $isTitle = false ) {
3376 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3380 * @param $key string
3383 public function convertCategoryKey( $key ) {
3384 return $this->mConverter
->convertCategoryKey( $key );
3388 * Get the list of variants supported by this language
3389 * see sample implementation in LanguageZh.php
3391 * @return array an array of language codes
3393 public function getVariants() {
3394 return $this->mConverter
->getVariants();
3400 public function getPreferredVariant() {
3401 return $this->mConverter
->getPreferredVariant();
3407 public function getDefaultVariant() {
3408 return $this->mConverter
->getDefaultVariant();
3414 public function getURLVariant() {
3415 return $this->mConverter
->getURLVariant();
3419 * If a language supports multiple variants, it is
3420 * possible that non-existing link in one variant
3421 * actually exists in another variant. this function
3422 * tries to find it. See e.g. LanguageZh.php
3424 * @param $link String: the name of the link
3425 * @param $nt Mixed: the title object of the link
3426 * @param $ignoreOtherCond Boolean: to disable other conditions when
3427 * we need to transclude a template or update a category's link
3428 * @return null the input parameters may be modified upon return
3430 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3431 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3435 * If a language supports multiple variants, converts text
3436 * into an array of all possible variants of the text:
3437 * 'variant' => text in that variant
3439 * @deprecated since 1.17 Use autoConvertToAllVariants()
3441 * @param $text string
3445 public function convertLinkToAllVariants( $text ) {
3446 return $this->mConverter
->convertLinkToAllVariants( $text );
3450 * returns language specific options used by User::getPageRenderHash()
3451 * for example, the preferred language variant
3455 function getExtraHashOptions() {
3456 return $this->mConverter
->getExtraHashOptions();
3460 * For languages that support multiple variants, the title of an
3461 * article may be displayed differently in different variants. this
3462 * function returns the apporiate title defined in the body of the article.
3466 public function getParsedTitle() {
3467 return $this->mConverter
->getParsedTitle();
3471 * Enclose a string with the "no conversion" tag. This is used by
3472 * various functions in the Parser
3474 * @param $text String: text to be tagged for no conversion
3475 * @param $noParse bool
3476 * @return string the tagged text
3478 public function markNoConversion( $text, $noParse = false ) {
3479 return $this->mConverter
->markNoConversion( $text, $noParse );
3483 * A regular expression to match legal word-trailing characters
3484 * which should be merged onto a link of the form [[foo]]bar.
3488 public function linkTrail() {
3489 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3495 function getLangObj() {
3500 * Get the RFC 3066 code for this language object
3504 public function getCode() {
3505 return $this->mCode
;
3509 * Get the code in Bcp47 format which we can use
3510 * inside of html lang="" tags.
3514 public function getHtmlCode() {
3515 if ( is_null( $this->mHtmlCode
) ) {
3516 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3518 return $this->mHtmlCode
;
3522 * @param $code string
3524 public function setCode( $code ) {
3525 $this->mCode
= $code;
3526 // Ensure we don't leave an incorrect html code lying around
3527 $this->mHtmlCode
= null;
3531 * Get the name of a file for a certain language code
3532 * @param $prefix string Prepend this to the filename
3533 * @param $code string Language code
3534 * @param $suffix string Append this to the filename
3535 * @return string $prefix . $mangledCode . $suffix
3537 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3538 // Protect against path traversal
3539 if ( !Language
::isValidCode( $code )
3540 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3542 throw new MWException( "Invalid language code \"$code\"" );
3545 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3549 * Get the language code from a file name. Inverse of getFileName()
3550 * @param $filename string $prefix . $languageCode . $suffix
3551 * @param $prefix string Prefix before the language code
3552 * @param $suffix string Suffix after the language code
3553 * @return string Language code, or false if $prefix or $suffix isn't found
3555 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3557 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3558 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3559 if ( !count( $m ) ) {
3562 return str_replace( '_', '-', strtolower( $m[1] ) );
3566 * @param $code string
3569 public static function getMessagesFileName( $code ) {
3571 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3572 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3577 * @param $code string
3580 public static function getClassFileName( $code ) {
3582 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3586 * Get the first fallback for a given language.
3588 * @param $code string
3590 * @return bool|string
3592 public static function getFallbackFor( $code ) {
3593 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3596 $fallbacks = self
::getFallbacksFor( $code );
3597 $first = array_shift( $fallbacks );
3603 * Get the ordered list of fallback languages.
3606 * @param $code string Language code
3609 public static function getFallbacksFor( $code ) {
3610 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3613 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3614 $v = array_map( 'trim', explode( ',', $v ) );
3615 if ( $v[count( $v ) - 1] !== 'en' ) {
3623 * Get all messages for a given language
3624 * WARNING: this may take a long time. If you just need all message *keys*
3625 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3627 * @param $code string
3631 public static function getMessagesFor( $code ) {
3632 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3636 * Get a message for a given language
3638 * @param $key string
3639 * @param $code string
3643 public static function getMessageFor( $key, $code ) {
3644 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3648 * Get all message keys for a given language. This is a faster alternative to
3649 * array_keys( Language::getMessagesFor( $code ) )
3652 * @param $code string Language code
3653 * @return array of message keys (strings)
3655 public static function getMessageKeysFor( $code ) {
3656 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3663 function fixVariableInNamespace( $talk ) {
3664 if ( strpos( $talk, '$1' ) === false ) {
3668 global $wgMetaNamespace;
3669 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3671 # Allow grammar transformations
3672 # Allowing full message-style parsing would make simple requests
3673 # such as action=raw much more expensive than they need to be.
3674 # This will hopefully cover most cases.
3675 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3676 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3677 return str_replace( ' ', '_', $talk );
3684 function replaceGrammarInNamespace( $m ) {
3685 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3689 * @throws MWException
3692 static function getCaseMaps() {
3693 static $wikiUpperChars, $wikiLowerChars;
3694 if ( isset( $wikiUpperChars ) ) {
3695 return array( $wikiUpperChars, $wikiLowerChars );
3698 wfProfileIn( __METHOD__
);
3699 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3700 if ( $arr === false ) {
3701 throw new MWException(
3702 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3704 $wikiUpperChars = $arr['wikiUpperChars'];
3705 $wikiLowerChars = $arr['wikiLowerChars'];
3706 wfProfileOut( __METHOD__
);
3707 return array( $wikiUpperChars, $wikiLowerChars );
3711 * Decode an expiry (block, protection, etc) which has come from the DB
3713 * @param $expiry String: Database expiry String
3714 * @param $format Bool|Int true to process using language functions, or TS_ constant
3715 * to return the expiry in a given timestamp
3718 public function formatExpiry( $expiry, $format = true ) {
3719 static $infinity, $infinityMsg;
3720 if ( $infinity === null ) {
3721 $infinityMsg = wfMessage( 'infiniteblock' );
3722 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3725 if ( $expiry == '' ||
$expiry == $infinity ) {
3726 return $format === true
3730 return $format === true
3731 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3732 : wfTimestamp( $format, $expiry );
3738 * @param $seconds int|float
3739 * @param $format Array Optional
3740 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3741 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3742 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3743 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3746 function formatTimePeriod( $seconds, $format = array() ) {
3747 if ( !is_array( $format ) ) {
3748 $format = array( 'avoid' => $format ); // For backwards compatibility
3750 if ( !isset( $format['avoid'] ) ) {
3751 $format['avoid'] = false;
3753 if ( !isset( $format['noabbrevs' ] ) ) {
3754 $format['noabbrevs'] = false;
3756 $secondsMsg = wfMessage(
3757 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3758 $minutesMsg = wfMessage(
3759 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3760 $hoursMsg = wfMessage(
3761 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3762 $daysMsg = wfMessage(
3763 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3765 if ( round( $seconds * 10 ) < 100 ) {
3766 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3767 $s = $secondsMsg->params( $s )->text();
3768 } elseif ( round( $seconds ) < 60 ) {
3769 $s = $this->formatNum( round( $seconds ) );
3770 $s = $secondsMsg->params( $s )->text();
3771 } elseif ( round( $seconds ) < 3600 ) {
3772 $minutes = floor( $seconds / 60 );
3773 $secondsPart = round( fmod( $seconds, 60 ) );
3774 if ( $secondsPart == 60 ) {
3778 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3780 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3781 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3782 $hours = floor( $seconds / 3600 );
3783 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3784 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3785 if ( $secondsPart == 60 ) {
3789 if ( $minutes == 60 ) {
3793 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3795 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3796 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3797 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3800 $days = floor( $seconds / 86400 );
3801 if ( $format['avoid'] === 'avoidminutes' ) {
3802 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3803 if ( $hours == 24 ) {
3807 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3809 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3810 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3811 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3812 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3813 if ( $minutes == 60 ) {
3817 if ( $hours == 24 ) {
3821 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3823 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3825 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3827 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3829 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3836 * Format a bitrate for output, using an appropriate
3837 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3839 * This use base 1000. For base 1024 use formatSize(), for another base
3840 * see formatComputingNumbers()
3845 function formatBitrate( $bps ) {
3846 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3850 * @param $size int Size of the unit
3851 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3852 * @param $messageKey string Message key to be uesd
3855 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3857 return str_replace( '$1', $this->formatNum( $size ),
3858 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3861 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3864 $maxIndex = count( $sizes ) - 1;
3865 while ( $size >= $boundary && $index < $maxIndex ) {
3870 // For small sizes no decimal places necessary
3873 // For MB and bigger two decimal places are smarter
3876 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3878 $size = round( $size, $round );
3879 $text = $this->getMessageFromDB( $msg );
3880 return str_replace( '$1', $this->formatNum( $size ), $text );
3884 * Format a size in bytes for output, using an appropriate
3885 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3887 * This method use base 1024. For base 1000 use formatBitrate(), for
3888 * another base see formatComputingNumbers()
3890 * @param $size int Size to format
3891 * @return string Plain text (not HTML)
3893 function formatSize( $size ) {
3894 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3898 * Make a list item, used by various special pages
3900 * @param $page String Page link
3901 * @param $details String Text between brackets
3902 * @param $oppositedm Boolean Add the direction mark opposite to your
3903 * language, to display text properly
3906 function specialList( $page, $details, $oppositedm = true ) {
3907 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3908 $this->getDirMark();
3909 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3910 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3911 return $page . $details;
3915 * Generate (prev x| next x) (20|50|100...) type links for paging
3917 * @param $title Title object to link
3918 * @param $offset Integer offset parameter
3919 * @param $limit Integer limit parameter
3920 * @param $query String optional URL query parameter string
3921 * @param $atend Bool optional param for specified if this is the last page
3924 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3925 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3927 # Make 'previous' link
3928 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3929 if ( $offset > 0 ) {
3930 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3931 $query, $prev, 'prevn-title', 'mw-prevlink' );
3933 $plink = htmlspecialchars( $prev );
3937 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3939 $nlink = htmlspecialchars( $next );
3941 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3942 $query, $next, 'prevn-title', 'mw-nextlink' );
3945 # Make links to set number of items per page
3946 $numLinks = array();
3947 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
3948 $numLinks[] = $this->numLink( $title, $offset, $num,
3949 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3952 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3953 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
3957 * Helper function for viewPrevNext() that generates links
3959 * @param $title Title object to link
3960 * @param $offset Integer offset parameter
3961 * @param $limit Integer limit parameter
3962 * @param $query Array extra query parameters
3963 * @param $link String text to use for the link; will be escaped
3964 * @param $tooltipMsg String name of the message to use as tooltip
3965 * @param $class String value of the "class" attribute of the link
3966 * @return String HTML fragment
3968 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
3969 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
3970 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3971 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
3972 'title' => $tooltip, 'class' => $class ), $link );
3976 * Get the conversion rule title, if any.
3980 public function getConvRuleTitle() {
3981 return $this->mConverter
->getConvRuleTitle();