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
33 function __construct( $langobj ) { $this->mLang
= $langobj; }
34 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
35 function convert( $t ) { return $t; }
36 function convertTitle( $t ) { return $t->getPrefixedText(); }
37 function getVariants() { return array( $this->mLang
->getCode() ); }
38 function getPreferredVariant() { return $this->mLang
->getCode(); }
39 function getDefaultVariant() { return $this->mLang
->getCode(); }
40 function getURLVariant() { return ''; }
41 function getConvRuleTitle() { return false; }
42 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
43 function getExtraHashOptions() { return ''; }
44 function getParsedTitle() { return ''; }
45 function markNoConversion( $text, $noParse = false ) { return $text; }
46 function convertCategoryKey( $key ) { return $key; }
47 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
48 function armourMath( $text ) { return $text; }
52 * Internationalisation code
58 * @var LanguageConverter
62 var $mVariants, $mCode, $mLoaded = false;
63 var $mMagicExtensions = array(), $mMagicHookDone = false;
64 private $mHtmlCode = null;
66 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
67 var $dateFormatStrings = array();
68 var $mExtendedSpecialPageAliases;
71 * ReplacementArray object caches
73 var $transformData = array();
76 * @var LocalisationCache
78 static public $dataCache;
80 static public $mLangObjCache = array();
82 static public $mWeekdayMsgs = array(
83 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
87 static public $mWeekdayAbbrevMsgs = array(
88 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
91 static public $mMonthMsgs = array(
92 'january', 'february', 'march', 'april', 'may_long', 'june',
93 'july', 'august', 'september', 'october', 'november',
96 static public $mMonthGenMsgs = array(
97 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
98 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
101 static public $mMonthAbbrevMsgs = array(
102 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
103 'sep', 'oct', 'nov', 'dec'
106 static public $mIranianCalendarMonthMsgs = array(
107 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
108 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
109 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
110 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
113 static public $mHebrewCalendarMonthMsgs = array(
114 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
115 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
116 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
117 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
118 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
121 static public $mHebrewCalendarMonthGenMsgs = array(
122 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
123 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
124 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
125 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
126 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
129 static public $mHijriCalendarMonthMsgs = array(
130 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
131 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
132 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
133 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
137 * Get a cached language object for a given language code
138 * @param $code String
141 static function factory( $code ) {
142 if ( !isset( self
::$mLangObjCache[$code] ) ) {
143 if ( count( self
::$mLangObjCache ) > 10 ) {
144 // Don't keep a billion objects around, that's stupid.
145 self
::$mLangObjCache = array();
147 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
149 return self
::$mLangObjCache[$code];
153 * Create a language object for a given language code
154 * @param $code String
157 protected static function newFromCode( $code ) {
158 // Protect against path traversal below
159 if ( !Language
::isValidCode( $code )
160 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
162 throw new MWException( "Invalid language code \"$code\"" );
165 if ( !Language
::isValidBuiltInCode( $code ) ) {
166 // It's not possible to customise this code with class files, so
167 // just return a Language object. This is to support uselang= hacks.
168 $lang = new Language
;
169 $lang->setCode( $code );
173 // Check if there is a language class for the code
174 $class = self
::classFromCode( $code );
175 self
::preloadLanguageClass( $class );
176 if ( MWInit
::classExists( $class ) ) {
181 // Keep trying the fallback list until we find an existing class
182 $fallbacks = Language
::getFallbacksFor( $code );
183 foreach ( $fallbacks as $fallbackCode ) {
184 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
185 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
188 $class = self
::classFromCode( $fallbackCode );
189 self
::preloadLanguageClass( $class );
190 if ( MWInit
::classExists( $class ) ) {
191 $lang = Language
::newFromCode( $fallbackCode );
192 $lang->setCode( $code );
197 throw new MWException( "Invalid fallback sequence for language '$code'" );
201 * Returns true if a language code string is of a valid form, whether or
202 * not it exists. This includes codes which are used solely for
203 * customisation via the MediaWiki namespace.
205 * @param $code string
209 public static function isValidCode( $code ) {
211 strcspn( $code, ":/\\\000" ) === strlen( $code )
212 && !preg_match( Title
::getTitleInvalidRegex(), $code );
216 * Returns true if a language code is of a valid form for the purposes of
217 * internal customisation of MediaWiki, via Messages*.php.
219 * @param $code string
224 public static function isValidBuiltInCode( $code ) {
225 return preg_match( '/^[a-z0-9-]+$/i', $code );
230 * @return String Name of the language class
232 public static function classFromCode( $code ) {
233 if ( $code == 'en' ) {
236 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
241 * Includes language class files
243 * @param $class string Name of the language class
245 public static function preloadLanguageClass( $class ) {
248 if ( $class === 'Language' ) {
252 if ( !defined( 'MW_COMPILED' ) ) {
253 // Preload base classes to work around APC/PHP5 bug
254 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
255 include_once( "$IP/languages/classes/$class.deps.php" );
257 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
258 include_once( "$IP/languages/classes/$class.php" );
264 * Get the LocalisationCache instance
266 * @return LocalisationCache
268 public static function getLocalisationCache() {
269 if ( is_null( self
::$dataCache ) ) {
270 global $wgLocalisationCacheConf;
271 $class = $wgLocalisationCacheConf['class'];
272 self
::$dataCache = new $class( $wgLocalisationCacheConf );
274 return self
::$dataCache;
277 function __construct() {
278 $this->mConverter
= new FakeConverter( $this );
279 // Set the code to the name of the descendant
280 if ( get_class( $this ) == 'Language' ) {
283 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
285 self
::getLocalisationCache();
289 * Reduce memory usage
291 function __destruct() {
292 foreach ( $this as $name => $value ) {
293 unset( $this->$name );
298 * Hook which will be called if this is the content language.
299 * Descendants can use this to register hook functions or modify globals
301 function initContLang() { }
304 * Same as getFallbacksFor for current language.
306 * @deprecated in 1.19
308 function getFallbackLanguageCode() {
309 wfDeprecated( __METHOD__
);
310 return self
::getFallbackFor( $this->mCode
);
317 function getFallbackLanguages() {
318 return self
::getFallbacksFor( $this->mCode
);
322 * Exports $wgBookstoreListEn
325 function getBookstoreList() {
326 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
332 function getNamespaces() {
333 if ( is_null( $this->namespaceNames
) ) {
334 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
336 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
337 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
339 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
341 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
342 if ( $wgMetaNamespaceTalk ) {
343 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
345 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
346 $this->namespaceNames
[NS_PROJECT_TALK
] =
347 $this->fixVariableInNamespace( $talk );
350 # Sometimes a language will be localised but not actually exist on this wiki.
351 foreach ( $this->namespaceNames
as $key => $text ) {
352 if ( !isset( $validNamespaces[$key] ) ) {
353 unset( $this->namespaceNames
[$key] );
357 # The above mixing may leave namespaces out of canonical order.
358 # Re-order by namespace ID number...
359 ksort( $this->namespaceNames
);
361 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
363 return $this->namespaceNames
;
367 * A convenience function that returns the same thing as
368 * getNamespaces() except with the array values changed to ' '
369 * where it found '_', useful for producing output to be displayed
370 * e.g. in <select> forms.
374 function getFormattedNamespaces() {
375 $ns = $this->getNamespaces();
376 foreach ( $ns as $k => $v ) {
377 $ns[$k] = strtr( $v, '_', ' ' );
383 * Get a namespace value by key
385 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
386 * echo $mw_ns; // prints 'MediaWiki'
389 * @param $index Int: the array key of the namespace to return
390 * @return mixed, string if the namespace value exists, otherwise false
392 function getNsText( $index ) {
393 $ns = $this->getNamespaces();
394 return isset( $ns[$index] ) ?
$ns[$index] : false;
398 * A convenience function that returns the same thing as
399 * getNsText() except with '_' changed to ' ', useful for
402 * @param $index string
406 function getFormattedNsText( $index ) {
407 $ns = $this->getNsText( $index );
408 return strtr( $ns, '_', ' ' );
412 * Returns gender-dependent namespace alias if available.
413 * @param $index Int: namespace index
414 * @param $gender String: gender key (male, female... )
418 function getGenderNsText( $index, $gender ) {
419 global $wgExtraGenderNamespaces;
421 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
422 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
426 * Whether this language makes distinguishes genders for example in
431 function needsGenderDistinction() {
432 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
433 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
434 // $wgExtraGenderNamespaces overrides everything
436 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
437 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
438 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
441 // Check what is in i18n files
442 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
443 return count( $aliases ) > 0;
448 * Get a namespace key by value, case insensitive.
449 * Only matches namespace names for the current language, not the
450 * canonical ones defined in Namespace.php.
452 * @param $text String
453 * @return mixed An integer if $text is a valid value otherwise false
455 function getLocalNsIndex( $text ) {
456 $lctext = $this->lc( $text );
457 $ids = $this->getNamespaceIds();
458 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
464 function getNamespaceAliases() {
465 if ( is_null( $this->namespaceAliases
) ) {
466 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
470 foreach ( $aliases as $name => $index ) {
471 if ( $index === NS_PROJECT_TALK
) {
472 unset( $aliases[$name] );
473 $name = $this->fixVariableInNamespace( $name );
474 $aliases[$name] = $index;
479 global $wgExtraGenderNamespaces;
480 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
481 foreach ( $genders as $index => $forms ) {
482 foreach ( $forms as $alias ) {
483 $aliases[$alias] = $index;
487 $this->namespaceAliases
= $aliases;
489 return $this->namespaceAliases
;
495 function getNamespaceIds() {
496 if ( is_null( $this->mNamespaceIds
) ) {
497 global $wgNamespaceAliases;
498 # Put namespace names and aliases into a hashtable.
499 # If this is too slow, then we should arrange it so that it is done
500 # before caching. The catch is that at pre-cache time, the above
501 # class-specific fixup hasn't been done.
502 $this->mNamespaceIds
= array();
503 foreach ( $this->getNamespaces() as $index => $name ) {
504 $this->mNamespaceIds
[$this->lc( $name )] = $index;
506 foreach ( $this->getNamespaceAliases() as $name => $index ) {
507 $this->mNamespaceIds
[$this->lc( $name )] = $index;
509 if ( $wgNamespaceAliases ) {
510 foreach ( $wgNamespaceAliases as $name => $index ) {
511 $this->mNamespaceIds
[$this->lc( $name )] = $index;
515 return $this->mNamespaceIds
;
519 * Get a namespace key by value, case insensitive. Canonical namespace
520 * names override custom ones defined for the current language.
522 * @param $text String
523 * @return mixed An integer if $text is a valid value otherwise false
525 function getNsIndex( $text ) {
526 $lctext = $this->lc( $text );
527 $ns = MWNamespace
::getCanonicalIndex( $lctext );
528 if ( $ns !== null ) {
531 $ids = $this->getNamespaceIds();
532 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
536 * short names for language variants used for language conversion links.
538 * @param $code String
539 * @param $usemsg bool Use the "variantname-xyz" message if it exists
542 function getVariantname( $code, $usemsg = true ) {
543 $msg = "variantname-$code";
544 list( $rootCode ) = explode( '-', $code );
545 if ( $usemsg && wfMessage( $msg )->exists() ) {
546 return $this->getMessageFromDB( $msg );
548 $name = self
::getLanguageName( $code );
550 return $name; # if it's defined as a language name, show that
552 # otherwise, output the language code
558 * @param $name string
561 function specialPage( $name ) {
562 $aliases = $this->getSpecialPageAliases();
563 if ( isset( $aliases[$name][0] ) ) {
564 $name = $aliases[$name][0];
566 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
572 function getQuickbarSettings() {
574 $this->getMessage( 'qbsettings-none' ),
575 $this->getMessage( 'qbsettings-fixedleft' ),
576 $this->getMessage( 'qbsettings-fixedright' ),
577 $this->getMessage( 'qbsettings-floatingleft' ),
578 $this->getMessage( 'qbsettings-floatingright' ),
579 $this->getMessage( 'qbsettings-directionality' )
586 function getDatePreferences() {
587 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
593 function getDateFormats() {
594 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
598 * @return array|string
600 function getDefaultDateFormat() {
601 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
602 if ( $df === 'dmy or mdy' ) {
603 global $wgAmericanDates;
604 return $wgAmericanDates ?
'mdy' : 'dmy';
613 function getDatePreferenceMigrationMap() {
614 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
621 function getImageFile( $image ) {
622 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
628 function getExtraUserToggles() {
629 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
636 function getUserToggle( $tog ) {
637 return $this->getMessageFromDB( "tog-$tog" );
641 * Get language names, indexed by code.
642 * If $customisedOnly is true, only returns codes with a messages file
644 * @param $customisedOnly bool
648 public static function getLanguageNames( $customisedOnly = false ) {
649 global $wgExtraLanguageNames;
650 static $coreLanguageNames;
652 if ( $coreLanguageNames === null ) {
653 include( MWInit
::compiledPath( 'languages/Names.php' ) );
656 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
657 if ( !$customisedOnly ) {
663 // We do this using a foreach over the codes instead of a directory
664 // loop so that messages files in extensions will work correctly.
665 foreach ( $allNames as $code => $value ) {
666 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
667 $names[$code] = $allNames[$code];
674 * Get translated language names. This is done on best effort and
675 * by default this is exactly the same as Language::getLanguageNames.
676 * The CLDR extension provides translated names.
677 * @param $code String Language code.
678 * @return Array language code => language name
681 public static function getTranslatedLanguageNames( $code ) {
683 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
685 foreach ( self
::getLanguageNames() as $code => $name ) {
686 if ( !isset( $names[$code] ) ) $names[$code] = $name;
693 * Get a message from the MediaWiki namespace.
695 * @param $msg String: message name
698 function getMessageFromDB( $msg ) {
699 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
703 * @param $code string
706 function getLanguageName( $code ) {
707 $names = self
::getLanguageNames();
708 if ( !array_key_exists( $code, $names ) ) {
711 return $names[$code];
718 function getMonthName( $key ) {
719 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
725 function getMonthNamesArray() {
726 $monthNames = array( '' );
727 for ( $i = 1; $i < 13; $i++
) {
728 $monthNames[] = $this->getMonthName( $i );
737 function getMonthNameGen( $key ) {
738 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
745 function getMonthAbbreviation( $key ) {
746 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
752 function getMonthAbbreviationsArray() {
753 $monthNames = array( '' );
754 for ( $i = 1; $i < 13; $i++
) {
755 $monthNames[] = $this->getMonthAbbreviation( $i );
764 function getWeekdayName( $key ) {
765 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
772 function getWeekdayAbbreviation( $key ) {
773 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
780 function getIranianCalendarMonthName( $key ) {
781 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
788 function getHebrewCalendarMonthName( $key ) {
789 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
796 function getHebrewCalendarMonthNameGen( $key ) {
797 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
804 function getHijriCalendarMonthName( $key ) {
805 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
809 * This is a workalike of PHP's date() function, but with better
810 * internationalisation, a reduced set of format characters, and a better
813 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
814 * PHP manual for definitions. There are a number of extensions, which
817 * xn Do not translate digits of the next numeric format character
818 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
819 * xr Use roman numerals for the next numeric format character
820 * xh Use hebrew numerals for the next numeric format character
822 * xg Genitive month name
824 * xij j (day number) in Iranian calendar
825 * xiF F (month name) in Iranian calendar
826 * xin n (month number) in Iranian calendar
827 * xiy y (two digit year) in Iranian calendar
828 * xiY Y (full year) in Iranian calendar
830 * xjj j (day number) in Hebrew calendar
831 * xjF F (month name) in Hebrew calendar
832 * xjt t (days in month) in Hebrew calendar
833 * xjx xg (genitive month name) in Hebrew calendar
834 * xjn n (month number) in Hebrew calendar
835 * xjY Y (full year) in Hebrew calendar
837 * xmj j (day number) in Hijri calendar
838 * xmF F (month name) in Hijri calendar
839 * xmn n (month number) in Hijri calendar
840 * xmY Y (full year) in Hijri calendar
842 * xkY Y (full year) in Thai solar calendar. Months and days are
843 * identical to the Gregorian calendar
844 * xoY Y (full year) in Minguo calendar or Juche year.
845 * Months and days are identical to the
847 * xtY Y (full year) in Japanese nengo. Months and days are
848 * identical to the Gregorian calendar
850 * Characters enclosed in double quotes will be considered literal (with
851 * the quotes themselves removed). Unmatched quotes will be considered
852 * literal quotes. Example:
854 * "The month is" F => The month is January
857 * Backslash escaping is also supported.
859 * Input timestamp is assumed to be pre-normalized to the desired local
862 * @param $format String
863 * @param $ts String: 14-character timestamp
866 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
870 function sprintfDate( $format, $ts ) {
883 for ( $p = 0; $p < strlen( $format ); $p++
) {
886 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
887 $code .= $format[++
$p];
890 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
891 $code .= $format[++
$p];
902 $rawToggle = !$rawToggle;
911 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
914 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
915 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
918 $num = substr( $ts, 6, 2 );
921 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
922 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
925 $num = intval( substr( $ts, 6, 2 ) );
929 $iranian = self
::tsToIranian( $ts );
935 $hijri = self
::tsToHijri( $ts );
941 $hebrew = self
::tsToHebrew( $ts );
947 $unix = wfTimestamp( TS_UNIX
, $ts );
949 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
953 $unix = wfTimestamp( TS_UNIX
, $ts );
955 $w = gmdate( 'w', $unix );
960 $unix = wfTimestamp( TS_UNIX
, $ts );
962 $num = gmdate( 'w', $unix );
966 $unix = wfTimestamp( TS_UNIX
, $ts );
968 $num = gmdate( 'z', $unix );
972 $unix = wfTimestamp( TS_UNIX
, $ts );
974 $num = gmdate( 'W', $unix );
977 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
981 $iranian = self
::tsToIranian( $ts );
983 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
987 $hijri = self
::tsToHijri( $ts );
989 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
993 $hebrew = self
::tsToHebrew( $ts );
995 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
998 $num = substr( $ts, 4, 2 );
1001 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1004 $num = intval( substr( $ts, 4, 2 ) );
1008 $iranian = self
::tsToIranian( $ts );
1014 $hijri = self
::tsToHijri ( $ts );
1020 $hebrew = self
::tsToHebrew( $ts );
1026 $unix = wfTimestamp( TS_UNIX
, $ts );
1028 $num = gmdate( 't', $unix );
1032 $hebrew = self
::tsToHebrew( $ts );
1038 $unix = wfTimestamp( TS_UNIX
, $ts );
1040 $num = gmdate( 'L', $unix );
1044 $unix = wfTimestamp( TS_UNIX
, $ts );
1046 $num = date( 'o', $unix );
1049 $num = substr( $ts, 0, 4 );
1053 $iranian = self
::tsToIranian( $ts );
1059 $hijri = self
::tsToHijri( $ts );
1065 $hebrew = self
::tsToHebrew( $ts );
1071 $thai = self
::tsToYear( $ts, 'thai' );
1077 $minguo = self
::tsToYear( $ts, 'minguo' );
1083 $tenno = self
::tsToYear( $ts, 'tenno' );
1088 $num = substr( $ts, 2, 2 );
1092 $iranian = self
::tsToIranian( $ts );
1094 $num = substr( $iranian[0], -2 );
1097 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1100 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1103 $h = substr( $ts, 8, 2 );
1104 $num = $h %
12 ?
$h %
12 : 12;
1107 $num = intval( substr( $ts, 8, 2 ) );
1110 $h = substr( $ts, 8, 2 );
1111 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1114 $num = substr( $ts, 8, 2 );
1117 $num = substr( $ts, 10, 2 );
1120 $num = substr( $ts, 12, 2 );
1124 $unix = wfTimestamp( TS_UNIX
, $ts );
1126 $s .= gmdate( 'c', $unix );
1130 $unix = wfTimestamp( TS_UNIX
, $ts );
1132 $s .= gmdate( 'r', $unix );
1136 $unix = wfTimestamp( TS_UNIX
, $ts );
1141 # Backslash escaping
1142 if ( $p < strlen( $format ) - 1 ) {
1143 $s .= $format[++
$p];
1150 if ( $p < strlen( $format ) - 1 ) {
1151 $endQuote = strpos( $format, '"', $p +
1 );
1152 if ( $endQuote === false ) {
1153 # No terminating quote, assume literal "
1156 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1160 # Quote at end of string, assume literal "
1167 if ( $num !== false ) {
1168 if ( $rawToggle ||
$raw ) {
1171 } elseif ( $roman ) {
1172 $s .= self
::romanNumeral( $num );
1174 } elseif ( $hebrewNum ) {
1175 $s .= self
::hebrewNumeral( $num );
1178 $s .= $this->formatNum( $num, true );
1185 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1186 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1189 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1190 * Gregorian dates to Iranian dates. Originally written in C, it
1191 * is released under the terms of GNU Lesser General Public
1192 * License. Conversion to PHP was performed by Niklas Laxström.
1194 * Link: http://www.farsiweb.info/jalali/jalali.c
1200 private static function tsToIranian( $ts ) {
1201 $gy = substr( $ts, 0, 4 ) -1600;
1202 $gm = substr( $ts, 4, 2 ) -1;
1203 $gd = substr( $ts, 6, 2 ) -1;
1205 # Days passed from the beginning (including leap years)
1207 +
floor( ( $gy +
3 ) / 4 )
1208 - floor( ( $gy +
99 ) / 100 )
1209 +
floor( ( $gy +
399 ) / 400 );
1211 // Add days of the past months of this year
1212 for ( $i = 0; $i < $gm; $i++
) {
1213 $gDayNo +
= self
::$GREG_DAYS[$i];
1217 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1221 // Days passed in current month
1222 $gDayNo +
= (int)$gd;
1224 $jDayNo = $gDayNo - 79;
1226 $jNp = floor( $jDayNo / 12053 );
1229 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1232 if ( $jDayNo >= 366 ) {
1233 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1234 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1237 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1238 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1244 return array( $jy, $jm, $jd );
1248 * Converting Gregorian dates to Hijri dates.
1250 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1252 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1258 private static function tsToHijri( $ts ) {
1259 $year = substr( $ts, 0, 4 );
1260 $month = substr( $ts, 4, 2 );
1261 $day = substr( $ts, 6, 2 );
1269 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1270 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1273 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1274 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1275 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1278 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1279 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1282 $zl = $zjd -1948440 +
10632;
1283 $zn = (int)( ( $zl - 1 ) / 10631 );
1284 $zl = $zl - 10631 * $zn +
354;
1285 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1286 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1287 $zm = (int)( ( 24 * $zl ) / 709 );
1288 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1289 $zy = 30 * $zn +
$zj - 30;
1291 return array( $zy, $zm, $zd );
1295 * Converting Gregorian dates to Hebrew dates.
1297 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1298 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1299 * to translate the relevant functions into PHP and release them under
1302 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1303 * and Adar II is 14. In a non-leap year, Adar is 6.
1309 private static function tsToHebrew( $ts ) {
1311 $year = substr( $ts, 0, 4 );
1312 $month = substr( $ts, 4, 2 );
1313 $day = substr( $ts, 6, 2 );
1315 # Calculate Hebrew year
1316 $hebrewYear = $year +
3760;
1318 # Month number when September = 1, August = 12
1320 if ( $month > 12 ) {
1327 # Calculate day of year from 1 September
1329 for ( $i = 1; $i < $month; $i++
) {
1333 # Check if the year is leap
1334 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1337 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1344 # Calculate the start of the Hebrew year
1345 $start = self
::hebrewYearStart( $hebrewYear );
1347 # Calculate next year's start
1348 if ( $dayOfYear <= $start ) {
1349 # Day is before the start of the year - it is the previous year
1351 $nextStart = $start;
1355 # Add days since previous year's 1 September
1357 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1361 # Start of the new (previous) year
1362 $start = self
::hebrewYearStart( $hebrewYear );
1365 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1368 # Calculate Hebrew day of year
1369 $hebrewDayOfYear = $dayOfYear - $start;
1371 # Difference between year's days
1372 $diff = $nextStart - $start;
1373 # Add 12 (or 13 for leap years) days to ignore the difference between
1374 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1375 # difference is only about the year type
1376 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1382 # Check the year pattern, and is leap year
1383 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1384 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1385 # and non-leap years
1386 $yearPattern = $diff %
30;
1387 # Check if leap year
1388 $isLeap = $diff >= 30;
1390 # Calculate day in the month from number of day in the Hebrew year
1391 # Don't check Adar - if the day is not in Adar, we will stop before;
1392 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1393 $hebrewDay = $hebrewDayOfYear;
1396 while ( $hebrewMonth <= 12 ) {
1397 # Calculate days in this month
1398 if ( $isLeap && $hebrewMonth == 6 ) {
1399 # Adar in a leap year
1401 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1403 if ( $hebrewDay <= $days ) {
1407 # Subtract the days of Adar I
1408 $hebrewDay -= $days;
1411 if ( $hebrewDay <= $days ) {
1417 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1418 # Cheshvan in a complete year (otherwise as the rule below)
1420 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1421 # Kislev in an incomplete year (otherwise as the rule below)
1424 # Odd months have 30 days, even have 29
1425 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1427 if ( $hebrewDay <= $days ) {
1428 # In the current month
1431 # Subtract the days of the current month
1432 $hebrewDay -= $days;
1433 # Try in the next month
1438 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1442 * This calculates the Hebrew year start, as days since 1 September.
1443 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1444 * Used for Hebrew date.
1450 private static function hebrewYearStart( $year ) {
1451 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1452 $b = intval( ( $year - 1 ) %
4 );
1453 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1457 $Mar = intval( $m );
1463 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1464 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1466 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1468 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1472 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1477 * Algorithm to convert Gregorian dates to Thai solar dates,
1478 * Minguo dates or Minguo dates.
1480 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1481 * http://en.wikipedia.org/wiki/Minguo_calendar
1482 * http://en.wikipedia.org/wiki/Japanese_era_name
1484 * @param $ts String: 14-character timestamp
1485 * @param $cName String: calender name
1486 * @return Array: converted year, month, day
1488 private static function tsToYear( $ts, $cName ) {
1489 $gy = substr( $ts, 0, 4 );
1490 $gm = substr( $ts, 4, 2 );
1491 $gd = substr( $ts, 6, 2 );
1493 if ( !strcmp( $cName, 'thai' ) ) {
1495 # Add 543 years to the Gregorian calendar
1496 # Months and days are identical
1497 $gy_offset = $gy +
543;
1498 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1500 # Deduct 1911 years from the Gregorian calendar
1501 # Months and days are identical
1502 $gy_offset = $gy - 1911;
1503 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1504 # Nengō dates up to Meiji period
1505 # Deduct years from the Gregorian calendar
1506 # depending on the nengo periods
1507 # Months and days are identical
1508 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1510 $gy_gannen = $gy - 1868 +
1;
1511 $gy_offset = $gy_gannen;
1512 if ( $gy_gannen == 1 ) {
1515 $gy_offset = '明治' . $gy_offset;
1517 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1518 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1519 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1520 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1521 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1525 $gy_gannen = $gy - 1912 +
1;
1526 $gy_offset = $gy_gannen;
1527 if ( $gy_gannen == 1 ) {
1530 $gy_offset = '大正' . $gy_offset;
1532 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1533 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1534 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1538 $gy_gannen = $gy - 1926 +
1;
1539 $gy_offset = $gy_gannen;
1540 if ( $gy_gannen == 1 ) {
1543 $gy_offset = '昭和' . $gy_offset;
1546 $gy_gannen = $gy - 1989 +
1;
1547 $gy_offset = $gy_gannen;
1548 if ( $gy_gannen == 1 ) {
1551 $gy_offset = '平成' . $gy_offset;
1557 return array( $gy_offset, $gm, $gd );
1561 * Roman number formatting up to 3000
1567 static function romanNumeral( $num ) {
1568 static $table = array(
1569 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1570 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1571 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1572 array( '', 'M', 'MM', 'MMM' )
1575 $num = intval( $num );
1576 if ( $num > 3000 ||
$num <= 0 ) {
1581 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1582 if ( $num >= $pow10 ) {
1583 $s .= $table[$i][(int)floor( $num / $pow10 )];
1585 $num = $num %
$pow10;
1591 * Hebrew Gematria number formatting up to 9999
1597 static function hebrewNumeral( $num ) {
1598 static $table = array(
1599 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1600 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1601 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1602 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1605 $num = intval( $num );
1606 if ( $num > 9999 ||
$num <= 0 ) {
1611 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1612 if ( $num >= $pow10 ) {
1613 if ( $num == 15 ||
$num == 16 ) {
1614 $s .= $table[0][9] . $table[0][$num - 9];
1617 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1618 if ( $pow10 == 1000 ) {
1623 $num = $num %
$pow10;
1625 if ( strlen( $s ) == 2 ) {
1628 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1629 $str .= substr( $s, strlen( $s ) - 2, 2 );
1631 $start = substr( $str, 0, strlen( $str ) - 2 );
1632 $end = substr( $str, strlen( $str ) - 2 );
1635 $str = $start . 'ך';
1638 $str = $start . 'ם';
1641 $str = $start . 'ן';
1644 $str = $start . 'ף';
1647 $str = $start . 'ץ';
1654 * Used by date() and time() to adjust the time output.
1656 * @param $ts Int the time in date('YmdHis') format
1657 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1658 * get user timecorrection setting)
1661 function userAdjust( $ts, $tz = false ) {
1662 global $wgUser, $wgLocalTZoffset;
1664 if ( $tz === false ) {
1665 $tz = $wgUser->getOption( 'timecorrection' );
1668 $data = explode( '|', $tz, 3 );
1670 if ( $data[0] == 'ZoneInfo' ) {
1671 wfSuppressWarnings();
1672 $userTZ = timezone_open( $data[2] );
1673 wfRestoreWarnings();
1674 if ( $userTZ !== false ) {
1675 $date = date_create( $ts, timezone_open( 'UTC' ) );
1676 date_timezone_set( $date, $userTZ );
1677 $date = date_format( $date, 'YmdHis' );
1680 # Unrecognized timezone, default to 'Offset' with the stored offset.
1681 $data[0] = 'Offset';
1685 if ( $data[0] == 'System' ||
$tz == '' ) {
1686 # Global offset in minutes.
1687 if ( isset( $wgLocalTZoffset ) ) {
1688 $minDiff = $wgLocalTZoffset;
1690 } elseif ( $data[0] == 'Offset' ) {
1691 $minDiff = intval( $data[1] );
1693 $data = explode( ':', $tz );
1694 if ( count( $data ) == 2 ) {
1695 $data[0] = intval( $data[0] );
1696 $data[1] = intval( $data[1] );
1697 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1698 if ( $data[0] < 0 ) {
1699 $minDiff = -$minDiff;
1702 $minDiff = intval( $data[0] ) * 60;
1706 # No difference ? Return time unchanged
1707 if ( 0 == $minDiff ) {
1711 wfSuppressWarnings(); // E_STRICT system time bitching
1712 # Generate an adjusted date; take advantage of the fact that mktime
1713 # will normalize out-of-range values so we don't have to split $minDiff
1714 # into hours and minutes.
1716 (int)substr( $ts, 8, 2 ) ), # Hours
1717 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1718 (int)substr( $ts, 12, 2 ), # Seconds
1719 (int)substr( $ts, 4, 2 ), # Month
1720 (int)substr( $ts, 6, 2 ), # Day
1721 (int)substr( $ts, 0, 4 ) ); # Year
1723 $date = date( 'YmdHis', $t );
1724 wfRestoreWarnings();
1730 * This is meant to be used by time(), date(), and timeanddate() to get
1731 * the date preference they're supposed to use, it should be used in
1735 * function timeanddate([...], $format = true) {
1736 * $datePreference = $this->dateFormat($format);
1741 * @param $usePrefs Mixed: if true, the user's preference is used
1742 * if false, the site/language default is used
1743 * if int/string, assumed to be a format.
1746 function dateFormat( $usePrefs = true ) {
1749 if ( is_bool( $usePrefs ) ) {
1751 $datePreference = $wgUser->getDatePreference();
1753 $datePreference = (string)User
::getDefaultOption( 'date' );
1756 $datePreference = (string)$usePrefs;
1760 if ( $datePreference == '' ) {
1764 return $datePreference;
1768 * Get a format string for a given type and preference
1769 * @param $type string May be date, time or both
1770 * @param $pref string The format name as it appears in Messages*.php
1774 function getDateFormatString( $type, $pref ) {
1775 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1776 if ( $pref == 'default' ) {
1777 $pref = $this->getDefaultDateFormat();
1778 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1780 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1781 if ( is_null( $df ) ) {
1782 $pref = $this->getDefaultDateFormat();
1783 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1786 $this->dateFormatStrings
[$type][$pref] = $df;
1788 return $this->dateFormatStrings
[$type][$pref];
1792 * @param $ts Mixed: the time format which needs to be turned into a
1793 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1794 * @param $adj Bool: whether to adjust the time output according to the
1795 * user configured offset ($timecorrection)
1796 * @param $format Mixed: true to use user's date format preference
1797 * @param $timecorrection String|bool the time offset as returned by
1798 * validateTimeZone() in Special:Preferences
1801 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1802 $ts = wfTimestamp( TS_MW
, $ts );
1804 $ts = $this->userAdjust( $ts, $timecorrection );
1806 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1807 return $this->sprintfDate( $df, $ts );
1811 * @param $ts Mixed: the time format which needs to be turned into a
1812 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1813 * @param $adj Bool: whether to adjust the time output according to the
1814 * user configured offset ($timecorrection)
1815 * @param $format Mixed: true to use user's date format preference
1816 * @param $timecorrection String|bool the time offset as returned by
1817 * validateTimeZone() in Special:Preferences
1820 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1821 $ts = wfTimestamp( TS_MW
, $ts );
1823 $ts = $this->userAdjust( $ts, $timecorrection );
1825 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1826 return $this->sprintfDate( $df, $ts );
1830 * @param $ts Mixed: the time format which needs to be turned into a
1831 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1832 * @param $adj Bool: whether to adjust the time output according to the
1833 * user configured offset ($timecorrection)
1834 * @param $format Mixed: what format to return, if it's false output the
1835 * default one (default true)
1836 * @param $timecorrection String|bool the time offset as returned by
1837 * validateTimeZone() in Special:Preferences
1840 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1841 $ts = wfTimestamp( TS_MW
, $ts );
1843 $ts = $this->userAdjust( $ts, $timecorrection );
1845 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1846 return $this->sprintfDate( $df, $ts );
1850 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1852 * @param $type String: can be 'date', 'time' or 'both'
1853 * @param $ts Mixed: the time format which needs to be turned into a
1854 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1855 * @param $user User object used to get preferences for timezone and format
1856 * @param $options Array, can contain the following keys:
1857 * - 'timecorrection': time correction, can have the following values:
1858 * - true: use user's preference
1859 * - false: don't use time correction
1860 * - integer: value of time correction in minutes
1861 * - 'format': format to use, can have the following values:
1862 * - true: use user's preference
1863 * - false: use default preference
1864 * - string: format to use
1867 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1868 $ts = wfTimestamp( TS_MW
, $ts );
1869 $options +
= array( 'timecorrection' => true, 'format' => true );
1870 if ( $options['timecorrection'] !== false ) {
1871 if ( $options['timecorrection'] === true ) {
1872 $offset = $user->getOption( 'timecorrection' );
1874 $offset = $options['timecorrection'];
1876 $ts = $this->userAdjust( $ts, $offset );
1878 if ( $options['format'] === true ) {
1879 $format = $user->getDatePreference();
1881 $format = $options['format'];
1883 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1884 return $this->sprintfDate( $df, $ts );
1888 * Get the formatted date for the given timestamp and formatted for
1891 * @param $ts Mixed: the time format which needs to be turned into a
1892 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1893 * @param $user User object used to get preferences for timezone and format
1894 * @param $options Array, can contain the following keys:
1895 * - 'timecorrection': time correction, can have the following values:
1896 * - true: use user's preference
1897 * - false: don't use time correction
1898 * - integer: value of time correction in minutes
1899 * - 'format': format to use, can have the following values:
1900 * - true: use user's preference
1901 * - false: use default preference
1902 * - string: format to use
1905 public function userDate( $ts, User
$user, array $options = array() ) {
1906 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1910 * Get the formatted time for the given timestamp and formatted for
1913 * @param $ts Mixed: the time format which needs to be turned into a
1914 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1915 * @param $user User object used to get preferences for timezone and format
1916 * @param $options Array, can contain the following keys:
1917 * - 'timecorrection': time correction, can have the following values:
1918 * - true: use user's preference
1919 * - false: don't use time correction
1920 * - integer: value of time correction in minutes
1921 * - 'format': format to use, can have the following values:
1922 * - true: use user's preference
1923 * - false: use default preference
1924 * - string: format to use
1927 public function userTime( $ts, User
$user, array $options = array() ) {
1928 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1932 * Get the formatted date and time for the given timestamp and formatted for
1935 * @param $ts Mixed: the time format which needs to be turned into a
1936 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1937 * @param $user User object used to get preferences for timezone and format
1938 * @param $options Array, can contain the following keys:
1939 * - 'timecorrection': time correction, can have the following values:
1940 * - true: use user's preference
1941 * - false: don't use time correction
1942 * - integer: value of time correction in minutes
1943 * - 'format': format to use, can have the following values:
1944 * - true: use user's preference
1945 * - false: use default preference
1946 * - string: format to use
1949 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
1950 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
1954 * @param $key string
1955 * @return array|null
1957 function getMessage( $key ) {
1958 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1964 function getAllMessages() {
1965 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1974 function iconv( $in, $out, $string ) {
1975 # This is a wrapper for iconv in all languages except esperanto,
1976 # which does some nasty x-conversions beforehand
1978 # Even with //IGNORE iconv can whine about illegal characters in
1979 # *input* string. We just ignore those too.
1980 # REF: http://bugs.php.net/bug.php?id=37166
1981 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1982 wfSuppressWarnings();
1983 $text = iconv( $in, $out . '//IGNORE', $string );
1984 wfRestoreWarnings();
1988 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1991 * @param $matches array
1992 * @return mixed|string
1994 function ucwordbreaksCallbackAscii( $matches ) {
1995 return $this->ucfirst( $matches[1] );
1999 * @param $matches array
2002 function ucwordbreaksCallbackMB( $matches ) {
2003 return mb_strtoupper( $matches[0] );
2007 * @param $matches array
2010 function ucCallback( $matches ) {
2011 list( $wikiUpperChars ) = self
::getCaseMaps();
2012 return strtr( $matches[1], $wikiUpperChars );
2016 * @param $matches array
2019 function lcCallback( $matches ) {
2020 list( , $wikiLowerChars ) = self
::getCaseMaps();
2021 return strtr( $matches[1], $wikiLowerChars );
2025 * @param $matches array
2028 function ucwordsCallbackMB( $matches ) {
2029 return mb_strtoupper( $matches[0] );
2033 * @param $matches array
2036 function ucwordsCallbackWiki( $matches ) {
2037 list( $wikiUpperChars ) = self
::getCaseMaps();
2038 return strtr( $matches[0], $wikiUpperChars );
2042 * Make a string's first character uppercase
2044 * @param $str string
2048 function ucfirst( $str ) {
2050 if ( $o < 96 ) { // if already uppercase...
2052 } elseif ( $o < 128 ) {
2053 return ucfirst( $str ); // use PHP's ucfirst()
2055 // fall back to more complex logic in case of multibyte strings
2056 return $this->uc( $str, true );
2061 * Convert a string to uppercase
2063 * @param $str string
2064 * @param $first bool
2068 function uc( $str, $first = false ) {
2069 if ( function_exists( 'mb_strtoupper' ) ) {
2071 if ( $this->isMultibyte( $str ) ) {
2072 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2074 return ucfirst( $str );
2077 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2080 if ( $this->isMultibyte( $str ) ) {
2081 $x = $first ?
'^' : '';
2082 return preg_replace_callback(
2083 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2084 array( $this, 'ucCallback' ),
2088 return $first ?
ucfirst( $str ) : strtoupper( $str );
2094 * @param $str string
2095 * @return mixed|string
2097 function lcfirst( $str ) {
2100 return strval( $str );
2101 } elseif ( $o >= 128 ) {
2102 return $this->lc( $str, true );
2103 } elseif ( $o > 96 ) {
2106 $str[0] = strtolower( $str[0] );
2112 * @param $str string
2113 * @param $first bool
2114 * @return mixed|string
2116 function lc( $str, $first = false ) {
2117 if ( function_exists( 'mb_strtolower' ) ) {
2119 if ( $this->isMultibyte( $str ) ) {
2120 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2122 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2125 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2128 if ( $this->isMultibyte( $str ) ) {
2129 $x = $first ?
'^' : '';
2130 return preg_replace_callback(
2131 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2132 array( $this, 'lcCallback' ),
2136 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2142 * @param $str string
2145 function isMultibyte( $str ) {
2146 return (bool)preg_match( '/[\x80-\xff]/', $str );
2150 * @param $str string
2151 * @return mixed|string
2153 function ucwords( $str ) {
2154 if ( $this->isMultibyte( $str ) ) {
2155 $str = $this->lc( $str );
2157 // regexp to find first letter in each word (i.e. after each space)
2158 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2160 // function to use to capitalize a single char
2161 if ( function_exists( 'mb_strtoupper' ) ) {
2162 return preg_replace_callback(
2164 array( $this, 'ucwordsCallbackMB' ),
2168 return preg_replace_callback(
2170 array( $this, 'ucwordsCallbackWiki' ),
2175 return ucwords( strtolower( $str ) );
2180 * capitalize words at word breaks
2182 * @param $str string
2185 function ucwordbreaks( $str ) {
2186 if ( $this->isMultibyte( $str ) ) {
2187 $str = $this->lc( $str );
2189 // since \b doesn't work for UTF-8, we explicitely define word break chars
2190 $breaks = "[ \-\(\)\}\{\.,\?!]";
2192 // find first letter after word break
2193 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2195 if ( function_exists( 'mb_strtoupper' ) ) {
2196 return preg_replace_callback(
2198 array( $this, 'ucwordbreaksCallbackMB' ),
2202 return preg_replace_callback(
2204 array( $this, 'ucwordsCallbackWiki' ),
2209 return preg_replace_callback(
2210 '/\b([\w\x80-\xff]+)\b/',
2211 array( $this, 'ucwordbreaksCallbackAscii' ),
2218 * Return a case-folded representation of $s
2220 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2221 * and $s2 are the same except for the case of their characters. It is not
2222 * necessary for the value returned to make sense when displayed.
2224 * Do *not* perform any other normalisation in this function. If a caller
2225 * uses this function when it should be using a more general normalisation
2226 * function, then fix the caller.
2232 function caseFold( $s ) {
2233 return $this->uc( $s );
2240 function checkTitleEncoding( $s ) {
2241 if ( is_array( $s ) ) {
2242 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2244 # Check for non-UTF-8 URLs
2245 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2250 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2251 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2256 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2262 function fallback8bitEncoding() {
2263 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2267 * Most writing systems use whitespace to break up words.
2268 * Some languages such as Chinese don't conventionally do this,
2269 * which requires special handling when breaking up words for
2274 function hasWordBreaks() {
2279 * Some languages such as Chinese require word segmentation,
2280 * Specify such segmentation when overridden in derived class.
2282 * @param $string String
2285 function segmentByWord( $string ) {
2290 * Some languages have special punctuation need to be normalized.
2291 * Make such changes here.
2293 * @param $string String
2296 function normalizeForSearch( $string ) {
2297 return self
::convertDoubleWidth( $string );
2301 * convert double-width roman characters to single-width.
2302 * range: ff00-ff5f ~= 0020-007f
2304 * @param $string string
2308 protected static function convertDoubleWidth( $string ) {
2309 static $full = null;
2310 static $half = null;
2312 if ( $full === null ) {
2313 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2314 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2315 $full = str_split( $fullWidth, 3 );
2316 $half = str_split( $halfWidth );
2319 $string = str_replace( $full, $half, $string );
2324 * @param $string string
2325 * @param $pattern string
2328 protected static function insertSpace( $string, $pattern ) {
2329 $string = preg_replace( $pattern, " $1 ", $string );
2330 $string = preg_replace( '/ +/', ' ', $string );
2335 * @param $termsArray array
2338 function convertForSearchResult( $termsArray ) {
2339 # some languages, e.g. Chinese, need to do a conversion
2340 # in order for search results to be displayed correctly
2345 * Get the first character of a string.
2350 function firstChar( $s ) {
2353 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2354 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2359 if ( isset( $matches[1] ) ) {
2360 if ( strlen( $matches[1] ) != 3 ) {
2364 // Break down Hangul syllables to grab the first jamo
2365 $code = utf8ToCodepoint( $matches[1] );
2366 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2368 } elseif ( $code < 0xb098 ) {
2369 return "\xe3\x84\xb1";
2370 } elseif ( $code < 0xb2e4 ) {
2371 return "\xe3\x84\xb4";
2372 } elseif ( $code < 0xb77c ) {
2373 return "\xe3\x84\xb7";
2374 } elseif ( $code < 0xb9c8 ) {
2375 return "\xe3\x84\xb9";
2376 } elseif ( $code < 0xbc14 ) {
2377 return "\xe3\x85\x81";
2378 } elseif ( $code < 0xc0ac ) {
2379 return "\xe3\x85\x82";
2380 } elseif ( $code < 0xc544 ) {
2381 return "\xe3\x85\x85";
2382 } elseif ( $code < 0xc790 ) {
2383 return "\xe3\x85\x87";
2384 } elseif ( $code < 0xcc28 ) {
2385 return "\xe3\x85\x88";
2386 } elseif ( $code < 0xce74 ) {
2387 return "\xe3\x85\x8a";
2388 } elseif ( $code < 0xd0c0 ) {
2389 return "\xe3\x85\x8b";
2390 } elseif ( $code < 0xd30c ) {
2391 return "\xe3\x85\x8c";
2392 } elseif ( $code < 0xd558 ) {
2393 return "\xe3\x85\x8d";
2395 return "\xe3\x85\x8e";
2402 function initEncoding() {
2403 # Some languages may have an alternate char encoding option
2404 # (Esperanto X-coding, Japanese furigana conversion, etc)
2405 # If this language is used as the primary content language,
2406 # an override to the defaults can be set here on startup.
2413 function recodeForEdit( $s ) {
2414 # For some languages we'll want to explicitly specify
2415 # which characters make it into the edit box raw
2416 # or are converted in some way or another.
2417 global $wgEditEncoding;
2418 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2421 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2429 function recodeInput( $s ) {
2430 # Take the previous into account.
2431 global $wgEditEncoding;
2432 if ( $wgEditEncoding != '' ) {
2433 $enc = $wgEditEncoding;
2437 if ( $enc == 'UTF-8' ) {
2440 return $this->iconv( $enc, 'UTF-8', $s );
2445 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2446 * also cleans up certain backwards-compatible sequences, converting them
2447 * to the modern Unicode equivalent.
2449 * This is language-specific for performance reasons only.
2455 function normalize( $s ) {
2456 global $wgAllUnicodeFixes;
2457 $s = UtfNormal
::cleanUp( $s );
2458 if ( $wgAllUnicodeFixes ) {
2459 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2460 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2467 * Transform a string using serialized data stored in the given file (which
2468 * must be in the serialized subdirectory of $IP). The file contains pairs
2469 * mapping source characters to destination characters.
2471 * The data is cached in process memory. This will go faster if you have the
2472 * FastStringSearch extension.
2474 * @param $file string
2475 * @param $string string
2479 function transformUsingPairFile( $file, $string ) {
2480 if ( !isset( $this->transformData
[$file] ) ) {
2481 $data = wfGetPrecompiledData( $file );
2482 if ( $data === false ) {
2483 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2485 $this->transformData
[$file] = new ReplacementArray( $data );
2487 return $this->transformData
[$file]->replace( $string );
2491 * For right-to-left language support
2496 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2500 * Return the correct HTML 'dir' attribute value for this language.
2504 return $this->isRTL() ?
'rtl' : 'ltr';
2508 * Return 'left' or 'right' as appropriate alignment for line-start
2509 * for this language's text direction.
2511 * Should be equivalent to CSS3 'start' text-align value....
2515 function alignStart() {
2516 return $this->isRTL() ?
'right' : 'left';
2520 * Return 'right' or 'left' as appropriate alignment for line-end
2521 * for this language's text direction.
2523 * Should be equivalent to CSS3 'end' text-align value....
2527 function alignEnd() {
2528 return $this->isRTL() ?
'left' : 'right';
2532 * A hidden direction mark (LRM or RLM), depending on the language direction
2534 * @param $opposite Boolean Get the direction mark opposite to your language
2537 function getDirMark( $opposite = false ) {
2538 $rtl = "\xE2\x80\x8F";
2539 $ltr = "\xE2\x80\x8E";
2540 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2541 return $this->isRTL() ?
$rtl : $ltr;
2547 function capitalizeAllNouns() {
2548 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2552 * An arrow, depending on the language direction
2556 function getArrow() {
2557 return $this->isRTL() ?
'←' : '→';
2561 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2565 function linkPrefixExtension() {
2566 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2572 function getMagicWords() {
2573 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2576 protected function doMagicHook() {
2577 if ( $this->mMagicHookDone
) {
2580 $this->mMagicHookDone
= true;
2581 wfProfileIn( 'LanguageGetMagic' );
2582 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2583 wfProfileOut( 'LanguageGetMagic' );
2587 * Fill a MagicWord object with data from here
2591 function getMagic( $mw ) {
2592 $this->doMagicHook();
2594 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2595 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2597 $magicWords = $this->getMagicWords();
2598 if ( isset( $magicWords[$mw->mId
] ) ) {
2599 $rawEntry = $magicWords[$mw->mId
];
2605 if ( !is_array( $rawEntry ) ) {
2606 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2608 $mw->mCaseSensitive
= $rawEntry[0];
2609 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2614 * Add magic words to the extension array
2616 * @param $newWords array
2618 function addMagicWordsByLang( $newWords ) {
2619 $fallbackChain = $this->getFallbackLanguages();
2620 $fallbackChain = array_reverse( $fallbackChain );
2621 foreach ( $fallbackChain as $code ) {
2622 if ( isset( $newWords[$code] ) ) {
2623 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2629 * Get special page names, as an associative array
2630 * case folded alias => real name
2632 function getSpecialPageAliases() {
2633 // Cache aliases because it may be slow to load them
2634 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2636 $this->mExtendedSpecialPageAliases
=
2637 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2638 wfRunHooks( 'LanguageGetSpecialPageAliases',
2639 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2642 return $this->mExtendedSpecialPageAliases
;
2646 * Italic is unsuitable for some languages
2648 * @param $text String: the text to be emphasized.
2651 function emphasize( $text ) {
2652 return "<em>$text</em>";
2656 * Normally we output all numbers in plain en_US style, that is
2657 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2658 * point twohundredthirtyfive. However this is not suitable for all
2659 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2660 * Icelandic just want to use commas instead of dots, and dots instead
2661 * of commas like "293.291,235".
2663 * An example of this function being called:
2665 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2668 * See LanguageGu.php for the Gujarati implementation and
2669 * $separatorTransformTable on MessageIs.php for
2670 * the , => . and . => , implementation.
2672 * @todo check if it's viable to use localeconv() for the decimal
2674 * @param $number Mixed: the string to be formatted, should be an integer
2675 * or a floating point number.
2676 * @param $nocommafy Bool: set to true for special numbers like dates
2679 public function formatNum( $number, $nocommafy = false ) {
2680 global $wgTranslateNumerals;
2681 if ( !$nocommafy ) {
2682 $number = $this->commafy( $number );
2683 $s = $this->separatorTransformTable();
2685 $number = strtr( $number, $s );
2689 if ( $wgTranslateNumerals ) {
2690 $s = $this->digitTransformTable();
2692 $number = strtr( $number, $s );
2700 * @param $number string
2703 function parseFormattedNumber( $number ) {
2704 $s = $this->digitTransformTable();
2706 $number = strtr( $number, array_flip( $s ) );
2709 $s = $this->separatorTransformTable();
2711 $number = strtr( $number, array_flip( $s ) );
2714 $number = strtr( $number, array( ',' => '' ) );
2719 * Adds commas to a given number
2724 function commafy( $_ ) {
2725 $digitGroupingPattern = $this->digitGroupingPattern();
2727 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2728 // default grouping is at thousands, use the same for ###,###,### pattern too.
2729 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2731 // Ref: http://cldr.unicode.org/translation/number-patterns
2733 if ( intval( $_ ) < 0 ) {
2734 // For negative numbers apply the algorithm like positive number and add sign.
2736 $_ = substr( $_,1 );
2738 $numberpart = array();
2739 $decimalpart = array();
2740 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2741 preg_match( "/\d+/", $_, $numberpart );
2742 preg_match( "/\.\d*/", $_, $decimalpart );
2743 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2744 if ( $groupedNumber === $_ ) {
2745 // the string does not have any number part. Eg: .12345
2746 return $sign . $groupedNumber;
2748 $start = $end = strlen( $numberpart[0] );
2749 while ( $start > 0 ) {
2750 $match = $matches[0][$numMatches -1] ;
2751 $matchLen = strlen( $match );
2752 $start = $end - $matchLen;
2756 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2758 if ( $numMatches > 1 ) {
2759 // use the last pattern for the rest of the number
2763 $groupedNumber = "," . $groupedNumber;
2766 return $sign . $groupedNumber;
2772 function digitGroupingPattern() {
2773 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2779 function digitTransformTable() {
2780 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2786 function separatorTransformTable() {
2787 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2791 * Take a list of strings and build a locale-friendly comma-separated
2792 * list, using the local comma-separator message.
2793 * The last two strings are chained with an "and".
2798 function listToText( array $l ) {
2800 $m = count( $l ) - 1;
2802 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2804 for ( $i = $m; $i >= 0; $i-- ) {
2807 } elseif ( $i == $m - 1 ) {
2808 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2810 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2818 * Take a list of strings and build a locale-friendly comma-separated
2819 * list, using the local comma-separator message.
2820 * @param $list array of strings to put in a comma list
2823 function commaList( array $list ) {
2827 array( 'parsemag', 'escapenoentities', 'language' => $this )
2834 * Take a list of strings and build a locale-friendly semicolon-separated
2835 * list, using the local semicolon-separator message.
2836 * @param $list array of strings to put in a semicolon list
2839 function semicolonList( array $list ) {
2842 'semicolon-separator',
2843 array( 'parsemag', 'escapenoentities', 'language' => $this )
2850 * Same as commaList, but separate it with the pipe instead.
2851 * @param $list array of strings to put in a pipe list
2854 function pipeList( array $list ) {
2858 array( 'escapenoentities', 'language' => $this )
2865 * Truncate a string to a specified length in bytes, appending an optional
2866 * string (e.g. for ellipses)
2868 * The database offers limited byte lengths for some columns in the database;
2869 * multi-byte character sets mean we need to ensure that only whole characters
2870 * are included, otherwise broken characters can be passed to the user
2872 * If $length is negative, the string will be truncated from the beginning
2874 * @param $string String to truncate
2875 * @param $length Int: maximum length (including ellipses)
2876 * @param $ellipsis String to append to the truncated text
2877 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2878 * $adjustLength was introduced in 1.18, before that behaved as if false.
2881 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2882 # Use the localized ellipsis character
2883 if ( $ellipsis == '...' ) {
2884 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2886 # Check if there is no need to truncate
2887 if ( $length == 0 ) {
2888 return $ellipsis; // convention
2889 } elseif ( strlen( $string ) <= abs( $length ) ) {
2890 return $string; // no need to truncate
2892 $stringOriginal = $string;
2893 # If ellipsis length is >= $length then we can't apply $adjustLength
2894 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2895 $string = $ellipsis; // this can be slightly unexpected
2896 # Otherwise, truncate and add ellipsis...
2898 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2899 if ( $length > 0 ) {
2900 $length -= $eLength;
2901 $string = substr( $string, 0, $length ); // xyz...
2902 $string = $this->removeBadCharLast( $string );
2903 $string = $string . $ellipsis;
2905 $length +
= $eLength;
2906 $string = substr( $string, $length ); // ...xyz
2907 $string = $this->removeBadCharFirst( $string );
2908 $string = $ellipsis . $string;
2911 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2912 # This check is *not* redundant if $adjustLength, due to the single case where
2913 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2914 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2917 return $stringOriginal;
2922 * Remove bytes that represent an incomplete Unicode character
2923 * at the end of string (e.g. bytes of the char are missing)
2925 * @param $string String
2928 protected function removeBadCharLast( $string ) {
2929 if ( $string != '' ) {
2930 $char = ord( $string[strlen( $string ) - 1] );
2932 if ( $char >= 0xc0 ) {
2933 # We got the first byte only of a multibyte char; remove it.
2934 $string = substr( $string, 0, -1 );
2935 } elseif ( $char >= 0x80 &&
2936 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2937 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2939 # We chopped in the middle of a character; remove it
2947 * Remove bytes that represent an incomplete Unicode character
2948 * at the start of string (e.g. bytes of the char are missing)
2950 * @param $string String
2953 protected function removeBadCharFirst( $string ) {
2954 if ( $string != '' ) {
2955 $char = ord( $string[0] );
2956 if ( $char >= 0x80 && $char < 0xc0 ) {
2957 # We chopped in the middle of a character; remove the whole thing
2958 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2965 * Truncate a string of valid HTML to a specified length in bytes,
2966 * appending an optional string (e.g. for ellipses), and return valid HTML
2968 * This is only intended for styled/linked text, such as HTML with
2969 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2970 * Also, this will not detect things like "display:none" CSS.
2972 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2974 * @param string $text HTML string to truncate
2975 * @param int $length (zero/positive) Maximum length (including ellipses)
2976 * @param string $ellipsis String to append to the truncated text
2979 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2980 # Use the localized ellipsis character
2981 if ( $ellipsis == '...' ) {
2982 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2984 # Check if there is clearly no need to truncate
2985 if ( $length <= 0 ) {
2986 return $ellipsis; // no text shown, nothing to format (convention)
2987 } elseif ( strlen( $text ) <= $length ) {
2988 return $text; // string short enough even *with* HTML (short-circuit)
2991 $dispLen = 0; // innerHTML legth so far
2992 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2993 $tagType = 0; // 0-open, 1-close
2994 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2995 $entityState = 0; // 0-not entity, 1-entity
2996 $tag = $ret = ''; // accumulated tag name, accumulated result string
2997 $openTags = array(); // open tag stack
2998 $maybeState = null; // possible truncation state
3000 $textLen = strlen( $text );
3001 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3002 for ( $pos = 0; true; ++
$pos ) {
3003 # Consider truncation once the display length has reached the maximim.
3004 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3005 # Check that we're not in the middle of a bracket/entity...
3006 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3007 if ( !$testingEllipsis ) {
3008 $testingEllipsis = true;
3009 # Save where we are; we will truncate here unless there turn out to
3010 # be so few remaining characters that truncation is not necessary.
3011 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3012 $maybeState = array( $ret, $openTags ); // save state
3014 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3015 # String in fact does need truncation, the truncation point was OK.
3016 list( $ret, $openTags ) = $maybeState; // reload state
3017 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3018 $ret .= $ellipsis; // add ellipsis
3022 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3024 # Read the next char...
3026 $lastCh = $pos ?
$text[$pos - 1] : '';
3027 $ret .= $ch; // add to result string
3029 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3030 $entityState = 0; // for bad HTML
3031 $bracketState = 1; // tag started (checking for backslash)
3032 } elseif ( $ch == '>' ) {
3033 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3034 $entityState = 0; // for bad HTML
3035 $bracketState = 0; // out of brackets
3036 } elseif ( $bracketState == 1 ) {
3038 $tagType = 1; // close tag (e.g. "</span>")
3040 $tagType = 0; // open tag (e.g. "<span>")
3043 $bracketState = 2; // building tag name
3044 } elseif ( $bracketState == 2 ) {
3048 // Name found (e.g. "<a href=..."), add on tag attributes...
3049 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3051 } elseif ( $bracketState == 0 ) {
3052 if ( $entityState ) {
3055 $dispLen++
; // entity is one displayed char
3058 if ( $neLength == 0 && !$maybeState ) {
3059 // Save state without $ch. We want to *hit* the first
3060 // display char (to get tags) but not *use* it if truncating.
3061 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3064 $entityState = 1; // entity found, (e.g. " ")
3066 $dispLen++
; // this char is displayed
3067 // Add the next $max display text chars after this in one swoop...
3068 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3069 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3070 $dispLen +
= $skipped;
3076 // Close the last tag if left unclosed by bad HTML
3077 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3078 while ( count( $openTags ) > 0 ) {
3079 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3085 * truncateHtml() helper function
3086 * like strcspn() but adds the skipped chars to $ret
3095 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3096 if ( $len === null ) {
3097 $len = -1; // -1 means "no limit" for strcspn
3098 } elseif ( $len < 0 ) {
3102 if ( $start < strlen( $text ) ) {
3103 $skipCount = strcspn( $text, $search, $start, $len );
3104 $ret .= substr( $text, $start, $skipCount );
3110 * truncateHtml() helper function
3111 * (a) push or pop $tag from $openTags as needed
3112 * (b) clear $tag value
3113 * @param &$tag string Current HTML tag name we are looking at
3114 * @param $tagType int (0-open tag, 1-close tag)
3115 * @param $lastCh char|string Character before the '>' that ended this tag
3116 * @param &$openTags array Open tag stack (not accounting for $tag)
3118 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3119 $tag = ltrim( $tag );
3121 if ( $tagType == 0 && $lastCh != '/' ) {
3122 $openTags[] = $tag; // tag opened (didn't close itself)
3123 } elseif ( $tagType == 1 ) {
3124 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3125 array_pop( $openTags ); // tag closed
3133 * Grammatical transformations, needed for inflected languages
3134 * Invoked by putting {{grammar:case|word}} in a message
3136 * @param $word string
3137 * @param $case string
3140 function convertGrammar( $word, $case ) {
3141 global $wgGrammarForms;
3142 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3143 return $wgGrammarForms[$this->getCode()][$case][$word];
3149 * Provides an alternative text depending on specified gender.
3150 * Usage {{gender:username|masculine|feminine|neutral}}.
3151 * username is optional, in which case the gender of current user is used,
3152 * but only in (some) interface messages; otherwise default gender is used.
3153 * If second or third parameter are not specified, masculine is used.
3154 * These details may be overriden per language.
3156 * @param $gender string
3157 * @param $forms array
3161 function gender( $gender, $forms ) {
3162 if ( !count( $forms ) ) {
3165 $forms = $this->preConvertPlural( $forms, 2 );
3166 if ( $gender === 'male' ) {
3169 if ( $gender === 'female' ) {
3172 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3176 * Plural form transformations, needed for some languages.
3177 * For example, there are 3 form of plural in Russian and Polish,
3178 * depending on "count mod 10". See [[w:Plural]]
3179 * For English it is pretty simple.
3181 * Invoked by putting {{plural:count|wordform1|wordform2}}
3182 * or {{plural:count|wordform1|wordform2|wordform3}}
3184 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3186 * @param $count Integer: non-localized number
3187 * @param $forms Array: different plural forms
3188 * @return string Correct form of plural for $count in this language
3190 function convertPlural( $count, $forms ) {
3191 if ( !count( $forms ) ) {
3194 $forms = $this->preConvertPlural( $forms, 2 );
3196 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3200 * Checks that convertPlural was given an array and pads it to requested
3201 * amount of forms by copying the last one.
3203 * @param $count Integer: How many forms should there be at least
3204 * @param $forms Array of forms given to convertPlural
3205 * @return array Padded array of forms or an exception if not an array
3207 protected function preConvertPlural( /* Array */ $forms, $count ) {
3208 while ( count( $forms ) < $count ) {
3209 $forms[] = $forms[count( $forms ) - 1];
3215 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3216 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3217 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3218 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3221 * @param $str String: the validated block duration in English
3222 * @return Somehow translated block duration
3223 * @see LanguageFi.php for example implementation
3225 function translateBlockExpiry( $str ) {
3226 $duration = SpecialBlock
::getSuggestedDurations( $this );
3227 foreach ( $duration as $show => $value ) {
3228 if ( strcmp( $str, $value ) == 0 ) {
3229 return htmlspecialchars( trim( $show ) );
3233 // Since usually only infinite or indefinite is only on list, so try
3234 // equivalents if still here.
3235 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3236 if ( in_array( $str, $indefs ) ) {
3237 foreach ( $indefs as $val ) {
3238 $show = array_search( $val, $duration, true );
3239 if ( $show !== false ) {
3240 return htmlspecialchars( trim( $show ) );
3244 // If all else fails, return the original string.
3249 * languages like Chinese need to be segmented in order for the diff
3252 * @param $text String
3255 public function segmentForDiff( $text ) {
3260 * and unsegment to show the result
3262 * @param $text String
3265 public function unsegmentForDiff( $text ) {
3270 * Return the LanguageConverter used in the Language
3271 * @return LanguageConverter
3273 public function getConverter() {
3274 return $this->mConverter
;
3278 * convert text to all supported variants
3280 * @param $text string
3283 public function autoConvertToAllVariants( $text ) {
3284 return $this->mConverter
->autoConvertToAllVariants( $text );
3288 * convert text to different variants of a language.
3290 * @param $text string
3293 public function convert( $text ) {
3294 return $this->mConverter
->convert( $text );
3298 * Convert a Title object to a string in the preferred variant
3300 * @param $title Title
3303 public function convertTitle( $title ) {
3304 return $this->mConverter
->convertTitle( $title );
3308 * Check if this is a language with variants
3312 public function hasVariants() {
3313 return sizeof( $this->getVariants() ) > 1;
3317 * Check if the language has the specific variant
3318 * @param $variant string
3321 public function hasVariant( $variant ) {
3322 return (bool)$this->mConverter
->validateVariant( $variant );
3326 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3328 * @param $text string
3331 public function armourMath( $text ) {
3332 return $this->mConverter
->armourMath( $text );
3336 * Perform output conversion on a string, and encode for safe HTML output.
3337 * @param $text String text to be converted
3338 * @param $isTitle Bool whether this conversion is for the article title
3340 * @todo this should get integrated somewhere sane
3342 public function convertHtml( $text, $isTitle = false ) {
3343 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3347 * @param $key string
3350 public function convertCategoryKey( $key ) {
3351 return $this->mConverter
->convertCategoryKey( $key );
3355 * Get the list of variants supported by this language
3356 * see sample implementation in LanguageZh.php
3358 * @return array an array of language codes
3360 public function getVariants() {
3361 return $this->mConverter
->getVariants();
3367 public function getPreferredVariant() {
3368 return $this->mConverter
->getPreferredVariant();
3374 public function getDefaultVariant() {
3375 return $this->mConverter
->getDefaultVariant();
3381 public function getURLVariant() {
3382 return $this->mConverter
->getURLVariant();
3386 * If a language supports multiple variants, it is
3387 * possible that non-existing link in one variant
3388 * actually exists in another variant. this function
3389 * tries to find it. See e.g. LanguageZh.php
3391 * @param $link String: the name of the link
3392 * @param $nt Mixed: the title object of the link
3393 * @param $ignoreOtherCond Boolean: to disable other conditions when
3394 * we need to transclude a template or update a category's link
3395 * @return null the input parameters may be modified upon return
3397 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3398 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3402 * If a language supports multiple variants, converts text
3403 * into an array of all possible variants of the text:
3404 * 'variant' => text in that variant
3406 * @deprecated since 1.17 Use autoConvertToAllVariants()
3408 * @param $text string
3412 public function convertLinkToAllVariants( $text ) {
3413 return $this->mConverter
->convertLinkToAllVariants( $text );
3417 * returns language specific options used by User::getPageRenderHash()
3418 * for example, the preferred language variant
3422 function getExtraHashOptions() {
3423 return $this->mConverter
->getExtraHashOptions();
3427 * For languages that support multiple variants, the title of an
3428 * article may be displayed differently in different variants. this
3429 * function returns the apporiate title defined in the body of the article.
3433 public function getParsedTitle() {
3434 return $this->mConverter
->getParsedTitle();
3438 * Enclose a string with the "no conversion" tag. This is used by
3439 * various functions in the Parser
3441 * @param $text String: text to be tagged for no conversion
3442 * @param $noParse bool
3443 * @return string the tagged text
3445 public function markNoConversion( $text, $noParse = false ) {
3446 return $this->mConverter
->markNoConversion( $text, $noParse );
3450 * A regular expression to match legal word-trailing characters
3451 * which should be merged onto a link of the form [[foo]]bar.
3455 public function linkTrail() {
3456 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3462 function getLangObj() {
3467 * Get the RFC 3066 code for this language object
3471 public function getCode() {
3472 return $this->mCode
;
3476 * Get the code in Bcp47 format which we can use
3477 * inside of html lang="" tags.
3481 public function getHtmlCode() {
3482 if ( is_null( $this->mHtmlCode
) ) {
3483 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3485 return $this->mHtmlCode
;
3489 * @param $code string
3491 public function setCode( $code ) {
3492 $this->mCode
= $code;
3493 // Ensure we don't leave an incorrect html code lying around
3494 $this->mHtmlCode
= null;
3498 * Get the name of a file for a certain language code
3499 * @param $prefix string Prepend this to the filename
3500 * @param $code string Language code
3501 * @param $suffix string Append this to the filename
3502 * @return string $prefix . $mangledCode . $suffix
3504 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3505 // Protect against path traversal
3506 if ( !Language
::isValidCode( $code )
3507 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3509 throw new MWException( "Invalid language code \"$code\"" );
3512 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3516 * Get the language code from a file name. Inverse of getFileName()
3517 * @param $filename string $prefix . $languageCode . $suffix
3518 * @param $prefix string Prefix before the language code
3519 * @param $suffix string Suffix after the language code
3520 * @return string Language code, or false if $prefix or $suffix isn't found
3522 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3524 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3525 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3526 if ( !count( $m ) ) {
3529 return str_replace( '_', '-', strtolower( $m[1] ) );
3533 * @param $code string
3536 public static function getMessagesFileName( $code ) {
3538 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3539 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3544 * @param $code string
3547 public static function getClassFileName( $code ) {
3549 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3553 * Get the first fallback for a given language.
3555 * @param $code string
3557 * @return false|string
3559 public static function getFallbackFor( $code ) {
3560 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3563 $fallbacks = self
::getFallbacksFor( $code );
3564 $first = array_shift( $fallbacks );
3570 * Get the ordered list of fallback languages.
3573 * @param $code string Language code
3576 public static function getFallbacksFor( $code ) {
3577 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3580 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3581 $v = array_map( 'trim', explode( ',', $v ) );
3582 if ( $v[count( $v ) - 1] !== 'en' ) {
3590 * Get all messages for a given language
3591 * WARNING: this may take a long time. If you just need all message *keys*
3592 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3594 * @param $code string
3598 public static function getMessagesFor( $code ) {
3599 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3603 * Get a message for a given language
3605 * @param $key string
3606 * @param $code string
3610 public static function getMessageFor( $key, $code ) {
3611 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3615 * Get all message keys for a given language. This is a faster alternative to
3616 * array_keys( Language::getMessagesFor( $code ) )
3619 * @param $code string Language code
3620 * @return array of message keys (strings)
3622 public static function getMessageKeysFor( $code ) {
3623 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3630 function fixVariableInNamespace( $talk ) {
3631 if ( strpos( $talk, '$1' ) === false ) {
3635 global $wgMetaNamespace;
3636 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3638 # Allow grammar transformations
3639 # Allowing full message-style parsing would make simple requests
3640 # such as action=raw much more expensive than they need to be.
3641 # This will hopefully cover most cases.
3642 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3643 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3644 return str_replace( ' ', '_', $talk );
3651 function replaceGrammarInNamespace( $m ) {
3652 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3656 * @throws MWException
3659 static function getCaseMaps() {
3660 static $wikiUpperChars, $wikiLowerChars;
3661 if ( isset( $wikiUpperChars ) ) {
3662 return array( $wikiUpperChars, $wikiLowerChars );
3665 wfProfileIn( __METHOD__
);
3666 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3667 if ( $arr === false ) {
3668 throw new MWException(
3669 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3671 $wikiUpperChars = $arr['wikiUpperChars'];
3672 $wikiLowerChars = $arr['wikiLowerChars'];
3673 wfProfileOut( __METHOD__
);
3674 return array( $wikiUpperChars, $wikiLowerChars );
3678 * Decode an expiry (block, protection, etc) which has come from the DB
3680 * @param $expiry String: Database expiry String
3681 * @param $format Bool|Int true to process using language functions, or TS_ constant
3682 * to return the expiry in a given timestamp
3685 public function formatExpiry( $expiry, $format = true ) {
3686 static $infinity, $infinityMsg;
3687 if ( $infinity === null ) {
3688 $infinityMsg = wfMessage( 'infiniteblock' );
3689 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3692 if ( $expiry == '' ||
$expiry == $infinity ) {
3693 return $format === true
3697 return $format === true
3698 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3699 : wfTimestamp( $format, $expiry );
3705 * @param $seconds int|float
3706 * @param $format Array Optional
3707 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3708 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3709 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3710 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3713 function formatTimePeriod( $seconds, $format = array() ) {
3714 if ( !is_array( $format ) ) {
3715 $format = array( 'avoid' => $format ); // For backwards compatibility
3717 if ( !isset( $format['avoid'] ) ) {
3718 $format['avoid'] = false;
3720 if ( !isset( $format['noabbrevs' ] ) ) {
3721 $format['noabbrevs'] = false;
3723 $secondsMsg = wfMessage(
3724 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3725 $minutesMsg = wfMessage(
3726 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3727 $hoursMsg = wfMessage(
3728 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3729 $daysMsg = wfMessage(
3730 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3732 if ( round( $seconds * 10 ) < 100 ) {
3733 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3734 $s = $secondsMsg->params( $s )->text();
3735 } elseif ( round( $seconds ) < 60 ) {
3736 $s = $this->formatNum( round( $seconds ) );
3737 $s = $secondsMsg->params( $s )->text();
3738 } elseif ( round( $seconds ) < 3600 ) {
3739 $minutes = floor( $seconds / 60 );
3740 $secondsPart = round( fmod( $seconds, 60 ) );
3741 if ( $secondsPart == 60 ) {
3745 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3747 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3748 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3749 $hours = floor( $seconds / 3600 );
3750 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3751 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3752 if ( $secondsPart == 60 ) {
3756 if ( $minutes == 60 ) {
3760 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3762 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3763 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3764 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3767 $days = floor( $seconds / 86400 );
3768 if ( $format['avoid'] === 'avoidminutes' ) {
3769 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3770 if ( $hours == 24 ) {
3774 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3776 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3777 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3778 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3779 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3780 if ( $minutes == 60 ) {
3784 if ( $hours == 24 ) {
3788 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3790 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3792 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3794 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3796 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3806 function formatBitrate( $bps ) {
3807 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3809 return $this->formatNum( $bps ) . $units[0];
3811 $unitIndex = (int)floor( log10( $bps ) / 3 );
3812 $mantissa = $bps / pow( 1000, $unitIndex );
3813 if ( $mantissa < 10 ) {
3814 $mantissa = round( $mantissa, 1 );
3816 $mantissa = round( $mantissa );
3818 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3822 * Format a size in bytes for output, using an appropriate
3823 * unit (B, KB, MB or GB) according to the magnitude in question
3825 * @param $size int Size to format
3826 * @return string Plain text (not HTML)
3828 function formatSize( $size ) {
3829 // For small sizes no decimal places necessary
3831 if ( $size > 1024 ) {
3832 $size = $size / 1024;
3833 if ( $size > 1024 ) {
3834 $size = $size / 1024;
3835 // For MB and bigger two decimal places are smarter
3837 if ( $size > 1024 ) {
3838 $size = $size / 1024;
3839 $msg = 'size-gigabytes';
3841 $msg = 'size-megabytes';
3844 $msg = 'size-kilobytes';
3847 $msg = 'size-bytes';
3849 $size = round( $size, $round );
3850 $text = $this->getMessageFromDB( $msg );
3851 return str_replace( '$1', $this->formatNum( $size ), $text );
3855 * Make a list item, used by various special pages
3857 * @param $page String Page link
3858 * @param $details String Text between brackets
3859 * @param $oppositedm Boolean Add the direction mark opposite to your
3860 * language, to display text properly
3863 function specialList( $page, $details, $oppositedm = true ) {
3864 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3865 $this->getDirMark();
3866 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3867 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3868 return $page . $details;
3872 * Generate (prev x| next x) (20|50|100...) type links for paging
3874 * @param $title Title object to link
3875 * @param $offset Integer offset parameter
3876 * @param $limit Integer limit parameter
3877 * @param $query String optional URL query parameter string
3878 * @param $atend Bool optional param for specified if this is the last page
3881 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3882 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3884 # Make 'previous' link
3885 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3887 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3888 $query, $prev, 'prevn-title', 'mw-prevlink' );
3890 $plink = htmlspecialchars( $prev );
3894 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3896 $nlink = htmlspecialchars( $next );
3898 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3899 $query, $next, 'prevn-title', 'mw-nextlink' );
3902 # Make links to set number of items per page
3903 $numLinks = array();
3904 foreach( array( 20, 50, 100, 250, 500 ) as $num ) {
3905 $numLinks[] = $this->numLink( $title, $offset, $num,
3906 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3909 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3910 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
3914 * Helper function for viewPrevNext() that generates links
3916 * @param $title Title object to link
3917 * @param $offset Integer offset parameter
3918 * @param $limit Integer limit parameter
3919 * @param $query Array extra query parameters
3920 * @param $link String text to use for the link; will be escaped
3921 * @param $tooltipMsg String name of the message to use as tooltip
3922 * @param $class String value of the "class" attribute of the link
3923 * @return String HTML fragment
3925 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
3926 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
3927 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3928 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
3929 'title' => $tooltip, 'class' => $class ), $link );
3933 * Get the conversion rule title, if any.
3937 public function getConvRuleTitle() {
3938 return $this->mConverter
->getConvRuleTitle();