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;
65 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
66 var $dateFormatStrings = array();
67 var $mExtendedSpecialPageAliases;
70 * ReplacementArray object caches
72 var $transformData = array();
75 * @var LocalisationCache
77 static public $dataCache;
79 static public $mLangObjCache = array();
81 static public $mWeekdayMsgs = array(
82 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
86 static public $mWeekdayAbbrevMsgs = array(
87 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
90 static public $mMonthMsgs = array(
91 'january', 'february', 'march', 'april', 'may_long', 'june',
92 'july', 'august', 'september', 'october', 'november',
95 static public $mMonthGenMsgs = array(
96 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
97 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
100 static public $mMonthAbbrevMsgs = array(
101 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
102 'sep', 'oct', 'nov', 'dec'
105 static public $mIranianCalendarMonthMsgs = array(
106 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
107 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
108 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
109 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
112 static public $mHebrewCalendarMonthMsgs = array(
113 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
114 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
115 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
116 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
117 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
120 static public $mHebrewCalendarMonthGenMsgs = array(
121 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
122 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
123 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
124 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
125 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
128 static public $mHijriCalendarMonthMsgs = array(
129 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
130 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
131 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
132 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
136 * Get a cached language object for a given language code
137 * @param $code String
140 static function factory( $code ) {
141 if ( !isset( self
::$mLangObjCache[$code] ) ) {
142 if ( count( self
::$mLangObjCache ) > 10 ) {
143 // Don't keep a billion objects around, that's stupid.
144 self
::$mLangObjCache = array();
146 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
148 return self
::$mLangObjCache[$code];
152 * Create a language object for a given language code
153 * @param $code String
156 protected static function newFromCode( $code ) {
157 // Protect against path traversal below
158 if ( !Language
::isValidCode( $code )
159 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
161 throw new MWException( "Invalid language code \"$code\"" );
164 if ( !Language
::isValidBuiltInCode( $code ) ) {
165 // It's not possible to customise this code with class files, so
166 // just return a Language object. This is to support uselang= hacks.
167 $lang = new Language
;
168 $lang->setCode( $code );
172 // Check if there is a language class for the code
173 $class = self
::classFromCode( $code );
174 self
::preloadLanguageClass( $class );
175 if ( MWInit
::classExists( $class ) ) {
180 // Keep trying the fallback list until we find an existing class
181 $fallbacks = Language
::getFallbacksFor( $code );
182 foreach ( $fallbacks as $fallbackCode ) {
183 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
184 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
187 $class = self
::classFromCode( $fallbackCode );
188 self
::preloadLanguageClass( $class );
189 if ( MWInit
::classExists( $class ) ) {
190 $lang = Language
::newFromCode( $fallbackCode );
191 $lang->setCode( $code );
196 throw new MWException( "Invalid fallback sequence for language '$code'" );
200 * Returns true if a language code string is of a valid form, whether or
201 * not it exists. This includes codes which are used solely for
202 * customisation via the MediaWiki namespace.
204 * @param $code string
208 public static function isValidCode( $code ) {
210 strcspn( $code, ":/\\\000" ) === strlen( $code )
211 && !preg_match( Title
::getTitleInvalidRegex(), $code );
215 * Returns true if a language code is of a valid form for the purposes of
216 * internal customisation of MediaWiki, via Messages*.php.
218 * @param $code string
223 public static function isValidBuiltInCode( $code ) {
224 return preg_match( '/^[a-z0-9-]+$/i', $code );
229 * @return String Name of the language class
231 public static function classFromCode( $code ) {
232 if ( $code == 'en' ) {
235 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
240 * Includes language class files
242 * @param $class string Name of the language class
244 public static function preloadLanguageClass( $class ) {
247 if ( $class === 'Language' ) {
251 if ( !defined( 'MW_COMPILED' ) ) {
252 // Preload base classes to work around APC/PHP5 bug
253 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
254 include_once( "$IP/languages/classes/$class.deps.php" );
256 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
257 include_once( "$IP/languages/classes/$class.php" );
263 * Get the LocalisationCache instance
265 * @return LocalisationCache
267 public static function getLocalisationCache() {
268 if ( is_null( self
::$dataCache ) ) {
269 global $wgLocalisationCacheConf;
270 $class = $wgLocalisationCacheConf['class'];
271 self
::$dataCache = new $class( $wgLocalisationCacheConf );
273 return self
::$dataCache;
276 function __construct() {
277 $this->mConverter
= new FakeConverter( $this );
278 // Set the code to the name of the descendant
279 if ( get_class( $this ) == 'Language' ) {
282 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
284 self
::getLocalisationCache();
288 * Reduce memory usage
290 function __destruct() {
291 foreach ( $this as $name => $value ) {
292 unset( $this->$name );
297 * Hook which will be called if this is the content language.
298 * Descendants can use this to register hook functions or modify globals
300 function initContLang() { }
303 * Same as getFallbacksFor for current language.
305 * @deprecated in 1.19
307 function getFallbackLanguageCode() {
308 wfDeprecated( __METHOD__
);
309 return self
::getFallbackFor( $this->mCode
);
316 function getFallbackLanguages() {
317 return self
::getFallbacksFor( $this->mCode
);
321 * Exports $wgBookstoreListEn
324 function getBookstoreList() {
325 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
331 function getNamespaces() {
332 if ( is_null( $this->namespaceNames
) ) {
333 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
335 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
336 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
338 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
340 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
341 if ( $wgMetaNamespaceTalk ) {
342 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
344 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
345 $this->namespaceNames
[NS_PROJECT_TALK
] =
346 $this->fixVariableInNamespace( $talk );
349 # Sometimes a language will be localised but not actually exist on this wiki.
350 foreach ( $this->namespaceNames
as $key => $text ) {
351 if ( !isset( $validNamespaces[$key] ) ) {
352 unset( $this->namespaceNames
[$key] );
356 # The above mixing may leave namespaces out of canonical order.
357 # Re-order by namespace ID number...
358 ksort( $this->namespaceNames
);
360 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
362 return $this->namespaceNames
;
366 * A convenience function that returns the same thing as
367 * getNamespaces() except with the array values changed to ' '
368 * where it found '_', useful for producing output to be displayed
369 * e.g. in <select> forms.
373 function getFormattedNamespaces() {
374 $ns = $this->getNamespaces();
375 foreach ( $ns as $k => $v ) {
376 $ns[$k] = strtr( $v, '_', ' ' );
382 * Get a namespace value by key
384 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
385 * echo $mw_ns; // prints 'MediaWiki'
388 * @param $index Int: the array key of the namespace to return
389 * @return mixed, string if the namespace value exists, otherwise false
391 function getNsText( $index ) {
392 $ns = $this->getNamespaces();
393 return isset( $ns[$index] ) ?
$ns[$index] : false;
397 * A convenience function that returns the same thing as
398 * getNsText() except with '_' changed to ' ', useful for
401 * @param $index string
405 function getFormattedNsText( $index ) {
406 $ns = $this->getNsText( $index );
407 return strtr( $ns, '_', ' ' );
411 * Returns gender-dependent namespace alias if available.
412 * @param $index Int: namespace index
413 * @param $gender String: gender key (male, female... )
417 function getGenderNsText( $index, $gender ) {
418 global $wgExtraGenderNamespaces;
420 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
421 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
425 * Whether this language makes distinguishes genders for example in
430 function needsGenderDistinction() {
431 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
432 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
433 // $wgExtraGenderNamespaces overrides everything
435 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
436 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
437 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
440 // Check what is in i18n files
441 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
442 return count( $aliases ) > 0;
447 * Get a namespace key by value, case insensitive.
448 * Only matches namespace names for the current language, not the
449 * canonical ones defined in Namespace.php.
451 * @param $text String
452 * @return mixed An integer if $text is a valid value otherwise false
454 function getLocalNsIndex( $text ) {
455 $lctext = $this->lc( $text );
456 $ids = $this->getNamespaceIds();
457 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
463 function getNamespaceAliases() {
464 if ( is_null( $this->namespaceAliases
) ) {
465 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
469 foreach ( $aliases as $name => $index ) {
470 if ( $index === NS_PROJECT_TALK
) {
471 unset( $aliases[$name] );
472 $name = $this->fixVariableInNamespace( $name );
473 $aliases[$name] = $index;
478 global $wgExtraGenderNamespaces;
479 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
480 foreach ( $genders as $index => $forms ) {
481 foreach ( $forms as $alias ) {
482 $aliases[$alias] = $index;
486 $this->namespaceAliases
= $aliases;
488 return $this->namespaceAliases
;
494 function getNamespaceIds() {
495 if ( is_null( $this->mNamespaceIds
) ) {
496 global $wgNamespaceAliases;
497 # Put namespace names and aliases into a hashtable.
498 # If this is too slow, then we should arrange it so that it is done
499 # before caching. The catch is that at pre-cache time, the above
500 # class-specific fixup hasn't been done.
501 $this->mNamespaceIds
= array();
502 foreach ( $this->getNamespaces() as $index => $name ) {
503 $this->mNamespaceIds
[$this->lc( $name )] = $index;
505 foreach ( $this->getNamespaceAliases() as $name => $index ) {
506 $this->mNamespaceIds
[$this->lc( $name )] = $index;
508 if ( $wgNamespaceAliases ) {
509 foreach ( $wgNamespaceAliases as $name => $index ) {
510 $this->mNamespaceIds
[$this->lc( $name )] = $index;
514 return $this->mNamespaceIds
;
518 * Get a namespace key by value, case insensitive. Canonical namespace
519 * names override custom ones defined for the current language.
521 * @param $text String
522 * @return mixed An integer if $text is a valid value otherwise false
524 function getNsIndex( $text ) {
525 $lctext = $this->lc( $text );
526 $ns = MWNamespace
::getCanonicalIndex( $lctext );
527 if ( $ns !== null ) {
530 $ids = $this->getNamespaceIds();
531 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
535 * short names for language variants used for language conversion links.
537 * @param $code String
538 * @param $usemsg bool Use the "variantname-xyz" message if it exists
541 function getVariantname( $code, $usemsg = true ) {
542 $msg = "variantname-$code";
543 list( $rootCode ) = explode( '-', $code );
544 if ( $usemsg && wfMessage( $msg )->exists() ) {
545 return $this->getMessageFromDB( $msg );
547 $name = self
::getLanguageName( $code );
549 return $name; # if it's defined as a language name, show that
551 # otherwise, output the language code
557 * @param $name string
560 function specialPage( $name ) {
561 $aliases = $this->getSpecialPageAliases();
562 if ( isset( $aliases[$name][0] ) ) {
563 $name = $aliases[$name][0];
565 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
571 function getQuickbarSettings() {
573 $this->getMessage( 'qbsettings-none' ),
574 $this->getMessage( 'qbsettings-fixedleft' ),
575 $this->getMessage( 'qbsettings-fixedright' ),
576 $this->getMessage( 'qbsettings-floatingleft' ),
577 $this->getMessage( 'qbsettings-floatingright' ),
578 $this->getMessage( 'qbsettings-directionality' )
585 function getDatePreferences() {
586 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
592 function getDateFormats() {
593 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
597 * @return array|string
599 function getDefaultDateFormat() {
600 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
601 if ( $df === 'dmy or mdy' ) {
602 global $wgAmericanDates;
603 return $wgAmericanDates ?
'mdy' : 'dmy';
612 function getDatePreferenceMigrationMap() {
613 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
620 function getImageFile( $image ) {
621 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
627 function getExtraUserToggles() {
628 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
635 function getUserToggle( $tog ) {
636 return $this->getMessageFromDB( "tog-$tog" );
640 * Get language names, indexed by code.
641 * If $customisedOnly is true, only returns codes with a messages file
643 * @param $customisedOnly bool
647 public static function getLanguageNames( $customisedOnly = false ) {
648 global $wgExtraLanguageNames;
649 static $coreLanguageNames;
651 if ( $coreLanguageNames === null ) {
652 include( MWInit
::compiledPath( 'languages/Names.php' ) );
655 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
656 if ( !$customisedOnly ) {
662 $dir = opendir( "$IP/languages/messages" );
663 while ( false !== ( $file = readdir( $dir ) ) ) {
664 $code = self
::getCodeFromFileName( $file, 'Messages' );
665 if ( $code && isset( $allNames[$code] ) ) {
666 $names[$code] = $allNames[$code];
674 * Get translated language names. This is done on best effort and
675 * by default this is exactly the same as Language::getLanguageNames.
676 * The CLDR extension provides translated names.
677 * @param $code String Language code.
678 * @return Array language code => language name
681 public static function getTranslatedLanguageNames( $code ) {
683 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
685 foreach ( self
::getLanguageNames() as $code => $name ) {
686 if ( !isset( $names[$code] ) ) $names[$code] = $name;
693 * Get a message from the MediaWiki namespace.
695 * @param $msg String: message name
698 function getMessageFromDB( $msg ) {
699 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
703 * @param $code string
706 function getLanguageName( $code ) {
707 $names = self
::getLanguageNames();
708 if ( !array_key_exists( $code, $names ) ) {
711 return $names[$code];
718 function getMonthName( $key ) {
719 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
725 function getMonthNamesArray() {
726 $monthNames = array( '' );
727 for ( $i = 1; $i < 13; $i++
) {
728 $monthNames[] = $this->getMonthName( $i );
737 function getMonthNameGen( $key ) {
738 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
745 function getMonthAbbreviation( $key ) {
746 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
752 function getMonthAbbreviationsArray() {
753 $monthNames = array( '' );
754 for ( $i = 1; $i < 13; $i++
) {
755 $monthNames[] = $this->getMonthAbbreviation( $i );
764 function getWeekdayName( $key ) {
765 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
772 function getWeekdayAbbreviation( $key ) {
773 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
780 function getIranianCalendarMonthName( $key ) {
781 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
788 function getHebrewCalendarMonthName( $key ) {
789 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
796 function getHebrewCalendarMonthNameGen( $key ) {
797 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
804 function getHijriCalendarMonthName( $key ) {
805 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
809 * This is a workalike of PHP's date() function, but with better
810 * internationalisation, a reduced set of format characters, and a better
813 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
814 * PHP manual for definitions. There are a number of extensions, which
817 * xn Do not translate digits of the next numeric format character
818 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
819 * xr Use roman numerals for the next numeric format character
820 * xh Use hebrew numerals for the next numeric format character
822 * xg Genitive month name
824 * xij j (day number) in Iranian calendar
825 * xiF F (month name) in Iranian calendar
826 * xin n (month number) in Iranian calendar
827 * xiY Y (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 );
1090 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1093 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1096 $h = substr( $ts, 8, 2 );
1097 $num = $h %
12 ?
$h %
12 : 12;
1100 $num = intval( substr( $ts, 8, 2 ) );
1103 $h = substr( $ts, 8, 2 );
1104 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1107 $num = substr( $ts, 8, 2 );
1110 $num = substr( $ts, 10, 2 );
1113 $num = substr( $ts, 12, 2 );
1117 $unix = wfTimestamp( TS_UNIX
, $ts );
1119 $s .= gmdate( 'c', $unix );
1123 $unix = wfTimestamp( TS_UNIX
, $ts );
1125 $s .= gmdate( 'r', $unix );
1129 $unix = wfTimestamp( TS_UNIX
, $ts );
1134 # Backslash escaping
1135 if ( $p < strlen( $format ) - 1 ) {
1136 $s .= $format[++
$p];
1143 if ( $p < strlen( $format ) - 1 ) {
1144 $endQuote = strpos( $format, '"', $p +
1 );
1145 if ( $endQuote === false ) {
1146 # No terminating quote, assume literal "
1149 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1153 # Quote at end of string, assume literal "
1160 if ( $num !== false ) {
1161 if ( $rawToggle ||
$raw ) {
1164 } elseif ( $roman ) {
1165 $s .= self
::romanNumeral( $num );
1167 } elseif ( $hebrewNum ) {
1168 $s .= self
::hebrewNumeral( $num );
1171 $s .= $this->formatNum( $num, true );
1178 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1179 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1182 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1183 * Gregorian dates to Iranian dates. Originally written in C, it
1184 * is released under the terms of GNU Lesser General Public
1185 * License. Conversion to PHP was performed by Niklas Laxström.
1187 * Link: http://www.farsiweb.info/jalali/jalali.c
1193 private static function tsToIranian( $ts ) {
1194 $gy = substr( $ts, 0, 4 ) -1600;
1195 $gm = substr( $ts, 4, 2 ) -1;
1196 $gd = substr( $ts, 6, 2 ) -1;
1198 # Days passed from the beginning (including leap years)
1200 +
floor( ( $gy +
3 ) / 4 )
1201 - floor( ( $gy +
99 ) / 100 )
1202 +
floor( ( $gy +
399 ) / 400 );
1204 // Add days of the past months of this year
1205 for ( $i = 0; $i < $gm; $i++
) {
1206 $gDayNo +
= self
::$GREG_DAYS[$i];
1210 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1214 // Days passed in current month
1215 $gDayNo +
= (int)$gd;
1217 $jDayNo = $gDayNo - 79;
1219 $jNp = floor( $jDayNo / 12053 );
1222 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1225 if ( $jDayNo >= 366 ) {
1226 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1227 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1230 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1231 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1237 return array( $jy, $jm, $jd );
1241 * Converting Gregorian dates to Hijri dates.
1243 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1245 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1251 private static function tsToHijri( $ts ) {
1252 $year = substr( $ts, 0, 4 );
1253 $month = substr( $ts, 4, 2 );
1254 $day = substr( $ts, 6, 2 );
1262 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1263 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1266 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1267 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1268 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1271 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1272 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1275 $zl = $zjd -1948440 +
10632;
1276 $zn = (int)( ( $zl - 1 ) / 10631 );
1277 $zl = $zl - 10631 * $zn +
354;
1278 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1279 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1280 $zm = (int)( ( 24 * $zl ) / 709 );
1281 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1282 $zy = 30 * $zn +
$zj - 30;
1284 return array( $zy, $zm, $zd );
1288 * Converting Gregorian dates to Hebrew dates.
1290 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1291 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1292 * to translate the relevant functions into PHP and release them under
1295 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1296 * and Adar II is 14. In a non-leap year, Adar is 6.
1302 private static function tsToHebrew( $ts ) {
1304 $year = substr( $ts, 0, 4 );
1305 $month = substr( $ts, 4, 2 );
1306 $day = substr( $ts, 6, 2 );
1308 # Calculate Hebrew year
1309 $hebrewYear = $year +
3760;
1311 # Month number when September = 1, August = 12
1313 if ( $month > 12 ) {
1320 # Calculate day of year from 1 September
1322 for ( $i = 1; $i < $month; $i++
) {
1326 # Check if the year is leap
1327 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1330 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1337 # Calculate the start of the Hebrew year
1338 $start = self
::hebrewYearStart( $hebrewYear );
1340 # Calculate next year's start
1341 if ( $dayOfYear <= $start ) {
1342 # Day is before the start of the year - it is the previous year
1344 $nextStart = $start;
1348 # Add days since previous year's 1 September
1350 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1354 # Start of the new (previous) year
1355 $start = self
::hebrewYearStart( $hebrewYear );
1358 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1361 # Calculate Hebrew day of year
1362 $hebrewDayOfYear = $dayOfYear - $start;
1364 # Difference between year's days
1365 $diff = $nextStart - $start;
1366 # Add 12 (or 13 for leap years) days to ignore the difference between
1367 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1368 # difference is only about the year type
1369 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1375 # Check the year pattern, and is leap year
1376 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1377 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1378 # and non-leap years
1379 $yearPattern = $diff %
30;
1380 # Check if leap year
1381 $isLeap = $diff >= 30;
1383 # Calculate day in the month from number of day in the Hebrew year
1384 # Don't check Adar - if the day is not in Adar, we will stop before;
1385 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1386 $hebrewDay = $hebrewDayOfYear;
1389 while ( $hebrewMonth <= 12 ) {
1390 # Calculate days in this month
1391 if ( $isLeap && $hebrewMonth == 6 ) {
1392 # Adar in a leap year
1394 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1396 if ( $hebrewDay <= $days ) {
1400 # Subtract the days of Adar I
1401 $hebrewDay -= $days;
1404 if ( $hebrewDay <= $days ) {
1410 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1411 # Cheshvan in a complete year (otherwise as the rule below)
1413 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1414 # Kislev in an incomplete year (otherwise as the rule below)
1417 # Odd months have 30 days, even have 29
1418 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1420 if ( $hebrewDay <= $days ) {
1421 # In the current month
1424 # Subtract the days of the current month
1425 $hebrewDay -= $days;
1426 # Try in the next month
1431 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1435 * This calculates the Hebrew year start, as days since 1 September.
1436 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1437 * Used for Hebrew date.
1443 private static function hebrewYearStart( $year ) {
1444 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1445 $b = intval( ( $year - 1 ) %
4 );
1446 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1450 $Mar = intval( $m );
1456 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1457 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1459 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1461 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1465 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1470 * Algorithm to convert Gregorian dates to Thai solar dates,
1471 * Minguo dates or Minguo dates.
1473 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1474 * http://en.wikipedia.org/wiki/Minguo_calendar
1475 * http://en.wikipedia.org/wiki/Japanese_era_name
1477 * @param $ts String: 14-character timestamp
1478 * @param $cName String: calender name
1479 * @return Array: converted year, month, day
1481 private static function tsToYear( $ts, $cName ) {
1482 $gy = substr( $ts, 0, 4 );
1483 $gm = substr( $ts, 4, 2 );
1484 $gd = substr( $ts, 6, 2 );
1486 if ( !strcmp( $cName, 'thai' ) ) {
1488 # Add 543 years to the Gregorian calendar
1489 # Months and days are identical
1490 $gy_offset = $gy +
543;
1491 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1493 # Deduct 1911 years from the Gregorian calendar
1494 # Months and days are identical
1495 $gy_offset = $gy - 1911;
1496 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1497 # Nengō dates up to Meiji period
1498 # Deduct years from the Gregorian calendar
1499 # depending on the nengo periods
1500 # Months and days are identical
1501 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1503 $gy_gannen = $gy - 1868 +
1;
1504 $gy_offset = $gy_gannen;
1505 if ( $gy_gannen == 1 ) {
1508 $gy_offset = '明治' . $gy_offset;
1510 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1511 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1512 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1513 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1514 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1518 $gy_gannen = $gy - 1912 +
1;
1519 $gy_offset = $gy_gannen;
1520 if ( $gy_gannen == 1 ) {
1523 $gy_offset = '大正' . $gy_offset;
1525 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1526 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1527 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1531 $gy_gannen = $gy - 1926 +
1;
1532 $gy_offset = $gy_gannen;
1533 if ( $gy_gannen == 1 ) {
1536 $gy_offset = '昭和' . $gy_offset;
1539 $gy_gannen = $gy - 1989 +
1;
1540 $gy_offset = $gy_gannen;
1541 if ( $gy_gannen == 1 ) {
1544 $gy_offset = '平成' . $gy_offset;
1550 return array( $gy_offset, $gm, $gd );
1554 * Roman number formatting up to 3000
1560 static function romanNumeral( $num ) {
1561 static $table = array(
1562 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1563 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1564 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1565 array( '', 'M', 'MM', 'MMM' )
1568 $num = intval( $num );
1569 if ( $num > 3000 ||
$num <= 0 ) {
1574 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1575 if ( $num >= $pow10 ) {
1576 $s .= $table[$i][(int)floor( $num / $pow10 )];
1578 $num = $num %
$pow10;
1584 * Hebrew Gematria number formatting up to 9999
1590 static function hebrewNumeral( $num ) {
1591 static $table = array(
1592 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1593 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1594 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1595 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1598 $num = intval( $num );
1599 if ( $num > 9999 ||
$num <= 0 ) {
1604 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1605 if ( $num >= $pow10 ) {
1606 if ( $num == 15 ||
$num == 16 ) {
1607 $s .= $table[0][9] . $table[0][$num - 9];
1610 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1611 if ( $pow10 == 1000 ) {
1616 $num = $num %
$pow10;
1618 if ( strlen( $s ) == 2 ) {
1621 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1622 $str .= substr( $s, strlen( $s ) - 2, 2 );
1624 $start = substr( $str, 0, strlen( $str ) - 2 );
1625 $end = substr( $str, strlen( $str ) - 2 );
1628 $str = $start . 'ך';
1631 $str = $start . 'ם';
1634 $str = $start . 'ן';
1637 $str = $start . 'ף';
1640 $str = $start . 'ץ';
1647 * Used by date() and time() to adjust the time output.
1649 * @param $ts Int the time in date('YmdHis') format
1650 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1651 * get user timecorrection setting)
1654 function userAdjust( $ts, $tz = false ) {
1655 global $wgUser, $wgLocalTZoffset;
1657 if ( $tz === false ) {
1658 $tz = $wgUser->getOption( 'timecorrection' );
1661 $data = explode( '|', $tz, 3 );
1663 if ( $data[0] == 'ZoneInfo' ) {
1664 wfSuppressWarnings();
1665 $userTZ = timezone_open( $data[2] );
1666 wfRestoreWarnings();
1667 if ( $userTZ !== false ) {
1668 $date = date_create( $ts, timezone_open( 'UTC' ) );
1669 date_timezone_set( $date, $userTZ );
1670 $date = date_format( $date, 'YmdHis' );
1673 # Unrecognized timezone, default to 'Offset' with the stored offset.
1674 $data[0] = 'Offset';
1678 if ( $data[0] == 'System' ||
$tz == '' ) {
1679 # Global offset in minutes.
1680 if ( isset( $wgLocalTZoffset ) ) {
1681 $minDiff = $wgLocalTZoffset;
1683 } elseif ( $data[0] == 'Offset' ) {
1684 $minDiff = intval( $data[1] );
1686 $data = explode( ':', $tz );
1687 if ( count( $data ) == 2 ) {
1688 $data[0] = intval( $data[0] );
1689 $data[1] = intval( $data[1] );
1690 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1691 if ( $data[0] < 0 ) {
1692 $minDiff = -$minDiff;
1695 $minDiff = intval( $data[0] ) * 60;
1699 # No difference ? Return time unchanged
1700 if ( 0 == $minDiff ) {
1704 wfSuppressWarnings(); // E_STRICT system time bitching
1705 # Generate an adjusted date; take advantage of the fact that mktime
1706 # will normalize out-of-range values so we don't have to split $minDiff
1707 # into hours and minutes.
1709 (int)substr( $ts, 8, 2 ) ), # Hours
1710 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1711 (int)substr( $ts, 12, 2 ), # Seconds
1712 (int)substr( $ts, 4, 2 ), # Month
1713 (int)substr( $ts, 6, 2 ), # Day
1714 (int)substr( $ts, 0, 4 ) ); # Year
1716 $date = date( 'YmdHis', $t );
1717 wfRestoreWarnings();
1723 * This is meant to be used by time(), date(), and timeanddate() to get
1724 * the date preference they're supposed to use, it should be used in
1728 * function timeanddate([...], $format = true) {
1729 * $datePreference = $this->dateFormat($format);
1734 * @param $usePrefs Mixed: if true, the user's preference is used
1735 * if false, the site/language default is used
1736 * if int/string, assumed to be a format.
1739 function dateFormat( $usePrefs = true ) {
1742 if ( is_bool( $usePrefs ) ) {
1744 $datePreference = $wgUser->getDatePreference();
1746 $datePreference = (string)User
::getDefaultOption( 'date' );
1749 $datePreference = (string)$usePrefs;
1753 if ( $datePreference == '' ) {
1757 return $datePreference;
1761 * Get a format string for a given type and preference
1762 * @param $type string May be date, time or both
1763 * @param $pref string The format name as it appears in Messages*.php
1767 function getDateFormatString( $type, $pref ) {
1768 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1769 if ( $pref == 'default' ) {
1770 $pref = $this->getDefaultDateFormat();
1771 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1773 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1774 if ( is_null( $df ) ) {
1775 $pref = $this->getDefaultDateFormat();
1776 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1779 $this->dateFormatStrings
[$type][$pref] = $df;
1781 return $this->dateFormatStrings
[$type][$pref];
1785 * @param $ts Mixed: the time format which needs to be turned into a
1786 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1787 * @param $adj Bool: whether to adjust the time output according to the
1788 * user configured offset ($timecorrection)
1789 * @param $format Mixed: true to use user's date format preference
1790 * @param $timecorrection String|bool the time offset as returned by
1791 * validateTimeZone() in Special:Preferences
1794 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1795 $ts = wfTimestamp( TS_MW
, $ts );
1797 $ts = $this->userAdjust( $ts, $timecorrection );
1799 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1800 return $this->sprintfDate( $df, $ts );
1804 * @param $ts Mixed: the time format which needs to be turned into a
1805 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1806 * @param $adj Bool: whether to adjust the time output according to the
1807 * user configured offset ($timecorrection)
1808 * @param $format Mixed: true to use user's date format preference
1809 * @param $timecorrection String|bool the time offset as returned by
1810 * validateTimeZone() in Special:Preferences
1813 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1814 $ts = wfTimestamp( TS_MW
, $ts );
1816 $ts = $this->userAdjust( $ts, $timecorrection );
1818 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1819 return $this->sprintfDate( $df, $ts );
1823 * @param $ts Mixed: the time format which needs to be turned into a
1824 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1825 * @param $adj Bool: whether to adjust the time output according to the
1826 * user configured offset ($timecorrection)
1827 * @param $format Mixed: what format to return, if it's false output the
1828 * default one (default true)
1829 * @param $timecorrection String|bool the time offset as returned by
1830 * validateTimeZone() in Special:Preferences
1833 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1834 $ts = wfTimestamp( TS_MW
, $ts );
1836 $ts = $this->userAdjust( $ts, $timecorrection );
1838 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1839 return $this->sprintfDate( $df, $ts );
1843 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1845 * @param $type String: can be 'date', 'time' or 'both'
1846 * @param $ts Mixed: the time format which needs to be turned into a
1847 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1848 * @param $user User object used to get preferences for timezone and format
1849 * @param $options Array, can contain the following keys:
1850 * - 'timecorrection': time correction, can have the following values:
1851 * - true: use user's preference
1852 * - false: don't use time correction
1853 * - integer: value of time correction in minutes
1854 * - 'format': format to use, can have the following values:
1855 * - true: use user's preference
1856 * - false: use default preference
1857 * - string: format to use
1860 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
1861 $ts = wfTimestamp( TS_MW
, $ts );
1862 $options +
= array( 'timecorrection' => true, 'format' => true );
1863 if ( $options['timecorrection'] !== false ) {
1864 if ( $options['timecorrection'] === true ) {
1865 $offset = $user->getOption( 'timecorrection' );
1867 $offset = $options['timecorrection'];
1869 $ts = $this->userAdjust( $ts, $offset );
1871 if ( $options['format'] === true ) {
1872 $format = $user->getDatePreference();
1874 $format = $options['format'];
1876 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1877 return $this->sprintfDate( $df, $ts );
1881 * Get the formatted date for the given timestamp and formatted for
1884 * @param $ts Mixed: the time format which needs to be turned into a
1885 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1886 * @param $user User object used to get preferences for timezone and format
1887 * @param $options Array, can contain the following keys:
1888 * - 'timecorrection': time correction, can have the following values:
1889 * - true: use user's preference
1890 * - false: don't use time correction
1891 * - integer: value of time correction in minutes
1892 * - 'format': format to use, can have the following values:
1893 * - true: use user's preference
1894 * - false: use default preference
1895 * - string: format to use
1898 public function userDate( $ts, User
$user, array $options = array() ) {
1899 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
1903 * Get the formatted time for the given timestamp and formatted for
1906 * @param $ts Mixed: the time format which needs to be turned into a
1907 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1908 * @param $user User object used to get preferences for timezone and format
1909 * @param $options Array, can contain the following keys:
1910 * - 'timecorrection': time correction, can have the following values:
1911 * - true: use user's preference
1912 * - false: don't use time correction
1913 * - integer: value of time correction in minutes
1914 * - 'format': format to use, can have the following values:
1915 * - true: use user's preference
1916 * - false: use default preference
1917 * - string: format to use
1920 public function userTime( $ts, User
$user, array $options = array() ) {
1921 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
1925 * Get the formatted date and time for the given timestamp and formatted for
1928 * @param $ts Mixed: the time format which needs to be turned into a
1929 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1930 * @param $user User object used to get preferences for timezone and format
1931 * @param $options Array, can contain the following keys:
1932 * - 'timecorrection': time correction, can have the following values:
1933 * - true: use user's preference
1934 * - false: don't use time correction
1935 * - integer: value of time correction in minutes
1936 * - 'format': format to use, can have the following values:
1937 * - true: use user's preference
1938 * - false: use default preference
1939 * - string: format to use
1942 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
1943 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
1947 * @param $key string
1948 * @return array|null
1950 function getMessage( $key ) {
1951 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1957 function getAllMessages() {
1958 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1967 function iconv( $in, $out, $string ) {
1968 # This is a wrapper for iconv in all languages except esperanto,
1969 # which does some nasty x-conversions beforehand
1971 # Even with //IGNORE iconv can whine about illegal characters in
1972 # *input* string. We just ignore those too.
1973 # REF: http://bugs.php.net/bug.php?id=37166
1974 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1975 wfSuppressWarnings();
1976 $text = iconv( $in, $out . '//IGNORE', $string );
1977 wfRestoreWarnings();
1981 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1984 * @param $matches array
1985 * @return mixed|string
1987 function ucwordbreaksCallbackAscii( $matches ) {
1988 return $this->ucfirst( $matches[1] );
1992 * @param $matches array
1995 function ucwordbreaksCallbackMB( $matches ) {
1996 return mb_strtoupper( $matches[0] );
2000 * @param $matches array
2003 function ucCallback( $matches ) {
2004 list( $wikiUpperChars ) = self
::getCaseMaps();
2005 return strtr( $matches[1], $wikiUpperChars );
2009 * @param $matches array
2012 function lcCallback( $matches ) {
2013 list( , $wikiLowerChars ) = self
::getCaseMaps();
2014 return strtr( $matches[1], $wikiLowerChars );
2018 * @param $matches array
2021 function ucwordsCallbackMB( $matches ) {
2022 return mb_strtoupper( $matches[0] );
2026 * @param $matches array
2029 function ucwordsCallbackWiki( $matches ) {
2030 list( $wikiUpperChars ) = self
::getCaseMaps();
2031 return strtr( $matches[0], $wikiUpperChars );
2035 * Make a string's first character uppercase
2037 * @param $str string
2041 function ucfirst( $str ) {
2043 if ( $o < 96 ) { // if already uppercase...
2045 } elseif ( $o < 128 ) {
2046 return ucfirst( $str ); // use PHP's ucfirst()
2048 // fall back to more complex logic in case of multibyte strings
2049 return $this->uc( $str, true );
2054 * Convert a string to uppercase
2056 * @param $str string
2057 * @param $first bool
2061 function uc( $str, $first = false ) {
2062 if ( function_exists( 'mb_strtoupper' ) ) {
2064 if ( $this->isMultibyte( $str ) ) {
2065 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2067 return ucfirst( $str );
2070 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2073 if ( $this->isMultibyte( $str ) ) {
2074 $x = $first ?
'^' : '';
2075 return preg_replace_callback(
2076 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2077 array( $this, 'ucCallback' ),
2081 return $first ?
ucfirst( $str ) : strtoupper( $str );
2087 * @param $str string
2088 * @return mixed|string
2090 function lcfirst( $str ) {
2093 return strval( $str );
2094 } elseif ( $o >= 128 ) {
2095 return $this->lc( $str, true );
2096 } elseif ( $o > 96 ) {
2099 $str[0] = strtolower( $str[0] );
2105 * @param $str string
2106 * @param $first bool
2107 * @return mixed|string
2109 function lc( $str, $first = false ) {
2110 if ( function_exists( 'mb_strtolower' ) ) {
2112 if ( $this->isMultibyte( $str ) ) {
2113 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2115 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2118 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2121 if ( $this->isMultibyte( $str ) ) {
2122 $x = $first ?
'^' : '';
2123 return preg_replace_callback(
2124 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2125 array( $this, 'lcCallback' ),
2129 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2135 * @param $str string
2138 function isMultibyte( $str ) {
2139 return (bool)preg_match( '/[\x80-\xff]/', $str );
2143 * @param $str string
2144 * @return mixed|string
2146 function ucwords( $str ) {
2147 if ( $this->isMultibyte( $str ) ) {
2148 $str = $this->lc( $str );
2150 // regexp to find first letter in each word (i.e. after each space)
2151 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2153 // function to use to capitalize a single char
2154 if ( function_exists( 'mb_strtoupper' ) ) {
2155 return preg_replace_callback(
2157 array( $this, 'ucwordsCallbackMB' ),
2161 return preg_replace_callback(
2163 array( $this, 'ucwordsCallbackWiki' ),
2168 return ucwords( strtolower( $str ) );
2173 * capitalize words at word breaks
2175 * @param $str string
2178 function ucwordbreaks( $str ) {
2179 if ( $this->isMultibyte( $str ) ) {
2180 $str = $this->lc( $str );
2182 // since \b doesn't work for UTF-8, we explicitely define word break chars
2183 $breaks = "[ \-\(\)\}\{\.,\?!]";
2185 // find first letter after word break
2186 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2188 if ( function_exists( 'mb_strtoupper' ) ) {
2189 return preg_replace_callback(
2191 array( $this, 'ucwordbreaksCallbackMB' ),
2195 return preg_replace_callback(
2197 array( $this, 'ucwordsCallbackWiki' ),
2202 return preg_replace_callback(
2203 '/\b([\w\x80-\xff]+)\b/',
2204 array( $this, 'ucwordbreaksCallbackAscii' ),
2211 * Return a case-folded representation of $s
2213 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2214 * and $s2 are the same except for the case of their characters. It is not
2215 * necessary for the value returned to make sense when displayed.
2217 * Do *not* perform any other normalisation in this function. If a caller
2218 * uses this function when it should be using a more general normalisation
2219 * function, then fix the caller.
2225 function caseFold( $s ) {
2226 return $this->uc( $s );
2233 function checkTitleEncoding( $s ) {
2234 if ( is_array( $s ) ) {
2235 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2237 # Check for non-UTF-8 URLs
2238 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2243 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2244 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2249 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2255 function fallback8bitEncoding() {
2256 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2260 * Most writing systems use whitespace to break up words.
2261 * Some languages such as Chinese don't conventionally do this,
2262 * which requires special handling when breaking up words for
2267 function hasWordBreaks() {
2272 * Some languages such as Chinese require word segmentation,
2273 * Specify such segmentation when overridden in derived class.
2275 * @param $string String
2278 function segmentByWord( $string ) {
2283 * Some languages have special punctuation need to be normalized.
2284 * Make such changes here.
2286 * @param $string String
2289 function normalizeForSearch( $string ) {
2290 return self
::convertDoubleWidth( $string );
2294 * convert double-width roman characters to single-width.
2295 * range: ff00-ff5f ~= 0020-007f
2297 * @param $string string
2301 protected static function convertDoubleWidth( $string ) {
2302 static $full = null;
2303 static $half = null;
2305 if ( $full === null ) {
2306 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2307 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2308 $full = str_split( $fullWidth, 3 );
2309 $half = str_split( $halfWidth );
2312 $string = str_replace( $full, $half, $string );
2317 * @param $string string
2318 * @param $pattern string
2321 protected static function insertSpace( $string, $pattern ) {
2322 $string = preg_replace( $pattern, " $1 ", $string );
2323 $string = preg_replace( '/ +/', ' ', $string );
2328 * @param $termsArray array
2331 function convertForSearchResult( $termsArray ) {
2332 # some languages, e.g. Chinese, need to do a conversion
2333 # in order for search results to be displayed correctly
2338 * Get the first character of a string.
2343 function firstChar( $s ) {
2346 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2347 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2352 if ( isset( $matches[1] ) ) {
2353 if ( strlen( $matches[1] ) != 3 ) {
2357 // Break down Hangul syllables to grab the first jamo
2358 $code = utf8ToCodepoint( $matches[1] );
2359 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2361 } elseif ( $code < 0xb098 ) {
2362 return "\xe3\x84\xb1";
2363 } elseif ( $code < 0xb2e4 ) {
2364 return "\xe3\x84\xb4";
2365 } elseif ( $code < 0xb77c ) {
2366 return "\xe3\x84\xb7";
2367 } elseif ( $code < 0xb9c8 ) {
2368 return "\xe3\x84\xb9";
2369 } elseif ( $code < 0xbc14 ) {
2370 return "\xe3\x85\x81";
2371 } elseif ( $code < 0xc0ac ) {
2372 return "\xe3\x85\x82";
2373 } elseif ( $code < 0xc544 ) {
2374 return "\xe3\x85\x85";
2375 } elseif ( $code < 0xc790 ) {
2376 return "\xe3\x85\x87";
2377 } elseif ( $code < 0xcc28 ) {
2378 return "\xe3\x85\x88";
2379 } elseif ( $code < 0xce74 ) {
2380 return "\xe3\x85\x8a";
2381 } elseif ( $code < 0xd0c0 ) {
2382 return "\xe3\x85\x8b";
2383 } elseif ( $code < 0xd30c ) {
2384 return "\xe3\x85\x8c";
2385 } elseif ( $code < 0xd558 ) {
2386 return "\xe3\x85\x8d";
2388 return "\xe3\x85\x8e";
2395 function initEncoding() {
2396 # Some languages may have an alternate char encoding option
2397 # (Esperanto X-coding, Japanese furigana conversion, etc)
2398 # If this language is used as the primary content language,
2399 # an override to the defaults can be set here on startup.
2406 function recodeForEdit( $s ) {
2407 # For some languages we'll want to explicitly specify
2408 # which characters make it into the edit box raw
2409 # or are converted in some way or another.
2410 global $wgEditEncoding;
2411 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2414 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2422 function recodeInput( $s ) {
2423 # Take the previous into account.
2424 global $wgEditEncoding;
2425 if ( $wgEditEncoding != '' ) {
2426 $enc = $wgEditEncoding;
2430 if ( $enc == 'UTF-8' ) {
2433 return $this->iconv( $enc, 'UTF-8', $s );
2438 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2439 * also cleans up certain backwards-compatible sequences, converting them
2440 * to the modern Unicode equivalent.
2442 * This is language-specific for performance reasons only.
2448 function normalize( $s ) {
2449 global $wgAllUnicodeFixes;
2450 $s = UtfNormal
::cleanUp( $s );
2451 if ( $wgAllUnicodeFixes ) {
2452 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2453 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2460 * Transform a string using serialized data stored in the given file (which
2461 * must be in the serialized subdirectory of $IP). The file contains pairs
2462 * mapping source characters to destination characters.
2464 * The data is cached in process memory. This will go faster if you have the
2465 * FastStringSearch extension.
2467 * @param $file string
2468 * @param $string string
2472 function transformUsingPairFile( $file, $string ) {
2473 if ( !isset( $this->transformData
[$file] ) ) {
2474 $data = wfGetPrecompiledData( $file );
2475 if ( $data === false ) {
2476 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2478 $this->transformData
[$file] = new ReplacementArray( $data );
2480 return $this->transformData
[$file]->replace( $string );
2484 * For right-to-left language support
2489 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2493 * Return the correct HTML 'dir' attribute value for this language.
2497 return $this->isRTL() ?
'rtl' : 'ltr';
2501 * Return 'left' or 'right' as appropriate alignment for line-start
2502 * for this language's text direction.
2504 * Should be equivalent to CSS3 'start' text-align value....
2508 function alignStart() {
2509 return $this->isRTL() ?
'right' : 'left';
2513 * Return 'right' or 'left' as appropriate alignment for line-end
2514 * for this language's text direction.
2516 * Should be equivalent to CSS3 'end' text-align value....
2520 function alignEnd() {
2521 return $this->isRTL() ?
'left' : 'right';
2525 * A hidden direction mark (LRM or RLM), depending on the language direction
2527 * @param $opposite Boolean Get the direction mark opposite to your language
2530 function getDirMark( $opposite = false ) {
2531 $rtl = "\xE2\x80\x8F";
2532 $ltr = "\xE2\x80\x8E";
2533 if ( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2534 return $this->isRTL() ?
$rtl : $ltr;
2540 function capitalizeAllNouns() {
2541 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2545 * An arrow, depending on the language direction
2549 function getArrow() {
2550 return $this->isRTL() ?
'←' : '→';
2554 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2558 function linkPrefixExtension() {
2559 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2565 function getMagicWords() {
2566 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2569 protected function doMagicHook() {
2570 if ( $this->mMagicHookDone
) {
2573 $this->mMagicHookDone
= true;
2574 wfProfileIn( 'LanguageGetMagic' );
2575 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2576 wfProfileOut( 'LanguageGetMagic' );
2580 * Fill a MagicWord object with data from here
2584 function getMagic( $mw ) {
2585 $this->doMagicHook();
2587 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2588 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2590 $magicWords = $this->getMagicWords();
2591 if ( isset( $magicWords[$mw->mId
] ) ) {
2592 $rawEntry = $magicWords[$mw->mId
];
2598 if ( !is_array( $rawEntry ) ) {
2599 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2601 $mw->mCaseSensitive
= $rawEntry[0];
2602 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2607 * Add magic words to the extension array
2609 * @param $newWords array
2611 function addMagicWordsByLang( $newWords ) {
2612 $fallbackChain = $this->getFallbackLanguages();
2613 $fallbackChain = array_reverse( $fallbackChain );
2614 foreach ( $fallbackChain as $code ) {
2615 if ( isset( $newWords[$code] ) ) {
2616 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2622 * Get special page names, as an associative array
2623 * case folded alias => real name
2625 function getSpecialPageAliases() {
2626 // Cache aliases because it may be slow to load them
2627 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2629 $this->mExtendedSpecialPageAliases
=
2630 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2631 wfRunHooks( 'LanguageGetSpecialPageAliases',
2632 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2635 return $this->mExtendedSpecialPageAliases
;
2639 * Italic is unsuitable for some languages
2641 * @param $text String: the text to be emphasized.
2644 function emphasize( $text ) {
2645 return "<em>$text</em>";
2649 * Normally we output all numbers in plain en_US style, that is
2650 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2651 * point twohundredthirtyfive. However this is not suitable for all
2652 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2653 * Icelandic just want to use commas instead of dots, and dots instead
2654 * of commas like "293.291,235".
2656 * An example of this function being called:
2658 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2661 * See LanguageGu.php for the Gujarati implementation and
2662 * $separatorTransformTable on MessageIs.php for
2663 * the , => . and . => , implementation.
2665 * @todo check if it's viable to use localeconv() for the decimal
2667 * @param $number Mixed: the string to be formatted, should be an integer
2668 * or a floating point number.
2669 * @param $nocommafy Bool: set to true for special numbers like dates
2672 function formatNum( $number, $nocommafy = false ) {
2673 global $wgTranslateNumerals;
2674 if ( !$nocommafy ) {
2675 $number = $this->commafy( $number );
2676 $s = $this->separatorTransformTable();
2678 $number = strtr( $number, $s );
2682 if ( $wgTranslateNumerals ) {
2683 $s = $this->digitTransformTable();
2685 $number = strtr( $number, $s );
2693 * @param $number string
2696 function parseFormattedNumber( $number ) {
2697 $s = $this->digitTransformTable();
2699 $number = strtr( $number, array_flip( $s ) );
2702 $s = $this->separatorTransformTable();
2704 $number = strtr( $number, array_flip( $s ) );
2707 $number = strtr( $number, array( ',' => '' ) );
2712 * Adds commas to a given number
2717 function commafy( $_ ) {
2718 $digitGroupingPattern = $this->digitGroupingPattern();
2720 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2721 // default grouping is at thousands, use the same for ###,###,### pattern too.
2722 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2724 // Ref: http://cldr.unicode.org/translation/number-patterns
2726 if ( intval( $_ ) < 0 ) {
2727 // For negative numbers apply the algorithm like positive number and add sign.
2729 $_ = substr( $_,1 );
2731 $numberpart = array();
2732 $decimalpart = array();
2733 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2734 preg_match( "/\d+/", $_, $numberpart );
2735 preg_match( "/\.\d*/", $_, $decimalpart );
2736 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2737 if ( $groupedNumber === $_ ) {
2738 // the string does not have any number part. Eg: .12345
2739 return $sign . $groupedNumber;
2741 $start = $end = strlen( $numberpart[0] );
2742 while ( $start > 0 ) {
2743 $match = $matches[0][$numMatches -1] ;
2744 $matchLen = strlen( $match );
2745 $start = $end - $matchLen;
2749 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2751 if ( $numMatches > 1 ) {
2752 // use the last pattern for the rest of the number
2756 $groupedNumber = "," . $groupedNumber;
2759 return $sign . $groupedNumber;
2765 function digitGroupingPattern() {
2766 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2772 function digitTransformTable() {
2773 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2779 function separatorTransformTable() {
2780 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2784 * Take a list of strings and build a locale-friendly comma-separated
2785 * list, using the local comma-separator message.
2786 * The last two strings are chained with an "and".
2791 function listToText( $l ) {
2793 $m = count( $l ) - 1;
2795 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2797 for ( $i = $m; $i >= 0; $i-- ) {
2800 } elseif ( $i == $m - 1 ) {
2801 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2803 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2811 * Take a list of strings and build a locale-friendly comma-separated
2812 * list, using the local comma-separator message.
2813 * @param $list array of strings to put in a comma list
2816 function commaList( $list ) {
2821 array( 'parsemag', 'escapenoentities', 'language' => $this )
2827 * Take a list of strings and build a locale-friendly semicolon-separated
2828 * list, using the local semicolon-separator message.
2829 * @param $list array of strings to put in a semicolon list
2832 function semicolonList( $list ) {
2836 'semicolon-separator',
2837 array( 'parsemag', 'escapenoentities', 'language' => $this )
2843 * Same as commaList, but separate it with the pipe instead.
2844 * @param $list array of strings to put in a pipe list
2847 function pipeList( $list ) {
2852 array( 'escapenoentities', 'language' => $this )
2858 * Truncate a string to a specified length in bytes, appending an optional
2859 * string (e.g. for ellipses)
2861 * The database offers limited byte lengths for some columns in the database;
2862 * multi-byte character sets mean we need to ensure that only whole characters
2863 * are included, otherwise broken characters can be passed to the user
2865 * If $length is negative, the string will be truncated from the beginning
2867 * @param $string String to truncate
2868 * @param $length Int: maximum length (including ellipses)
2869 * @param $ellipsis String to append to the truncated text
2870 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2871 * $adjustLength was introduced in 1.18, before that behaved as if false.
2874 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2875 # Use the localized ellipsis character
2876 if ( $ellipsis == '...' ) {
2877 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2879 # Check if there is no need to truncate
2880 if ( $length == 0 ) {
2881 return $ellipsis; // convention
2882 } elseif ( strlen( $string ) <= abs( $length ) ) {
2883 return $string; // no need to truncate
2885 $stringOriginal = $string;
2886 # If ellipsis length is >= $length then we can't apply $adjustLength
2887 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2888 $string = $ellipsis; // this can be slightly unexpected
2889 # Otherwise, truncate and add ellipsis...
2891 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2892 if ( $length > 0 ) {
2893 $length -= $eLength;
2894 $string = substr( $string, 0, $length ); // xyz...
2895 $string = $this->removeBadCharLast( $string );
2896 $string = $string . $ellipsis;
2898 $length +
= $eLength;
2899 $string = substr( $string, $length ); // ...xyz
2900 $string = $this->removeBadCharFirst( $string );
2901 $string = $ellipsis . $string;
2904 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2905 # This check is *not* redundant if $adjustLength, due to the single case where
2906 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2907 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2910 return $stringOriginal;
2915 * Remove bytes that represent an incomplete Unicode character
2916 * at the end of string (e.g. bytes of the char are missing)
2918 * @param $string String
2921 protected function removeBadCharLast( $string ) {
2922 if ( $string != '' ) {
2923 $char = ord( $string[strlen( $string ) - 1] );
2925 if ( $char >= 0xc0 ) {
2926 # We got the first byte only of a multibyte char; remove it.
2927 $string = substr( $string, 0, -1 );
2928 } elseif ( $char >= 0x80 &&
2929 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2930 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2932 # We chopped in the middle of a character; remove it
2940 * Remove bytes that represent an incomplete Unicode character
2941 * at the start of string (e.g. bytes of the char are missing)
2943 * @param $string String
2946 protected function removeBadCharFirst( $string ) {
2947 if ( $string != '' ) {
2948 $char = ord( $string[0] );
2949 if ( $char >= 0x80 && $char < 0xc0 ) {
2950 # We chopped in the middle of a character; remove the whole thing
2951 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2958 * Truncate a string of valid HTML to a specified length in bytes,
2959 * appending an optional string (e.g. for ellipses), and return valid HTML
2961 * This is only intended for styled/linked text, such as HTML with
2962 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2963 * Also, this will not detect things like "display:none" CSS.
2965 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2967 * @param string $text HTML string to truncate
2968 * @param int $length (zero/positive) Maximum length (including ellipses)
2969 * @param string $ellipsis String to append to the truncated text
2972 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2973 # Use the localized ellipsis character
2974 if ( $ellipsis == '...' ) {
2975 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2977 # Check if there is clearly no need to truncate
2978 if ( $length <= 0 ) {
2979 return $ellipsis; // no text shown, nothing to format (convention)
2980 } elseif ( strlen( $text ) <= $length ) {
2981 return $text; // string short enough even *with* HTML (short-circuit)
2984 $dispLen = 0; // innerHTML legth so far
2985 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2986 $tagType = 0; // 0-open, 1-close
2987 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2988 $entityState = 0; // 0-not entity, 1-entity
2989 $tag = $ret = ''; // accumulated tag name, accumulated result string
2990 $openTags = array(); // open tag stack
2991 $maybeState = null; // possible truncation state
2993 $textLen = strlen( $text );
2994 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2995 for ( $pos = 0; true; ++
$pos ) {
2996 # Consider truncation once the display length has reached the maximim.
2997 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2998 # Check that we're not in the middle of a bracket/entity...
2999 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3000 if ( !$testingEllipsis ) {
3001 $testingEllipsis = true;
3002 # Save where we are; we will truncate here unless there turn out to
3003 # be so few remaining characters that truncation is not necessary.
3004 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3005 $maybeState = array( $ret, $openTags ); // save state
3007 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3008 # String in fact does need truncation, the truncation point was OK.
3009 list( $ret, $openTags ) = $maybeState; // reload state
3010 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3011 $ret .= $ellipsis; // add ellipsis
3015 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3017 # Read the next char...
3019 $lastCh = $pos ?
$text[$pos - 1] : '';
3020 $ret .= $ch; // add to result string
3022 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3023 $entityState = 0; // for bad HTML
3024 $bracketState = 1; // tag started (checking for backslash)
3025 } elseif ( $ch == '>' ) {
3026 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3027 $entityState = 0; // for bad HTML
3028 $bracketState = 0; // out of brackets
3029 } elseif ( $bracketState == 1 ) {
3031 $tagType = 1; // close tag (e.g. "</span>")
3033 $tagType = 0; // open tag (e.g. "<span>")
3036 $bracketState = 2; // building tag name
3037 } elseif ( $bracketState == 2 ) {
3041 // Name found (e.g. "<a href=..."), add on tag attributes...
3042 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3044 } elseif ( $bracketState == 0 ) {
3045 if ( $entityState ) {
3048 $dispLen++
; // entity is one displayed char
3051 if ( $neLength == 0 && !$maybeState ) {
3052 // Save state without $ch. We want to *hit* the first
3053 // display char (to get tags) but not *use* it if truncating.
3054 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3057 $entityState = 1; // entity found, (e.g. " ")
3059 $dispLen++
; // this char is displayed
3060 // Add the next $max display text chars after this in one swoop...
3061 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3062 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3063 $dispLen +
= $skipped;
3069 // Close the last tag if left unclosed by bad HTML
3070 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3071 while ( count( $openTags ) > 0 ) {
3072 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3078 * truncateHtml() helper function
3079 * like strcspn() but adds the skipped chars to $ret
3088 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3089 if ( $len === null ) {
3090 $len = -1; // -1 means "no limit" for strcspn
3091 } elseif ( $len < 0 ) {
3095 if ( $start < strlen( $text ) ) {
3096 $skipCount = strcspn( $text, $search, $start, $len );
3097 $ret .= substr( $text, $start, $skipCount );
3103 * truncateHtml() helper function
3104 * (a) push or pop $tag from $openTags as needed
3105 * (b) clear $tag value
3106 * @param &$tag string Current HTML tag name we are looking at
3107 * @param $tagType int (0-open tag, 1-close tag)
3108 * @param $lastCh char|string Character before the '>' that ended this tag
3109 * @param &$openTags array Open tag stack (not accounting for $tag)
3111 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3112 $tag = ltrim( $tag );
3114 if ( $tagType == 0 && $lastCh != '/' ) {
3115 $openTags[] = $tag; // tag opened (didn't close itself)
3116 } elseif ( $tagType == 1 ) {
3117 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3118 array_pop( $openTags ); // tag closed
3126 * Grammatical transformations, needed for inflected languages
3127 * Invoked by putting {{grammar:case|word}} in a message
3129 * @param $word string
3130 * @param $case string
3133 function convertGrammar( $word, $case ) {
3134 global $wgGrammarForms;
3135 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3136 return $wgGrammarForms[$this->getCode()][$case][$word];
3142 * Provides an alternative text depending on specified gender.
3143 * Usage {{gender:username|masculine|feminine|neutral}}.
3144 * username is optional, in which case the gender of current user is used,
3145 * but only in (some) interface messages; otherwise default gender is used.
3146 * If second or third parameter are not specified, masculine is used.
3147 * These details may be overriden per language.
3149 * @param $gender string
3150 * @param $forms array
3154 function gender( $gender, $forms ) {
3155 if ( !count( $forms ) ) {
3158 $forms = $this->preConvertPlural( $forms, 2 );
3159 if ( $gender === 'male' ) {
3162 if ( $gender === 'female' ) {
3165 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3169 * Plural form transformations, needed for some languages.
3170 * For example, there are 3 form of plural in Russian and Polish,
3171 * depending on "count mod 10". See [[w:Plural]]
3172 * For English it is pretty simple.
3174 * Invoked by putting {{plural:count|wordform1|wordform2}}
3175 * or {{plural:count|wordform1|wordform2|wordform3}}
3177 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3179 * @param $count Integer: non-localized number
3180 * @param $forms Array: different plural forms
3181 * @return string Correct form of plural for $count in this language
3183 function convertPlural( $count, $forms ) {
3184 if ( !count( $forms ) ) {
3187 $forms = $this->preConvertPlural( $forms, 2 );
3189 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3193 * Checks that convertPlural was given an array and pads it to requested
3194 * amount of forms by copying the last one.
3196 * @param $count Integer: How many forms should there be at least
3197 * @param $forms Array of forms given to convertPlural
3198 * @return array Padded array of forms or an exception if not an array
3200 protected function preConvertPlural( /* Array */ $forms, $count ) {
3201 while ( count( $forms ) < $count ) {
3202 $forms[] = $forms[count( $forms ) - 1];
3208 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3209 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3210 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3211 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3214 * @param $str String: the validated block duration in English
3215 * @return Somehow translated block duration
3216 * @see LanguageFi.php for example implementation
3218 function translateBlockExpiry( $str ) {
3219 $duration = SpecialBlock
::getSuggestedDurations( $this );
3220 foreach ( $duration as $show => $value ) {
3221 if ( strcmp( $str, $value ) == 0 ) {
3222 return htmlspecialchars( trim( $show ) );
3226 // Since usually only infinite or indefinite is only on list, so try
3227 // equivalents if still here.
3228 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3229 if ( in_array( $str, $indefs ) ) {
3230 foreach ( $indefs as $val ) {
3231 $show = array_search( $val, $duration, true );
3232 if ( $show !== false ) {
3233 return htmlspecialchars( trim( $show ) );
3237 // If all else fails, return the original string.
3242 * languages like Chinese need to be segmented in order for the diff
3245 * @param $text String
3248 function segmentForDiff( $text ) {
3253 * and unsegment to show the result
3255 * @param $text String
3258 function unsegmentForDiff( $text ) {
3263 * convert text to all supported variants
3265 * @param $text string
3268 function autoConvertToAllVariants( $text ) {
3269 return $this->mConverter
->autoConvertToAllVariants( $text );
3273 * convert text to different variants of a language.
3275 * @param $text string
3278 function convert( $text ) {
3279 return $this->mConverter
->convert( $text );
3284 * Convert a Title object to a string in the preferred variant
3286 * @param $title Title
3289 function convertTitle( $title ) {
3290 return $this->mConverter
->convertTitle( $title );
3294 * Check if this is a language with variants
3298 function hasVariants() {
3299 return sizeof( $this->getVariants() ) > 1;
3303 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3305 * @param $text string
3308 function armourMath( $text ) {
3309 return $this->mConverter
->armourMath( $text );
3313 * Perform output conversion on a string, and encode for safe HTML output.
3314 * @param $text String text to be converted
3315 * @param $isTitle Bool whether this conversion is for the article title
3317 * @todo this should get integrated somewhere sane
3319 function convertHtml( $text, $isTitle = false ) {
3320 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3324 * @param $key string
3327 function convertCategoryKey( $key ) {
3328 return $this->mConverter
->convertCategoryKey( $key );
3332 * Get the list of variants supported by this language
3333 * see sample implementation in LanguageZh.php
3335 * @return array an array of language codes
3337 function getVariants() {
3338 return $this->mConverter
->getVariants();
3344 function getPreferredVariant() {
3345 return $this->mConverter
->getPreferredVariant();
3351 function getDefaultVariant() {
3352 return $this->mConverter
->getDefaultVariant();
3358 function getURLVariant() {
3359 return $this->mConverter
->getURLVariant();
3363 * If a language supports multiple variants, it is
3364 * possible that non-existing link in one variant
3365 * actually exists in another variant. this function
3366 * tries to find it. See e.g. LanguageZh.php
3368 * @param $link String: the name of the link
3369 * @param $nt Mixed: the title object of the link
3370 * @param $ignoreOtherCond Boolean: to disable other conditions when
3371 * we need to transclude a template or update a category's link
3372 * @return null the input parameters may be modified upon return
3374 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3375 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3379 * If a language supports multiple variants, converts text
3380 * into an array of all possible variants of the text:
3381 * 'variant' => text in that variant
3383 * @deprecated since 1.17 Use autoConvertToAllVariants()
3385 * @param $text string
3389 function convertLinkToAllVariants( $text ) {
3390 return $this->mConverter
->convertLinkToAllVariants( $text );
3394 * returns language specific options used by User::getPageRenderHash()
3395 * for example, the preferred language variant
3399 function getExtraHashOptions() {
3400 return $this->mConverter
->getExtraHashOptions();
3404 * For languages that support multiple variants, the title of an
3405 * article may be displayed differently in different variants. this
3406 * function returns the apporiate title defined in the body of the article.
3410 function getParsedTitle() {
3411 return $this->mConverter
->getParsedTitle();
3415 * Enclose a string with the "no conversion" tag. This is used by
3416 * various functions in the Parser
3418 * @param $text String: text to be tagged for no conversion
3419 * @param $noParse bool
3420 * @return string the tagged text
3422 function markNoConversion( $text, $noParse = false ) {
3423 return $this->mConverter
->markNoConversion( $text, $noParse );
3427 * A regular expression to match legal word-trailing characters
3428 * which should be merged onto a link of the form [[foo]]bar.
3432 function linkTrail() {
3433 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3439 function getLangObj() {
3444 * Get the RFC 3066 code for this language object
3448 function getCode() {
3449 return $this->mCode
;
3453 * @param $code string
3455 function setCode( $code ) {
3456 $this->mCode
= $code;
3460 * Get the name of a file for a certain language code
3461 * @param $prefix string Prepend this to the filename
3462 * @param $code string Language code
3463 * @param $suffix string Append this to the filename
3464 * @return string $prefix . $mangledCode . $suffix
3466 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3467 // Protect against path traversal
3468 if ( !Language
::isValidCode( $code )
3469 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3471 throw new MWException( "Invalid language code \"$code\"" );
3474 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3478 * Get the language code from a file name. Inverse of getFileName()
3479 * @param $filename string $prefix . $languageCode . $suffix
3480 * @param $prefix string Prefix before the language code
3481 * @param $suffix string Suffix after the language code
3482 * @return string Language code, or false if $prefix or $suffix isn't found
3484 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3486 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3487 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3488 if ( !count( $m ) ) {
3491 return str_replace( '_', '-', strtolower( $m[1] ) );
3495 * @param $code string
3498 static function getMessagesFileName( $code ) {
3500 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3504 * @param $code string
3507 static function getClassFileName( $code ) {
3509 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3513 * Get the first fallback for a given language.
3515 * @param $code string
3517 * @return false|string
3519 static function getFallbackFor( $code ) {
3520 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3523 $fallbacks = self
::getFallbacksFor( $code );
3524 $first = array_shift( $fallbacks );
3530 * Get the ordered list of fallback languages.
3533 * @param $code string Language code
3536 static function getFallbacksFor( $code ) {
3537 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3540 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3541 $v = array_map( 'trim', explode( ',', $v ) );
3542 if ( $v[count( $v ) - 1] !== 'en' ) {
3550 * Get all messages for a given language
3551 * WARNING: this may take a long time. If you just need all message *keys*
3552 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3554 * @param $code string
3558 static function getMessagesFor( $code ) {
3559 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3563 * Get a message for a given language
3565 * @param $key string
3566 * @param $code string
3570 static function getMessageFor( $key, $code ) {
3571 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3575 * Get all message keys for a given language. This is a faster alternative to
3576 * array_keys( Language::getMessagesFor( $code ) )
3579 * @param $code string Language code
3580 * @return array of message keys (strings)
3582 static function getMessageKeysFor( $code ) {
3583 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3590 function fixVariableInNamespace( $talk ) {
3591 if ( strpos( $talk, '$1' ) === false ) {
3595 global $wgMetaNamespace;
3596 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3598 # Allow grammar transformations
3599 # Allowing full message-style parsing would make simple requests
3600 # such as action=raw much more expensive than they need to be.
3601 # This will hopefully cover most cases.
3602 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3603 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3604 return str_replace( ' ', '_', $talk );
3611 function replaceGrammarInNamespace( $m ) {
3612 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3616 * @throws MWException
3619 static function getCaseMaps() {
3620 static $wikiUpperChars, $wikiLowerChars;
3621 if ( isset( $wikiUpperChars ) ) {
3622 return array( $wikiUpperChars, $wikiLowerChars );
3625 wfProfileIn( __METHOD__
);
3626 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3627 if ( $arr === false ) {
3628 throw new MWException(
3629 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3631 $wikiUpperChars = $arr['wikiUpperChars'];
3632 $wikiLowerChars = $arr['wikiLowerChars'];
3633 wfProfileOut( __METHOD__
);
3634 return array( $wikiUpperChars, $wikiLowerChars );
3638 * Decode an expiry (block, protection, etc) which has come from the DB
3640 * @param $expiry String: Database expiry String
3641 * @param $format Bool|Int true to process using language functions, or TS_ constant
3642 * to return the expiry in a given timestamp
3645 public function formatExpiry( $expiry, $format = true ) {
3646 static $infinity, $infinityMsg;
3647 if ( $infinity === null ) {
3648 $infinityMsg = wfMessage( 'infiniteblock' );
3649 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3652 if ( $expiry == '' ||
$expiry == $infinity ) {
3653 return $format === true
3657 return $format === true
3658 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3659 : wfTimestamp( $format, $expiry );
3665 * @param $seconds int|float
3666 * @param $format Array Optional
3667 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3668 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3669 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3670 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3673 function formatTimePeriod( $seconds, $format = array() ) {
3674 if ( !is_array( $format ) ) {
3675 $format = array( 'avoid' => $format ); // For backwards compatibility
3677 if ( !isset( $format['avoid'] ) ) {
3678 $format['avoid'] = false;
3680 if ( !isset( $format['noabbrevs' ] ) ) {
3681 $format['noabbrevs'] = false;
3683 $secondsMsg = wfMessage(
3684 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3685 $minutesMsg = wfMessage(
3686 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3687 $hoursMsg = wfMessage(
3688 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3689 $daysMsg = wfMessage(
3690 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3692 if ( round( $seconds * 10 ) < 100 ) {
3693 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3694 $s = $secondsMsg->params( $s )->text();
3695 } elseif ( round( $seconds ) < 60 ) {
3696 $s = $this->formatNum( round( $seconds ) );
3697 $s = $secondsMsg->params( $s )->text();
3698 } elseif ( round( $seconds ) < 3600 ) {
3699 $minutes = floor( $seconds / 60 );
3700 $secondsPart = round( fmod( $seconds, 60 ) );
3701 if ( $secondsPart == 60 ) {
3705 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3707 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3708 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3709 $hours = floor( $seconds / 3600 );
3710 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3711 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3712 if ( $secondsPart == 60 ) {
3716 if ( $minutes == 60 ) {
3720 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3722 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3723 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3724 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3727 $days = floor( $seconds / 86400 );
3728 if ( $format['avoid'] === 'avoidminutes' ) {
3729 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3730 if ( $hours == 24 ) {
3734 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3736 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3737 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3738 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3739 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3740 if ( $minutes == 60 ) {
3744 if ( $hours == 24 ) {
3748 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3750 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3752 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3754 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3756 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3766 function formatBitrate( $bps ) {
3767 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3769 return $this->formatNum( $bps ) . $units[0];
3771 $unitIndex = (int)floor( log10( $bps ) / 3 );
3772 $mantissa = $bps / pow( 1000, $unitIndex );
3773 if ( $mantissa < 10 ) {
3774 $mantissa = round( $mantissa, 1 );
3776 $mantissa = round( $mantissa );
3778 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3782 * Format a size in bytes for output, using an appropriate
3783 * unit (B, KB, MB or GB) according to the magnitude in question
3785 * @param $size int Size to format
3786 * @return string Plain text (not HTML)
3788 function formatSize( $size ) {
3789 // For small sizes no decimal places necessary
3791 if ( $size > 1024 ) {
3792 $size = $size / 1024;
3793 if ( $size > 1024 ) {
3794 $size = $size / 1024;
3795 // For MB and bigger two decimal places are smarter
3797 if ( $size > 1024 ) {
3798 $size = $size / 1024;
3799 $msg = 'size-gigabytes';
3801 $msg = 'size-megabytes';
3804 $msg = 'size-kilobytes';
3807 $msg = 'size-bytes';
3809 $size = round( $size, $round );
3810 $text = $this->getMessageFromDB( $msg );
3811 return str_replace( '$1', $this->formatNum( $size ), $text );
3815 * Make a list item, used by various special pages
3817 * @param $page String Page link
3818 * @param $details String Text between brackets
3819 * @param $oppositedm Boolean Add the direction mark opposite to your
3820 * language, to display text properly
3823 function specialList( $page, $details, $oppositedm = true ) {
3824 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
3825 $this->getDirMark();
3826 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
3827 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
3828 return $page . $details;
3832 * Generate (prev x| next x) (20|50|100...) type links for paging
3834 * @param $title Title object to link
3835 * @param $offset Integer offset parameter
3836 * @param $limit Integer limit parameter
3837 * @param $query String optional URL query parameter string
3838 * @param $atend Bool optional param for specified if this is the last page
3841 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
3842 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
3844 # Make 'previous' link
3845 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3847 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
3848 $query, $prev, 'prevn-title', 'mw-prevlink' );
3850 $plink = htmlspecialchars( $prev );
3854 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3856 $nlink = htmlspecialchars( $next );
3858 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
3859 $query, $next, 'prevn-title', 'mw-nextlink' );
3862 # Make links to set number of items per page
3863 $numLinks = array();
3864 foreach( array( 20, 50, 100, 250, 500 ) as $num ) {
3865 $numLinks[] = $this->numLink( $title, $offset, $num,
3866 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
3869 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
3870 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
3874 * Helper function for viewPrevNext() that generates links
3876 * @param $title Title object to link
3877 * @param $offset Integer offset parameter
3878 * @param $limit Integer limit parameter
3879 * @param $query Array extra query parameters
3880 * @param $link String text to use for the link; will be escaped
3881 * @param $tooltipMsg String name of the message to use as tooltip
3882 * @param $class String value of the "class" attribute of the link
3883 * @return String HTML fragment
3885 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
3886 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
3887 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
3888 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
3889 'title' => $tooltip, 'class' => $class ), $link );
3893 * Get the conversion rule title, if any.
3897 function getConvRuleTitle() {
3898 return $this->mConverter
->getConvRuleTitle();