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 ) {
662 // We do this using a foreach over the codes instead of a directory
663 // loop so that messages files in extensions will work correctly.
664 foreach ( $allNames as $code => $value ) {
665 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
666 $names[$code] = $allNames[$code];
673 * Get translated language names. This is done on best effort and
674 * by default this is exactly the same as Language::getLanguageNames.
675 * The CLDR extension provides translated names.
676 * @param $code String Language code.
677 * @return Array language code => language name
680 public static function getTranslatedLanguageNames( $code ) {
682 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
684 foreach ( self
::getLanguageNames() as $code => $name ) {
685 if ( !isset( $names[$code] ) ) $names[$code] = $name;
692 * Get a message from the MediaWiki namespace.
694 * @param $msg String: message name
697 function getMessageFromDB( $msg ) {
698 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
702 * @param $code string
705 function getLanguageName( $code ) {
706 $names = self
::getLanguageNames();
707 if ( !array_key_exists( $code, $names ) ) {
710 return $names[$code];
717 function getMonthName( $key ) {
718 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
724 function getMonthNamesArray() {
725 $monthNames = array( '' );
726 for ( $i = 1; $i < 13; $i++
) {
727 $monthNames[] = $this->getMonthName( $i );
736 function getMonthNameGen( $key ) {
737 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
744 function getMonthAbbreviation( $key ) {
745 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
751 function getMonthAbbreviationsArray() {
752 $monthNames = array( '' );
753 for ( $i = 1; $i < 13; $i++
) {
754 $monthNames[] = $this->getMonthAbbreviation( $i );
763 function getWeekdayName( $key ) {
764 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
771 function getWeekdayAbbreviation( $key ) {
772 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
779 function getIranianCalendarMonthName( $key ) {
780 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
787 function getHebrewCalendarMonthName( $key ) {
788 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
795 function getHebrewCalendarMonthNameGen( $key ) {
796 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
803 function getHijriCalendarMonthName( $key ) {
804 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
808 * This is a workalike of PHP's date() function, but with better
809 * internationalisation, a reduced set of format characters, and a better
812 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
813 * PHP manual for definitions. There are a number of extensions, which
816 * xn Do not translate digits of the next numeric format character
817 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
818 * xr Use roman numerals for the next numeric format character
819 * xh Use hebrew numerals for the next numeric format character
821 * xg Genitive month name
823 * xij j (day number) in Iranian calendar
824 * xiF F (month name) in Iranian calendar
825 * xin n (month number) in Iranian calendar
826 * xiy y (two digit year) in Iranian calendar
827 * xiY Y (full year) in Iranian calendar
829 * xjj j (day number) in Hebrew calendar
830 * xjF F (month name) in Hebrew calendar
831 * xjt t (days in month) in Hebrew calendar
832 * xjx xg (genitive month name) in Hebrew calendar
833 * xjn n (month number) in Hebrew calendar
834 * xjY Y (full year) in Hebrew calendar
836 * xmj j (day number) in Hijri calendar
837 * xmF F (month name) in Hijri calendar
838 * xmn n (month number) in Hijri calendar
839 * xmY Y (full year) in Hijri calendar
841 * xkY Y (full year) in Thai solar calendar. Months and days are
842 * identical to the Gregorian calendar
843 * xoY Y (full year) in Minguo calendar or Juche year.
844 * Months and days are identical to the
846 * xtY Y (full year) in Japanese nengo. Months and days are
847 * identical to the Gregorian calendar
849 * Characters enclosed in double quotes will be considered literal (with
850 * the quotes themselves removed). Unmatched quotes will be considered
851 * literal quotes. Example:
853 * "The month is" F => The month is January
856 * Backslash escaping is also supported.
858 * Input timestamp is assumed to be pre-normalized to the desired local
861 * @param $format String
862 * @param $ts String: 14-character timestamp
865 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
869 function sprintfDate( $format, $ts ) {
882 for ( $p = 0; $p < strlen( $format ); $p++
) {
885 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
886 $code .= $format[++
$p];
889 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
890 $code .= $format[++
$p];
901 $rawToggle = !$rawToggle;
910 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
913 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
914 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
917 $num = substr( $ts, 6, 2 );
920 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
921 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
924 $num = intval( substr( $ts, 6, 2 ) );
928 $iranian = self
::tsToIranian( $ts );
934 $hijri = self
::tsToHijri( $ts );
940 $hebrew = self
::tsToHebrew( $ts );
946 $unix = wfTimestamp( TS_UNIX
, $ts );
948 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
952 $unix = wfTimestamp( TS_UNIX
, $ts );
954 $w = gmdate( 'w', $unix );
959 $unix = wfTimestamp( TS_UNIX
, $ts );
961 $num = gmdate( 'w', $unix );
965 $unix = wfTimestamp( TS_UNIX
, $ts );
967 $num = gmdate( 'z', $unix );
971 $unix = wfTimestamp( TS_UNIX
, $ts );
973 $num = gmdate( 'W', $unix );
976 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
980 $iranian = self
::tsToIranian( $ts );
982 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
986 $hijri = self
::tsToHijri( $ts );
988 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
992 $hebrew = self
::tsToHebrew( $ts );
994 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
997 $num = substr( $ts, 4, 2 );
1000 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1003 $num = intval( substr( $ts, 4, 2 ) );
1007 $iranian = self
::tsToIranian( $ts );
1013 $hijri = self
::tsToHijri ( $ts );
1019 $hebrew = self
::tsToHebrew( $ts );
1025 $unix = wfTimestamp( TS_UNIX
, $ts );
1027 $num = gmdate( 't', $unix );
1031 $hebrew = self
::tsToHebrew( $ts );
1037 $unix = wfTimestamp( TS_UNIX
, $ts );
1039 $num = gmdate( 'L', $unix );
1043 $unix = wfTimestamp( TS_UNIX
, $ts );
1045 $num = date( 'o', $unix );
1048 $num = substr( $ts, 0, 4 );
1052 $iranian = self
::tsToIranian( $ts );
1058 $hijri = self
::tsToHijri( $ts );
1064 $hebrew = self
::tsToHebrew( $ts );
1070 $thai = self
::tsToYear( $ts, 'thai' );
1076 $minguo = self
::tsToYear( $ts, 'minguo' );
1082 $tenno = self
::tsToYear( $ts, 'tenno' );
1087 $num = substr( $ts, 2, 2 );
1091 $iranian = self
::tsToIranian( $ts );
1093 $num = substr( $iranian[0], -2 );
1096 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1099 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1102 $h = substr( $ts, 8, 2 );
1103 $num = $h %
12 ?
$h %
12 : 12;
1106 $num = intval( substr( $ts, 8, 2 ) );
1109 $h = substr( $ts, 8, 2 );
1110 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1113 $num = substr( $ts, 8, 2 );
1116 $num = substr( $ts, 10, 2 );
1119 $num = substr( $ts, 12, 2 );
1123 $unix = wfTimestamp( TS_UNIX
, $ts );
1125 $s .= gmdate( 'c', $unix );
1129 $unix = wfTimestamp( TS_UNIX
, $ts );
1131 $s .= gmdate( 'r', $unix );
1135 $unix = wfTimestamp( TS_UNIX
, $ts );
1140 # Backslash escaping
1141 if ( $p < strlen( $format ) - 1 ) {
1142 $s .= $format[++
$p];
1149 if ( $p < strlen( $format ) - 1 ) {
1150 $endQuote = strpos( $format, '"', $p +
1 );
1151 if ( $endQuote === false ) {
1152 # No terminating quote, assume literal "
1155 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1159 # Quote at end of string, assume literal "
1166 if ( $num !== false ) {
1167 if ( $rawToggle ||
$raw ) {
1170 } elseif ( $roman ) {
1171 $s .= self
::romanNumeral( $num );
1173 } elseif ( $hebrewNum ) {
1174 $s .= self
::hebrewNumeral( $num );
1177 $s .= $this->formatNum( $num, true );
1184 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1185 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1188 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1189 * Gregorian dates to Iranian dates. Originally written in C, it
1190 * is released under the terms of GNU Lesser General Public
1191 * License. Conversion to PHP was performed by Niklas Laxström.
1193 * Link: http://www.farsiweb.info/jalali/jalali.c
1199 private static function tsToIranian( $ts ) {
1200 $gy = substr( $ts, 0, 4 ) -1600;
1201 $gm = substr( $ts, 4, 2 ) -1;
1202 $gd = substr( $ts, 6, 2 ) -1;
1204 # Days passed from the beginning (including leap years)
1206 +
floor( ( $gy +
3 ) / 4 )
1207 - floor( ( $gy +
99 ) / 100 )
1208 +
floor( ( $gy +
399 ) / 400 );
1210 // Add days of the past months of this year
1211 for ( $i = 0; $i < $gm; $i++
) {
1212 $gDayNo +
= self
::$GREG_DAYS[$i];
1216 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1220 // Days passed in current month
1221 $gDayNo +
= (int)$gd;
1223 $jDayNo = $gDayNo - 79;
1225 $jNp = floor( $jDayNo / 12053 );
1228 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1231 if ( $jDayNo >= 366 ) {
1232 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1233 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1236 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1237 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1243 return array( $jy, $jm, $jd );
1247 * Converting Gregorian dates to Hijri dates.
1249 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1251 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1257 private static function tsToHijri( $ts ) {
1258 $year = substr( $ts, 0, 4 );
1259 $month = substr( $ts, 4, 2 );
1260 $day = substr( $ts, 6, 2 );
1268 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1269 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1272 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1273 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1274 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1277 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1278 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1281 $zl = $zjd -1948440 +
10632;
1282 $zn = (int)( ( $zl - 1 ) / 10631 );
1283 $zl = $zl - 10631 * $zn +
354;
1284 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1285 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1286 $zm = (int)( ( 24 * $zl ) / 709 );
1287 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1288 $zy = 30 * $zn +
$zj - 30;
1290 return array( $zy, $zm, $zd );
1294 * Converting Gregorian dates to Hebrew dates.
1296 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1297 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1298 * to translate the relevant functions into PHP and release them under
1301 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1302 * and Adar II is 14. In a non-leap year, Adar is 6.
1308 private static function tsToHebrew( $ts ) {
1310 $year = substr( $ts, 0, 4 );
1311 $month = substr( $ts, 4, 2 );
1312 $day = substr( $ts, 6, 2 );
1314 # Calculate Hebrew year
1315 $hebrewYear = $year +
3760;
1317 # Month number when September = 1, August = 12
1319 if ( $month > 12 ) {
1326 # Calculate day of year from 1 September
1328 for ( $i = 1; $i < $month; $i++
) {
1332 # Check if the year is leap
1333 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1336 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1343 # Calculate the start of the Hebrew year
1344 $start = self
::hebrewYearStart( $hebrewYear );
1346 # Calculate next year's start
1347 if ( $dayOfYear <= $start ) {
1348 # Day is before the start of the year - it is the previous year
1350 $nextStart = $start;
1354 # Add days since previous year's 1 September
1356 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1360 # Start of the new (previous) year
1361 $start = self
::hebrewYearStart( $hebrewYear );
1364 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1367 # Calculate Hebrew day of year
1368 $hebrewDayOfYear = $dayOfYear - $start;
1370 # Difference between year's days
1371 $diff = $nextStart - $start;
1372 # Add 12 (or 13 for leap years) days to ignore the difference between
1373 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1374 # difference is only about the year type
1375 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1381 # Check the year pattern, and is leap year
1382 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1383 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1384 # and non-leap years
1385 $yearPattern = $diff %
30;
1386 # Check if leap year
1387 $isLeap = $diff >= 30;
1389 # Calculate day in the month from number of day in the Hebrew year
1390 # Don't check Adar - if the day is not in Adar, we will stop before;
1391 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1392 $hebrewDay = $hebrewDayOfYear;
1395 while ( $hebrewMonth <= 12 ) {
1396 # Calculate days in this month
1397 if ( $isLeap && $hebrewMonth == 6 ) {
1398 # Adar in a leap year
1400 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1402 if ( $hebrewDay <= $days ) {
1406 # Subtract the days of Adar I
1407 $hebrewDay -= $days;
1410 if ( $hebrewDay <= $days ) {
1416 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1417 # Cheshvan in a complete year (otherwise as the rule below)
1419 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1420 # Kislev in an incomplete year (otherwise as the rule below)
1423 # Odd months have 30 days, even have 29
1424 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1426 if ( $hebrewDay <= $days ) {
1427 # In the current month
1430 # Subtract the days of the current month
1431 $hebrewDay -= $days;
1432 # Try in the next month
1437 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1441 * This calculates the Hebrew year start, as days since 1 September.
1442 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1443 * Used for Hebrew date.
1449 private static function hebrewYearStart( $year ) {
1450 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1451 $b = intval( ( $year - 1 ) %
4 );
1452 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1456 $Mar = intval( $m );
1462 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1463 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1465 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1467 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1471 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1476 * Algorithm to convert Gregorian dates to Thai solar dates,
1477 * Minguo dates or Minguo dates.
1479 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1480 * http://en.wikipedia.org/wiki/Minguo_calendar
1481 * http://en.wikipedia.org/wiki/Japanese_era_name
1483 * @param $ts String: 14-character timestamp
1484 * @param $cName String: calender name
1485 * @return Array: converted year, month, day
1487 private static function tsToYear( $ts, $cName ) {
1488 $gy = substr( $ts, 0, 4 );
1489 $gm = substr( $ts, 4, 2 );
1490 $gd = substr( $ts, 6, 2 );
1492 if ( !strcmp( $cName, 'thai' ) ) {
1494 # Add 543 years to the Gregorian calendar
1495 # Months and days are identical
1496 $gy_offset = $gy +
543;
1497 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1499 # Deduct 1911 years from the Gregorian calendar
1500 # Months and days are identical
1501 $gy_offset = $gy - 1911;
1502 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1503 # Nengō dates up to Meiji period
1504 # Deduct years from the Gregorian calendar
1505 # depending on the nengo periods
1506 # Months and days are identical
1507 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1509 $gy_gannen = $gy - 1868 +
1;
1510 $gy_offset = $gy_gannen;
1511 if ( $gy_gannen == 1 ) {
1514 $gy_offset = '明治' . $gy_offset;
1516 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1517 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1518 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1519 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1520 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1524 $gy_gannen = $gy - 1912 +
1;
1525 $gy_offset = $gy_gannen;
1526 if ( $gy_gannen == 1 ) {
1529 $gy_offset = '大正' . $gy_offset;
1531 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1532 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1533 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1537 $gy_gannen = $gy - 1926 +
1;
1538 $gy_offset = $gy_gannen;
1539 if ( $gy_gannen == 1 ) {
1542 $gy_offset = '昭和' . $gy_offset;
1545 $gy_gannen = $gy - 1989 +
1;
1546 $gy_offset = $gy_gannen;
1547 if ( $gy_gannen == 1 ) {
1550 $gy_offset = '平成' . $gy_offset;
1556 return array( $gy_offset, $gm, $gd );
1560 * Roman number formatting up to 3000
1566 static function romanNumeral( $num ) {
1567 static $table = array(
1568 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1569 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1570 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1571 array( '', 'M', 'MM', 'MMM' )
1574 $num = intval( $num );
1575 if ( $num > 3000 ||
$num <= 0 ) {
1580 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1581 if ( $num >= $pow10 ) {
1582 $s .= $table[$i][(int)floor( $num / $pow10 )];
1584 $num = $num %
$pow10;
1590 * Hebrew Gematria number formatting up to 9999
1596 static function hebrewNumeral( $num ) {
1597 static $table = array(
1598 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1599 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1600 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1601 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1604 $num = intval( $num );
1605 if ( $num > 9999 ||
$num <= 0 ) {
1610 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1611 if ( $num >= $pow10 ) {
1612 if ( $num == 15 ||
$num == 16 ) {
1613 $s .= $table[0][9] . $table[0][$num - 9];
1616 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1617 if ( $pow10 == 1000 ) {
1622 $num = $num %
$pow10;
1624 if ( strlen( $s ) == 2 ) {
1627 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1628 $str .= substr( $s, strlen( $s ) - 2, 2 );
1630 $start = substr( $str, 0, strlen( $str ) - 2 );
1631 $end = substr( $str, strlen( $str ) - 2 );
1634 $str = $start . 'ך';
1637 $str = $start . 'ם';
1640 $str = $start . 'ן';
1643 $str = $start . 'ף';
1646 $str = $start . 'ץ';
1653 * Used by date() and time() to adjust the time output.
1655 * @param $ts Int the time in date('YmdHis') format
1656 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1657 * get user timecorrection setting)
1660 function userAdjust( $ts, $tz = false ) {
1661 global $wgUser, $wgLocalTZoffset;
1663 if ( $tz === false ) {
1664 $tz = $wgUser->getOption( 'timecorrection' );
1667 $data = explode( '|', $tz, 3 );
1669 if ( $data[0] == 'ZoneInfo' ) {
1670 wfSuppressWarnings();
1671 $userTZ = timezone_open( $data[2] );
1672 wfRestoreWarnings();
1673 if ( $userTZ !== false ) {
1674 $date = date_create( $ts, timezone_open( 'UTC' ) );
1675 date_timezone_set( $date, $userTZ );
1676 $date = date_format( $date, 'YmdHis' );
1679 # Unrecognized timezone, default to 'Offset' with the stored offset.
1680 $data[0] = 'Offset';
1684 if ( $data[0] == 'System' ||
$tz == '' ) {
1685 # Global offset in minutes.
1686 if ( isset( $wgLocalTZoffset ) ) {
1687 $minDiff = $wgLocalTZoffset;
1689 } elseif ( $data[0] == 'Offset' ) {
1690 $minDiff = intval( $data[1] );
1692 $data = explode( ':', $tz );
1693 if ( count( $data ) == 2 ) {
1694 $data[0] = intval( $data[0] );
1695 $data[1] = intval( $data[1] );
1696 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1697 if ( $data[0] < 0 ) {
1698 $minDiff = -$minDiff;
1701 $minDiff = intval( $data[0] ) * 60;
1705 # No difference ? Return time unchanged
1706 if ( 0 == $minDiff ) {
1710 wfSuppressWarnings(); // E_STRICT system time bitching
1711 # Generate an adjusted date; take advantage of the fact that mktime
1712 # will normalize out-of-range values so we don't have to split $minDiff
1713 # into hours and minutes.
1715 (int)substr( $ts, 8, 2 ) ), # Hours
1716 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1717 (int)substr( $ts, 12, 2 ), # Seconds
1718 (int)substr( $ts, 4, 2 ), # Month
1719 (int)substr( $ts, 6, 2 ), # Day
1720 (int)substr( $ts, 0, 4 ) ); # Year
1722 $date = date( 'YmdHis', $t );
1723 wfRestoreWarnings();
1729 * This is meant to be used by time(), date(), and timeanddate() to get
1730 * the date preference they're supposed to use, it should be used in
1734 * function timeanddate([...], $format = true) {
1735 * $datePreference = $this->dateFormat($format);
1740 * @param $usePrefs Mixed: if true, the user's preference is used
1741 * if false, the site/language default is used
1742 * if int/string, assumed to be a format.
1745 function dateFormat( $usePrefs = true ) {
1748 if ( is_bool( $usePrefs ) ) {
1750 $datePreference = $wgUser->getDatePreference();
1752 $datePreference = (string)User
::getDefaultOption( 'date' );
1755 $datePreference = (string)$usePrefs;
1759 if ( $datePreference == '' ) {
1763 return $datePreference;
1767 * Get a format string for a given type and preference
1768 * @param $type string May be date, time or both
1769 * @param $pref string The format name as it appears in Messages*.php
1773 function getDateFormatString( $type, $pref ) {
1774 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1775 if ( $pref == 'default' ) {
1776 $pref = $this->getDefaultDateFormat();
1777 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1779 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1780 if ( is_null( $df ) ) {
1781 $pref = $this->getDefaultDateFormat();
1782 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1785 $this->dateFormatStrings
[$type][$pref] = $df;
1787 return $this->dateFormatStrings
[$type][$pref];
1791 * @param $ts Mixed: the time format which needs to be turned into a
1792 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1793 * @param $adj Bool: whether to adjust the time output according to the
1794 * user configured offset ($timecorrection)
1795 * @param $format Mixed: true to use user's date format preference
1796 * @param $timecorrection String|bool the time offset as returned by
1797 * validateTimeZone() in Special:Preferences
1800 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1801 $ts = wfTimestamp( TS_MW
, $ts );
1803 $ts = $this->userAdjust( $ts, $timecorrection );
1805 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1806 return $this->sprintfDate( $df, $ts );
1810 * @param $ts Mixed: the time format which needs to be turned into a
1811 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1812 * @param $adj Bool: whether to adjust the time output according to the
1813 * user configured offset ($timecorrection)
1814 * @param $format Mixed: true to use user's date format preference
1815 * @param $timecorrection String|bool the time offset as returned by
1816 * validateTimeZone() in Special:Preferences
1819 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1820 $ts = wfTimestamp( TS_MW
, $ts );
1822 $ts = $this->userAdjust( $ts, $timecorrection );
1824 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1825 return $this->sprintfDate( $df, $ts );
1829 * @param $ts Mixed: the time format which needs to be turned into a
1830 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1831 * @param $adj Bool: whether to adjust the time output according to the
1832 * user configured offset ($timecorrection)
1833 * @param $format Mixed: what format to return, if it's false output the
1834 * default one (default true)
1835 * @param $timecorrection String|bool the time offset as returned by
1836 * validateTimeZone() in Special:Preferences
1839 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1840 $ts = wfTimestamp( TS_MW
, $ts );
1842 $ts = $this->userAdjust( $ts, $timecorrection );
1844 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1845 return $this->sprintfDate( $df, $ts );
1849 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1851 * @param $type String: can be 'date', 'time' or 'both'
1852 * @param $ts Mixed: the time format which needs to be turned into a
1853 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1854 * @param $user User object used to get preferences for timezone and format
1855 * @param $options Array, can contain the following keys:
1856 * - 'timecorrection': time correction, can have the following values:
1857 * - true: use user's preference
1858 * - false: don't use time correction
1859 * - integer: value of time correction in minutes
1860 * - 'format': format to use, can have the following values:
1861 * - true: use user's preference
1862 * - false: use default preference
1863 * - string: format to use
1866 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1867 $ts = wfTimestamp( TS_MW
, $ts );
1868 $options +
= array( 'timecorrection' => true, 'format' => true );
1869 if ( $options['timecorrection'] !== false ) {
1870 if ( $options['timecorrection'] === true ) {
1871 $offset = $user->getOption( 'timecorrection' );
1873 $offset = $options['timecorrection'];
1875 $ts = $this->userAdjust( $ts, $offset );
1877 if ( $options['format'] === true ) {
1878 $format = $user->getDatePreference();
1880 $format = $options['format'];
1882 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1883 return $this->sprintfDate( $df, $ts );
1887 * Get the formatted date for the given timestamp and formatted for
1890 * @param $ts Mixed: the time format which needs to be turned into a
1891 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1892 * @param $user User object used to get preferences for timezone and format
1893 * @param $options Array, can contain the following keys:
1894 * - 'timecorrection': time correction, can have the following values:
1895 * - true: use user's preference
1896 * - false: don't use time correction
1897 * - integer: value of time correction in minutes
1898 * - 'format': format to use, can have the following values:
1899 * - true: use user's preference
1900 * - false: use default preference
1901 * - string: format to use
1904 public function userDate( $ts, User
$user, array $options = array() ) {
1905 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1909 * Get the formatted time for the given timestamp and formatted for
1912 * @param $ts Mixed: the time format which needs to be turned into a
1913 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1914 * @param $user User object used to get preferences for timezone and format
1915 * @param $options Array, can contain the following keys:
1916 * - 'timecorrection': time correction, can have the following values:
1917 * - true: use user's preference
1918 * - false: don't use time correction
1919 * - integer: value of time correction in minutes
1920 * - 'format': format to use, can have the following values:
1921 * - true: use user's preference
1922 * - false: use default preference
1923 * - string: format to use
1926 public function userTime( $ts, User
$user, array $options = array() ) {
1927 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1931 * Get the formatted date and time for the given timestamp and formatted for
1934 * @param $ts Mixed: the time format which needs to be turned into a
1935 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1936 * @param $user User object used to get preferences for timezone and format
1937 * @param $options Array, can contain the following keys:
1938 * - 'timecorrection': time correction, can have the following values:
1939 * - true: use user's preference
1940 * - false: don't use time correction
1941 * - integer: value of time correction in minutes
1942 * - 'format': format to use, can have the following values:
1943 * - true: use user's preference
1944 * - false: use default preference
1945 * - string: format to use
1948 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
1949 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
1953 * @param $key string
1954 * @return array|null
1956 function getMessage( $key ) {
1957 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1963 function getAllMessages() {
1964 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1973 function iconv( $in, $out, $string ) {
1974 # This is a wrapper for iconv in all languages except esperanto,
1975 # which does some nasty x-conversions beforehand
1977 # Even with //IGNORE iconv can whine about illegal characters in
1978 # *input* string. We just ignore those too.
1979 # REF: http://bugs.php.net/bug.php?id=37166
1980 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1981 wfSuppressWarnings();
1982 $text = iconv( $in, $out . '//IGNORE', $string );
1983 wfRestoreWarnings();
1987 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1990 * @param $matches array
1991 * @return mixed|string
1993 function ucwordbreaksCallbackAscii( $matches ) {
1994 return $this->ucfirst( $matches[1] );
1998 * @param $matches array
2001 function ucwordbreaksCallbackMB( $matches ) {
2002 return mb_strtoupper( $matches[0] );
2006 * @param $matches array
2009 function ucCallback( $matches ) {
2010 list( $wikiUpperChars ) = self
::getCaseMaps();
2011 return strtr( $matches[1], $wikiUpperChars );
2015 * @param $matches array
2018 function lcCallback( $matches ) {
2019 list( , $wikiLowerChars ) = self
::getCaseMaps();
2020 return strtr( $matches[1], $wikiLowerChars );
2024 * @param $matches array
2027 function ucwordsCallbackMB( $matches ) {
2028 return mb_strtoupper( $matches[0] );
2032 * @param $matches array
2035 function ucwordsCallbackWiki( $matches ) {
2036 list( $wikiUpperChars ) = self
::getCaseMaps();
2037 return strtr( $matches[0], $wikiUpperChars );
2041 * Make a string's first character uppercase
2043 * @param $str string
2047 function ucfirst( $str ) {
2049 if ( $o < 96 ) { // if already uppercase...
2051 } elseif ( $o < 128 ) {
2052 return ucfirst( $str ); // use PHP's ucfirst()
2054 // fall back to more complex logic in case of multibyte strings
2055 return $this->uc( $str, true );
2060 * Convert a string to uppercase
2062 * @param $str string
2063 * @param $first bool
2067 function uc( $str, $first = false ) {
2068 if ( function_exists( 'mb_strtoupper' ) ) {
2070 if ( $this->isMultibyte( $str ) ) {
2071 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2073 return ucfirst( $str );
2076 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2079 if ( $this->isMultibyte( $str ) ) {
2080 $x = $first ?
'^' : '';
2081 return preg_replace_callback(
2082 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2083 array( $this, 'ucCallback' ),
2087 return $first ?
ucfirst( $str ) : strtoupper( $str );
2093 * @param $str string
2094 * @return mixed|string
2096 function lcfirst( $str ) {
2099 return strval( $str );
2100 } elseif ( $o >= 128 ) {
2101 return $this->lc( $str, true );
2102 } elseif ( $o > 96 ) {
2105 $str[0] = strtolower( $str[0] );
2111 * @param $str string
2112 * @param $first bool
2113 * @return mixed|string
2115 function lc( $str, $first = false ) {
2116 if ( function_exists( 'mb_strtolower' ) ) {
2118 if ( $this->isMultibyte( $str ) ) {
2119 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2121 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2124 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2127 if ( $this->isMultibyte( $str ) ) {
2128 $x = $first ?
'^' : '';
2129 return preg_replace_callback(
2130 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2131 array( $this, 'lcCallback' ),
2135 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2141 * @param $str string
2144 function isMultibyte( $str ) {
2145 return (bool)preg_match( '/[\x80-\xff]/', $str );
2149 * @param $str string
2150 * @return mixed|string
2152 function ucwords( $str ) {
2153 if ( $this->isMultibyte( $str ) ) {
2154 $str = $this->lc( $str );
2156 // regexp to find first letter in each word (i.e. after each space)
2157 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2159 // function to use to capitalize a single char
2160 if ( function_exists( 'mb_strtoupper' ) ) {
2161 return preg_replace_callback(
2163 array( $this, 'ucwordsCallbackMB' ),
2167 return preg_replace_callback(
2169 array( $this, 'ucwordsCallbackWiki' ),
2174 return ucwords( strtolower( $str ) );
2179 * capitalize words at word breaks
2181 * @param $str string
2184 function ucwordbreaks( $str ) {
2185 if ( $this->isMultibyte( $str ) ) {
2186 $str = $this->lc( $str );
2188 // since \b doesn't work for UTF-8, we explicitely define word break chars
2189 $breaks = "[ \-\(\)\}\{\.,\?!]";
2191 // find first letter after word break
2192 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2194 if ( function_exists( 'mb_strtoupper' ) ) {
2195 return preg_replace_callback(
2197 array( $this, 'ucwordbreaksCallbackMB' ),
2201 return preg_replace_callback(
2203 array( $this, 'ucwordsCallbackWiki' ),
2208 return preg_replace_callback(
2209 '/\b([\w\x80-\xff]+)\b/',
2210 array( $this, 'ucwordbreaksCallbackAscii' ),
2217 * Return a case-folded representation of $s
2219 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2220 * and $s2 are the same except for the case of their characters. It is not
2221 * necessary for the value returned to make sense when displayed.
2223 * Do *not* perform any other normalisation in this function. If a caller
2224 * uses this function when it should be using a more general normalisation
2225 * function, then fix the caller.
2231 function caseFold( $s ) {
2232 return $this->uc( $s );
2239 function checkTitleEncoding( $s ) {
2240 if ( is_array( $s ) ) {
2241 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2243 # Check for non-UTF-8 URLs
2244 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2249 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2250 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2255 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2261 function fallback8bitEncoding() {
2262 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2266 * Most writing systems use whitespace to break up words.
2267 * Some languages such as Chinese don't conventionally do this,
2268 * which requires special handling when breaking up words for
2273 function hasWordBreaks() {
2278 * Some languages such as Chinese require word segmentation,
2279 * Specify such segmentation when overridden in derived class.
2281 * @param $string String
2284 function segmentByWord( $string ) {
2289 * Some languages have special punctuation need to be normalized.
2290 * Make such changes here.
2292 * @param $string String
2295 function normalizeForSearch( $string ) {
2296 return self
::convertDoubleWidth( $string );
2300 * convert double-width roman characters to single-width.
2301 * range: ff00-ff5f ~= 0020-007f
2303 * @param $string string
2307 protected static function convertDoubleWidth( $string ) {
2308 static $full = null;
2309 static $half = null;
2311 if ( $full === null ) {
2312 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2313 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2314 $full = str_split( $fullWidth, 3 );
2315 $half = str_split( $halfWidth );
2318 $string = str_replace( $full, $half, $string );
2323 * @param $string string
2324 * @param $pattern string
2327 protected static function insertSpace( $string, $pattern ) {
2328 $string = preg_replace( $pattern, " $1 ", $string );
2329 $string = preg_replace( '/ +/', ' ', $string );
2334 * @param $termsArray array
2337 function convertForSearchResult( $termsArray ) {
2338 # some languages, e.g. Chinese, need to do a conversion
2339 # in order for search results to be displayed correctly
2344 * Get the first character of a string.
2349 function firstChar( $s ) {
2352 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2353 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2358 if ( isset( $matches[1] ) ) {
2359 if ( strlen( $matches[1] ) != 3 ) {
2363 // Break down Hangul syllables to grab the first jamo
2364 $code = utf8ToCodepoint( $matches[1] );
2365 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2367 } elseif ( $code < 0xb098 ) {
2368 return "\xe3\x84\xb1";
2369 } elseif ( $code < 0xb2e4 ) {
2370 return "\xe3\x84\xb4";
2371 } elseif ( $code < 0xb77c ) {
2372 return "\xe3\x84\xb7";
2373 } elseif ( $code < 0xb9c8 ) {
2374 return "\xe3\x84\xb9";
2375 } elseif ( $code < 0xbc14 ) {
2376 return "\xe3\x85\x81";
2377 } elseif ( $code < 0xc0ac ) {
2378 return "\xe3\x85\x82";
2379 } elseif ( $code < 0xc544 ) {
2380 return "\xe3\x85\x85";
2381 } elseif ( $code < 0xc790 ) {
2382 return "\xe3\x85\x87";
2383 } elseif ( $code < 0xcc28 ) {
2384 return "\xe3\x85\x88";
2385 } elseif ( $code < 0xce74 ) {
2386 return "\xe3\x85\x8a";
2387 } elseif ( $code < 0xd0c0 ) {
2388 return "\xe3\x85\x8b";
2389 } elseif ( $code < 0xd30c ) {
2390 return "\xe3\x85\x8c";
2391 } elseif ( $code < 0xd558 ) {
2392 return "\xe3\x85\x8d";
2394 return "\xe3\x85\x8e";
2401 function initEncoding() {
2402 # Some languages may have an alternate char encoding option
2403 # (Esperanto X-coding, Japanese furigana conversion, etc)
2404 # If this language is used as the primary content language,
2405 # an override to the defaults can be set here on startup.
2412 function recodeForEdit( $s ) {
2413 # For some languages we'll want to explicitly specify
2414 # which characters make it into the edit box raw
2415 # or are converted in some way or another.
2416 global $wgEditEncoding;
2417 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2420 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2428 function recodeInput( $s ) {
2429 # Take the previous into account.
2430 global $wgEditEncoding;
2431 if ( $wgEditEncoding != '' ) {
2432 $enc = $wgEditEncoding;
2436 if ( $enc == 'UTF-8' ) {
2439 return $this->iconv( $enc, 'UTF-8', $s );
2444 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2445 * also cleans up certain backwards-compatible sequences, converting them
2446 * to the modern Unicode equivalent.
2448 * This is language-specific for performance reasons only.
2454 function normalize( $s ) {
2455 global $wgAllUnicodeFixes;
2456 $s = UtfNormal
::cleanUp( $s );
2457 if ( $wgAllUnicodeFixes ) {
2458 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2459 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2466 * Transform a string using serialized data stored in the given file (which
2467 * must be in the serialized subdirectory of $IP). The file contains pairs
2468 * mapping source characters to destination characters.
2470 * The data is cached in process memory. This will go faster if you have the
2471 * FastStringSearch extension.
2473 * @param $file string
2474 * @param $string string
2478 function transformUsingPairFile( $file, $string ) {
2479 if ( !isset( $this->transformData
[$file] ) ) {
2480 $data = wfGetPrecompiledData( $file );
2481 if ( $data === false ) {
2482 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2484 $this->transformData
[$file] = new ReplacementArray( $data );
2486 return $this->transformData
[$file]->replace( $string );
2490 * For right-to-left language support
2495 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2499 * Return the correct HTML 'dir' attribute value for this language.
2503 return $this->isRTL() ?
'rtl' : 'ltr';
2507 * Return 'left' or 'right' as appropriate alignment for line-start
2508 * for this language's text direction.
2510 * Should be equivalent to CSS3 'start' text-align value....
2514 function alignStart() {
2515 return $this->isRTL() ?
'right' : 'left';
2519 * Return 'right' or 'left' as appropriate alignment for line-end
2520 * for this language's text direction.
2522 * Should be equivalent to CSS3 'end' text-align value....
2526 function alignEnd() {
2527 return $this->isRTL() ?
'left' : 'right';
2531 * A hidden direction mark (LRM or RLM), depending on the language direction
2533 * @param $opposite Boolean Get the direction mark opposite to your language
2536 function getDirMark( $opposite = false ) {
2537 $rtl = "\xE2\x80\x8F";
2538 $ltr = "\xE2\x80\x8E";
2539 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2540 return $this->isRTL() ?
$rtl : $ltr;
2546 function capitalizeAllNouns() {
2547 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2551 * An arrow, depending on the language direction
2555 function getArrow() {
2556 return $this->isRTL() ?
'←' : '→';
2560 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2564 function linkPrefixExtension() {
2565 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2571 function getMagicWords() {
2572 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2575 protected function doMagicHook() {
2576 if ( $this->mMagicHookDone
) {
2579 $this->mMagicHookDone
= true;
2580 wfProfileIn( 'LanguageGetMagic' );
2581 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2582 wfProfileOut( 'LanguageGetMagic' );
2586 * Fill a MagicWord object with data from here
2590 function getMagic( $mw ) {
2591 $this->doMagicHook();
2593 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2594 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2596 $magicWords = $this->getMagicWords();
2597 if ( isset( $magicWords[$mw->mId
] ) ) {
2598 $rawEntry = $magicWords[$mw->mId
];
2604 if ( !is_array( $rawEntry ) ) {
2605 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2607 $mw->mCaseSensitive
= $rawEntry[0];
2608 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2613 * Add magic words to the extension array
2615 * @param $newWords array
2617 function addMagicWordsByLang( $newWords ) {
2618 $fallbackChain = $this->getFallbackLanguages();
2619 $fallbackChain = array_reverse( $fallbackChain );
2620 foreach ( $fallbackChain as $code ) {
2621 if ( isset( $newWords[$code] ) ) {
2622 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2628 * Get special page names, as an associative array
2629 * case folded alias => real name
2631 function getSpecialPageAliases() {
2632 // Cache aliases because it may be slow to load them
2633 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2635 $this->mExtendedSpecialPageAliases
=
2636 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2637 wfRunHooks( 'LanguageGetSpecialPageAliases',
2638 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2641 return $this->mExtendedSpecialPageAliases
;
2645 * Italic is unsuitable for some languages
2647 * @param $text String: the text to be emphasized.
2650 function emphasize( $text ) {
2651 return "<em>$text</em>";
2655 * Normally we output all numbers in plain en_US style, that is
2656 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2657 * point twohundredthirtyfive. However this is not suitable for all
2658 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2659 * Icelandic just want to use commas instead of dots, and dots instead
2660 * of commas like "293.291,235".
2662 * An example of this function being called:
2664 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2667 * See LanguageGu.php for the Gujarati implementation and
2668 * $separatorTransformTable on MessageIs.php for
2669 * the , => . and . => , implementation.
2671 * @todo check if it's viable to use localeconv() for the decimal
2673 * @param $number Mixed: the string to be formatted, should be an integer
2674 * or a floating point number.
2675 * @param $nocommafy Bool: set to true for special numbers like dates
2678 public function formatNum( $number, $nocommafy = false ) {
2679 global $wgTranslateNumerals;
2680 if ( !$nocommafy ) {
2681 $number = $this->commafy( $number );
2682 $s = $this->separatorTransformTable();
2684 $number = strtr( $number, $s );
2688 if ( $wgTranslateNumerals ) {
2689 $s = $this->digitTransformTable();
2691 $number = strtr( $number, $s );
2699 * @param $number string
2702 function parseFormattedNumber( $number ) {
2703 $s = $this->digitTransformTable();
2705 $number = strtr( $number, array_flip( $s ) );
2708 $s = $this->separatorTransformTable();
2710 $number = strtr( $number, array_flip( $s ) );
2713 $number = strtr( $number, array( ',' => '' ) );
2718 * Adds commas to a given number
2723 function commafy( $_ ) {
2724 $digitGroupingPattern = $this->digitGroupingPattern();
2726 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2727 // default grouping is at thousands, use the same for ###,###,### pattern too.
2728 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2730 // Ref: http://cldr.unicode.org/translation/number-patterns
2732 if ( intval( $_ ) < 0 ) {
2733 // For negative numbers apply the algorithm like positive number and add sign.
2735 $_ = substr( $_,1 );
2737 $numberpart = array();
2738 $decimalpart = array();
2739 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2740 preg_match( "/\d+/", $_, $numberpart );
2741 preg_match( "/\.\d*/", $_, $decimalpart );
2742 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2743 if ( $groupedNumber === $_ ) {
2744 // the string does not have any number part. Eg: .12345
2745 return $sign . $groupedNumber;
2747 $start = $end = strlen( $numberpart[0] );
2748 while ( $start > 0 ) {
2749 $match = $matches[0][$numMatches -1] ;
2750 $matchLen = strlen( $match );
2751 $start = $end - $matchLen;
2755 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2757 if ( $numMatches > 1 ) {
2758 // use the last pattern for the rest of the number
2762 $groupedNumber = "," . $groupedNumber;
2765 return $sign . $groupedNumber;
2771 function digitGroupingPattern() {
2772 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2778 function digitTransformTable() {
2779 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2785 function separatorTransformTable() {
2786 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2790 * Take a list of strings and build a locale-friendly comma-separated
2791 * list, using the local comma-separator message.
2792 * The last two strings are chained with an "and".
2797 function listToText( array $l ) {
2799 $m = count( $l ) - 1;
2801 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2803 for ( $i = $m; $i >= 0; $i-- ) {
2806 } elseif ( $i == $m - 1 ) {
2807 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2809 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2817 * Take a list of strings and build a locale-friendly comma-separated
2818 * list, using the local comma-separator message.
2819 * @param $list array of strings to put in a comma list
2822 function commaList( array $list ) {
2826 array( 'parsemag', 'escapenoentities', 'language' => $this )
2833 * Take a list of strings and build a locale-friendly semicolon-separated
2834 * list, using the local semicolon-separator message.
2835 * @param $list array of strings to put in a semicolon list
2838 function semicolonList( array $list ) {
2841 'semicolon-separator',
2842 array( 'parsemag', 'escapenoentities', 'language' => $this )
2849 * Same as commaList, but separate it with the pipe instead.
2850 * @param $list array of strings to put in a pipe list
2853 function pipeList( array $list ) {
2857 array( 'escapenoentities', 'language' => $this )
2864 * Truncate a string to a specified length in bytes, appending an optional
2865 * string (e.g. for ellipses)
2867 * The database offers limited byte lengths for some columns in the database;
2868 * multi-byte character sets mean we need to ensure that only whole characters
2869 * are included, otherwise broken characters can be passed to the user
2871 * If $length is negative, the string will be truncated from the beginning
2873 * @param $string String to truncate
2874 * @param $length Int: maximum length (including ellipses)
2875 * @param $ellipsis String to append to the truncated text
2876 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2877 * $adjustLength was introduced in 1.18, before that behaved as if false.
2880 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2881 # Use the localized ellipsis character
2882 if ( $ellipsis == '...' ) {
2883 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2885 # Check if there is no need to truncate
2886 if ( $length == 0 ) {
2887 return $ellipsis; // convention
2888 } elseif ( strlen( $string ) <= abs( $length ) ) {
2889 return $string; // no need to truncate
2891 $stringOriginal = $string;
2892 # If ellipsis length is >= $length then we can't apply $adjustLength
2893 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2894 $string = $ellipsis; // this can be slightly unexpected
2895 # Otherwise, truncate and add ellipsis...
2897 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2898 if ( $length > 0 ) {
2899 $length -= $eLength;
2900 $string = substr( $string, 0, $length ); // xyz...
2901 $string = $this->removeBadCharLast( $string );
2902 $string = $string . $ellipsis;
2904 $length +
= $eLength;
2905 $string = substr( $string, $length ); // ...xyz
2906 $string = $this->removeBadCharFirst( $string );
2907 $string = $ellipsis . $string;
2910 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2911 # This check is *not* redundant if $adjustLength, due to the single case where
2912 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2913 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2916 return $stringOriginal;
2921 * Remove bytes that represent an incomplete Unicode character
2922 * at the end of string (e.g. bytes of the char are missing)
2924 * @param $string String
2927 protected function removeBadCharLast( $string ) {
2928 if ( $string != '' ) {
2929 $char = ord( $string[strlen( $string ) - 1] );
2931 if ( $char >= 0xc0 ) {
2932 # We got the first byte only of a multibyte char; remove it.
2933 $string = substr( $string, 0, -1 );
2934 } elseif ( $char >= 0x80 &&
2935 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2936 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2938 # We chopped in the middle of a character; remove it
2946 * Remove bytes that represent an incomplete Unicode character
2947 * at the start of string (e.g. bytes of the char are missing)
2949 * @param $string String
2952 protected function removeBadCharFirst( $string ) {
2953 if ( $string != '' ) {
2954 $char = ord( $string[0] );
2955 if ( $char >= 0x80 && $char < 0xc0 ) {
2956 # We chopped in the middle of a character; remove the whole thing
2957 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2964 * Truncate a string of valid HTML to a specified length in bytes,
2965 * appending an optional string (e.g. for ellipses), and return valid HTML
2967 * This is only intended for styled/linked text, such as HTML with
2968 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2969 * Also, this will not detect things like "display:none" CSS.
2971 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2973 * @param string $text HTML string to truncate
2974 * @param int $length (zero/positive) Maximum length (including ellipses)
2975 * @param string $ellipsis String to append to the truncated text
2978 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2979 # Use the localized ellipsis character
2980 if ( $ellipsis == '...' ) {
2981 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2983 # Check if there is clearly no need to truncate
2984 if ( $length <= 0 ) {
2985 return $ellipsis; // no text shown, nothing to format (convention)
2986 } elseif ( strlen( $text ) <= $length ) {
2987 return $text; // string short enough even *with* HTML (short-circuit)
2990 $dispLen = 0; // innerHTML legth so far
2991 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2992 $tagType = 0; // 0-open, 1-close
2993 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2994 $entityState = 0; // 0-not entity, 1-entity
2995 $tag = $ret = ''; // accumulated tag name, accumulated result string
2996 $openTags = array(); // open tag stack
2997 $maybeState = null; // possible truncation state
2999 $textLen = strlen( $text );
3000 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3001 for ( $pos = 0; true; ++
$pos ) {
3002 # Consider truncation once the display length has reached the maximim.
3003 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3004 # Check that we're not in the middle of a bracket/entity...
3005 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3006 if ( !$testingEllipsis ) {
3007 $testingEllipsis = true;
3008 # Save where we are; we will truncate here unless there turn out to
3009 # be so few remaining characters that truncation is not necessary.
3010 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3011 $maybeState = array( $ret, $openTags ); // save state
3013 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3014 # String in fact does need truncation, the truncation point was OK.
3015 list( $ret, $openTags ) = $maybeState; // reload state
3016 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3017 $ret .= $ellipsis; // add ellipsis
3021 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3023 # Read the next char...
3025 $lastCh = $pos ?
$text[$pos - 1] : '';
3026 $ret .= $ch; // add to result string
3028 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3029 $entityState = 0; // for bad HTML
3030 $bracketState = 1; // tag started (checking for backslash)
3031 } elseif ( $ch == '>' ) {
3032 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3033 $entityState = 0; // for bad HTML
3034 $bracketState = 0; // out of brackets
3035 } elseif ( $bracketState == 1 ) {
3037 $tagType = 1; // close tag (e.g. "</span>")
3039 $tagType = 0; // open tag (e.g. "<span>")
3042 $bracketState = 2; // building tag name
3043 } elseif ( $bracketState == 2 ) {
3047 // Name found (e.g. "<a href=..."), add on tag attributes...
3048 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3050 } elseif ( $bracketState == 0 ) {
3051 if ( $entityState ) {
3054 $dispLen++
; // entity is one displayed char
3057 if ( $neLength == 0 && !$maybeState ) {
3058 // Save state without $ch. We want to *hit* the first
3059 // display char (to get tags) but not *use* it if truncating.
3060 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3063 $entityState = 1; // entity found, (e.g. " ")
3065 $dispLen++
; // this char is displayed
3066 // Add the next $max display text chars after this in one swoop...
3067 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3068 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3069 $dispLen +
= $skipped;
3075 // Close the last tag if left unclosed by bad HTML
3076 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3077 while ( count( $openTags ) > 0 ) {
3078 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3084 * truncateHtml() helper function
3085 * like strcspn() but adds the skipped chars to $ret
3094 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3095 if ( $len === null ) {
3096 $len = -1; // -1 means "no limit" for strcspn
3097 } elseif ( $len < 0 ) {
3101 if ( $start < strlen( $text ) ) {
3102 $skipCount = strcspn( $text, $search, $start, $len );
3103 $ret .= substr( $text, $start, $skipCount );
3109 * truncateHtml() helper function
3110 * (a) push or pop $tag from $openTags as needed
3111 * (b) clear $tag value
3112 * @param &$tag string Current HTML tag name we are looking at
3113 * @param $tagType int (0-open tag, 1-close tag)
3114 * @param $lastCh char|string Character before the '>' that ended this tag
3115 * @param &$openTags array Open tag stack (not accounting for $tag)
3117 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3118 $tag = ltrim( $tag );
3120 if ( $tagType == 0 && $lastCh != '/' ) {
3121 $openTags[] = $tag; // tag opened (didn't close itself)
3122 } elseif ( $tagType == 1 ) {
3123 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3124 array_pop( $openTags ); // tag closed
3132 * Grammatical transformations, needed for inflected languages
3133 * Invoked by putting {{grammar:case|word}} in a message
3135 * @param $word string
3136 * @param $case string
3139 function convertGrammar( $word, $case ) {
3140 global $wgGrammarForms;
3141 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3142 return $wgGrammarForms[$this->getCode()][$case][$word];
3148 * Provides an alternative text depending on specified gender.
3149 * Usage {{gender:username|masculine|feminine|neutral}}.
3150 * username is optional, in which case the gender of current user is used,
3151 * but only in (some) interface messages; otherwise default gender is used.
3152 * If second or third parameter are not specified, masculine is used.
3153 * These details may be overriden per language.
3155 * @param $gender string
3156 * @param $forms array
3160 function gender( $gender, $forms ) {
3161 if ( !count( $forms ) ) {
3164 $forms = $this->preConvertPlural( $forms, 2 );
3165 if ( $gender === 'male' ) {
3168 if ( $gender === 'female' ) {
3171 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3175 * Plural form transformations, needed for some languages.
3176 * For example, there are 3 form of plural in Russian and Polish,
3177 * depending on "count mod 10". See [[w:Plural]]
3178 * For English it is pretty simple.
3180 * Invoked by putting {{plural:count|wordform1|wordform2}}
3181 * or {{plural:count|wordform1|wordform2|wordform3}}
3183 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3185 * @param $count Integer: non-localized number
3186 * @param $forms Array: different plural forms
3187 * @return string Correct form of plural for $count in this language
3189 function convertPlural( $count, $forms ) {
3190 if ( !count( $forms ) ) {
3193 $forms = $this->preConvertPlural( $forms, 2 );
3195 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3199 * Checks that convertPlural was given an array and pads it to requested
3200 * amount of forms by copying the last one.
3202 * @param $count Integer: How many forms should there be at least
3203 * @param $forms Array of forms given to convertPlural
3204 * @return array Padded array of forms or an exception if not an array
3206 protected function preConvertPlural( /* Array */ $forms, $count ) {
3207 while ( count( $forms ) < $count ) {
3208 $forms[] = $forms[count( $forms ) - 1];
3214 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3215 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3216 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3217 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3220 * @param $str String: the validated block duration in English
3221 * @return Somehow translated block duration
3222 * @see LanguageFi.php for example implementation
3224 function translateBlockExpiry( $str ) {
3225 $duration = SpecialBlock
::getSuggestedDurations( $this );
3226 foreach ( $duration as $show => $value ) {
3227 if ( strcmp( $str, $value ) == 0 ) {
3228 return htmlspecialchars( trim( $show ) );
3232 // Since usually only infinite or indefinite is only on list, so try
3233 // equivalents if still here.
3234 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3235 if ( in_array( $str, $indefs ) ) {
3236 foreach ( $indefs as $val ) {
3237 $show = array_search( $val, $duration, true );
3238 if ( $show !== false ) {
3239 return htmlspecialchars( trim( $show ) );
3243 // If all else fails, return the original string.
3248 * languages like Chinese need to be segmented in order for the diff
3251 * @param $text String
3254 public function segmentForDiff( $text ) {
3259 * and unsegment to show the result
3261 * @param $text String
3264 public function unsegmentForDiff( $text ) {
3269 * Return the LanguageConverter used in the Language
3270 * @return LanguageConverter
3272 public function getConverter() {
3273 return $this->mConverter
;
3277 * convert text to all supported variants
3279 * @param $text string
3282 public function autoConvertToAllVariants( $text ) {
3283 return $this->mConverter
->autoConvertToAllVariants( $text );
3287 * convert text to different variants of a language.
3289 * @param $text string
3292 public function convert( $text ) {
3293 return $this->mConverter
->convert( $text );
3297 * Convert a Title object to a string in the preferred variant
3299 * @param $title Title
3302 public function convertTitle( $title ) {
3303 return $this->mConverter
->convertTitle( $title );
3307 * Check if this is a language with variants
3311 public function hasVariants() {
3312 return sizeof( $this->getVariants() ) > 1;
3316 * Check if the language has the specific variant
3317 * @param $variant string
3320 public function hasVariant( $variant ) {
3321 return (bool)$this->mConverter
->validateVariant( $variant );
3325 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3327 * @param $text string
3330 public function armourMath( $text ) {
3331 return $this->mConverter
->armourMath( $text );
3335 * Perform output conversion on a string, and encode for safe HTML output.
3336 * @param $text String text to be converted
3337 * @param $isTitle Bool whether this conversion is for the article title
3339 * @todo this should get integrated somewhere sane
3341 public function convertHtml( $text, $isTitle = false ) {
3342 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3346 * @param $key string
3349 public function convertCategoryKey( $key ) {
3350 return $this->mConverter
->convertCategoryKey( $key );
3354 * Get the list of variants supported by this language
3355 * see sample implementation in LanguageZh.php
3357 * @return array an array of language codes
3359 public function getVariants() {
3360 return $this->mConverter
->getVariants();
3366 public function getPreferredVariant() {
3367 return $this->mConverter
->getPreferredVariant();
3373 public function getDefaultVariant() {
3374 return $this->mConverter
->getDefaultVariant();
3380 public function getURLVariant() {
3381 return $this->mConverter
->getURLVariant();
3385 * If a language supports multiple variants, it is
3386 * possible that non-existing link in one variant
3387 * actually exists in another variant. this function
3388 * tries to find it. See e.g. LanguageZh.php
3390 * @param $link String: the name of the link
3391 * @param $nt Mixed: the title object of the link
3392 * @param $ignoreOtherCond Boolean: to disable other conditions when
3393 * we need to transclude a template or update a category's link
3394 * @return null the input parameters may be modified upon return
3396 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3397 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3401 * If a language supports multiple variants, converts text
3402 * into an array of all possible variants of the text:
3403 * 'variant' => text in that variant
3405 * @deprecated since 1.17 Use autoConvertToAllVariants()
3407 * @param $text string
3411 public function convertLinkToAllVariants( $text ) {
3412 return $this->mConverter
->convertLinkToAllVariants( $text );
3416 * returns language specific options used by User::getPageRenderHash()
3417 * for example, the preferred language variant
3421 function getExtraHashOptions() {
3422 return $this->mConverter
->getExtraHashOptions();
3426 * For languages that support multiple variants, the title of an
3427 * article may be displayed differently in different variants. this
3428 * function returns the apporiate title defined in the body of the article.
3432 public function getParsedTitle() {
3433 return $this->mConverter
->getParsedTitle();
3437 * Enclose a string with the "no conversion" tag. This is used by
3438 * various functions in the Parser
3440 * @param $text String: text to be tagged for no conversion
3441 * @param $noParse bool
3442 * @return string the tagged text
3444 public function markNoConversion( $text, $noParse = false ) {
3445 return $this->mConverter
->markNoConversion( $text, $noParse );
3449 * A regular expression to match legal word-trailing characters
3450 * which should be merged onto a link of the form [[foo]]bar.
3454 public function linkTrail() {
3455 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3461 function getLangObj() {
3466 * Get the RFC 3066 code for this language object
3470 public function getCode() {
3471 return $this->mCode
;
3475 * Get the code in Bcp47 format which we can use
3476 * inside of html lang="" tags.
3480 public function getHtmlCode() {
3481 if ( is_null( $this->mHtmlCode
) ) {
3482 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3484 return $this->mHtmlCode
;
3488 * @param $code string
3490 public function setCode( $code ) {
3491 $this->mCode
= $code;
3492 // Ensure we don't leave an incorrect html code lying around
3493 $this->mHtmlCode
= null;
3497 * Get the name of a file for a certain language code
3498 * @param $prefix string Prepend this to the filename
3499 * @param $code string Language code
3500 * @param $suffix string Append this to the filename
3501 * @return string $prefix . $mangledCode . $suffix
3503 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3504 // Protect against path traversal
3505 if ( !Language
::isValidCode( $code )
3506 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3508 throw new MWException( "Invalid language code \"$code\"" );
3511 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3515 * Get the language code from a file name. Inverse of getFileName()
3516 * @param $filename string $prefix . $languageCode . $suffix
3517 * @param $prefix string Prefix before the language code
3518 * @param $suffix string Suffix after the language code
3519 * @return string Language code, or false if $prefix or $suffix isn't found
3521 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3523 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3524 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3525 if ( !count( $m ) ) {
3528 return str_replace( '_', '-', strtolower( $m[1] ) );
3532 * @param $code string
3535 public static function getMessagesFileName( $code ) {
3537 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3538 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3543 * @param $code string
3546 public static function getClassFileName( $code ) {
3548 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3552 * Get the first fallback for a given language.
3554 * @param $code string
3556 * @return false|string
3558 public static function getFallbackFor( $code ) {
3559 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3562 $fallbacks = self
::getFallbacksFor( $code );
3563 $first = array_shift( $fallbacks );
3569 * Get the ordered list of fallback languages.
3572 * @param $code string Language code
3575 public static function getFallbacksFor( $code ) {
3576 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3579 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3580 $v = array_map( 'trim', explode( ',', $v ) );
3581 if ( $v[count( $v ) - 1] !== 'en' ) {
3589 * Get all messages for a given language
3590 * WARNING: this may take a long time. If you just need all message *keys*
3591 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3593 * @param $code string
3597 public static function getMessagesFor( $code ) {
3598 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3602 * Get a message for a given language
3604 * @param $key string
3605 * @param $code string
3609 public static function getMessageFor( $key, $code ) {
3610 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3614 * Get all message keys for a given language. This is a faster alternative to
3615 * array_keys( Language::getMessagesFor( $code ) )
3618 * @param $code string Language code
3619 * @return array of message keys (strings)
3621 public static function getMessageKeysFor( $code ) {
3622 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3629 function fixVariableInNamespace( $talk ) {
3630 if ( strpos( $talk, '$1' ) === false ) {
3634 global $wgMetaNamespace;
3635 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3637 # Allow grammar transformations
3638 # Allowing full message-style parsing would make simple requests
3639 # such as action=raw much more expensive than they need to be.
3640 # This will hopefully cover most cases.
3641 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3642 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3643 return str_replace( ' ', '_', $talk );
3650 function replaceGrammarInNamespace( $m ) {
3651 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3655 * @throws MWException
3658 static function getCaseMaps() {
3659 static $wikiUpperChars, $wikiLowerChars;
3660 if ( isset( $wikiUpperChars ) ) {
3661 return array( $wikiUpperChars, $wikiLowerChars );
3664 wfProfileIn( __METHOD__
);
3665 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3666 if ( $arr === false ) {
3667 throw new MWException(
3668 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3670 $wikiUpperChars = $arr['wikiUpperChars'];
3671 $wikiLowerChars = $arr['wikiLowerChars'];
3672 wfProfileOut( __METHOD__
);
3673 return array( $wikiUpperChars, $wikiLowerChars );
3677 * Decode an expiry (block, protection, etc) which has come from the DB
3679 * @param $expiry String: Database expiry String
3680 * @param $format Bool|Int true to process using language functions, or TS_ constant
3681 * to return the expiry in a given timestamp
3684 public function formatExpiry( $expiry, $format = true ) {
3685 static $infinity, $infinityMsg;
3686 if ( $infinity === null ) {
3687 $infinityMsg = wfMessage( 'infiniteblock' );
3688 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3691 if ( $expiry == '' ||
$expiry == $infinity ) {
3692 return $format === true
3696 return $format === true
3697 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3698 : wfTimestamp( $format, $expiry );
3704 * @param $seconds int|float
3705 * @param $format Array Optional
3706 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3707 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3708 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3709 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3712 function formatTimePeriod( $seconds, $format = array() ) {
3713 if ( !is_array( $format ) ) {
3714 $format = array( 'avoid' => $format ); // For backwards compatibility
3716 if ( !isset( $format['avoid'] ) ) {
3717 $format['avoid'] = false;
3719 if ( !isset( $format['noabbrevs' ] ) ) {
3720 $format['noabbrevs'] = false;
3722 $secondsMsg = wfMessage(
3723 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3724 $minutesMsg = wfMessage(
3725 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3726 $hoursMsg = wfMessage(
3727 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3728 $daysMsg = wfMessage(
3729 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3731 if ( round( $seconds * 10 ) < 100 ) {
3732 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3733 $s = $secondsMsg->params( $s )->text();
3734 } elseif ( round( $seconds ) < 60 ) {
3735 $s = $this->formatNum( round( $seconds ) );
3736 $s = $secondsMsg->params( $s )->text();
3737 } elseif ( round( $seconds ) < 3600 ) {
3738 $minutes = floor( $seconds / 60 );
3739 $secondsPart = round( fmod( $seconds, 60 ) );
3740 if ( $secondsPart == 60 ) {
3744 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3746 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3747 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3748 $hours = floor( $seconds / 3600 );
3749 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3750 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3751 if ( $secondsPart == 60 ) {
3755 if ( $minutes == 60 ) {
3759 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3761 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3762 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3763 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3766 $days = floor( $seconds / 86400 );
3767 if ( $format['avoid'] === 'avoidminutes' ) {
3768 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3769 if ( $hours == 24 ) {
3773 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3775 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3776 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3777 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3778 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3779 if ( $minutes == 60 ) {
3783 if ( $hours == 24 ) {
3787 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3789 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3791 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3793 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3795 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3805 function formatBitrate( $bps ) {
3806 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3808 return $this->formatNum( $bps ) . $units[0];
3810 $unitIndex = (int)floor( log10( $bps ) / 3 );
3811 $mantissa = $bps / pow( 1000, $unitIndex );
3812 if ( $mantissa < 10 ) {
3813 $mantissa = round( $mantissa, 1 );
3815 $mantissa = round( $mantissa );
3817 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3821 * Format a size in bytes for output, using an appropriate
3822 * unit (B, KB, MB or GB) according to the magnitude in question
3824 * @param $size int Size to format
3825 * @return string Plain text (not HTML)
3827 function formatSize( $size ) {
3828 // For small sizes no decimal places necessary
3830 if ( $size > 1024 ) {
3831 $size = $size / 1024;
3832 if ( $size > 1024 ) {
3833 $size = $size / 1024;
3834 // For MB and bigger two decimal places are smarter
3836 if ( $size > 1024 ) {
3837 $size = $size / 1024;
3838 $msg = 'size-gigabytes';
3840 $msg = 'size-megabytes';
3843 $msg = 'size-kilobytes';
3846 $msg = 'size-bytes';
3848 $size = round( $size, $round );
3849 $text = $this->getMessageFromDB( $msg );
3850 return str_replace( '$1', $this->formatNum( $size ), $text );
3854 * Make a list item, used by various special pages
3856 * @param $page String Page link
3857 * @param $details String Text between brackets
3858 * @param $oppositedm Boolean Add the direction mark opposite to your
3859 * language, to display text properly
3862 function specialList( $page, $details, $oppositedm = true ) {
3863 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3864 $this->getDirMark();
3865 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3866 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3867 return $page . $details;
3871 * Generate (prev x| next x) (20|50|100...) type links for paging
3873 * @param $title Title object to link
3874 * @param $offset Integer offset parameter
3875 * @param $limit Integer limit parameter
3876 * @param $query String optional URL query parameter string
3877 * @param $atend Bool optional param for specified if this is the last page
3880 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3881 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3883 # Make 'previous' link
3884 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3886 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3887 $query, $prev, 'prevn-title', 'mw-prevlink' );
3889 $plink = htmlspecialchars( $prev );
3893 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3895 $nlink = htmlspecialchars( $next );
3897 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3898 $query, $next, 'prevn-title', 'mw-nextlink' );
3901 # Make links to set number of items per page
3902 $numLinks = array();
3903 foreach( array( 20, 50, 100, 250, 500 ) as $num ) {
3904 $numLinks[] = $this->numLink( $title, $offset, $num,
3905 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3908 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3909 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
3913 * Helper function for viewPrevNext() that generates links
3915 * @param $title Title object to link
3916 * @param $offset Integer offset parameter
3917 * @param $limit Integer limit parameter
3918 * @param $query Array extra query parameters
3919 * @param $link String text to use for the link; will be escaped
3920 * @param $tooltipMsg String name of the message to use as tooltip
3921 * @param $class String value of the "class" attribute of the link
3922 * @return String HTML fragment
3924 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
3925 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
3926 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3927 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
3928 'title' => $tooltip, 'class' => $class ), $link );
3932 * Get the conversion rule title, if any.
3936 public function getConvRuleTitle() {
3937 return $this->mConverter
->getConvRuleTitle();