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 global $wgInputEncoding, $wgOutputEncoding;
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
35 * a fake language converter
41 function __construct( $langobj ) { $this->mLang
= $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang
->getCode() ); }
46 function getPreferredVariant() { return $this->mLang
->getCode(); }
47 function getDefaultVariant() { return $this->mLang
->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
60 * Internationalisation code
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
135 * @param $code String
138 static function factory( $code ) {
139 if ( !isset( self
::$mLangObjCache[$code] ) ) {
140 if ( count( self
::$mLangObjCache ) > 10 ) {
141 // Don't keep a billion objects around, that's stupid.
142 self
::$mLangObjCache = array();
144 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
146 return self
::$mLangObjCache[$code];
150 * Create a language object for a given language code
151 * @param $code String
154 protected static function newFromCode( $code ) {
156 static $recursionLevel = 0;
158 // Protect against path traversal below
159 if ( !Language
::isValidCode( $code )
160 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
162 throw new MWException( "Invalid language code \"$code\"" );
165 if ( !Language
::isValidBuiltInCode( $code ) ) {
166 // It's not possible to customise this code with class files, so
167 // just return a Language object. This is to support uselang= hacks.
168 $lang = new Language
;
169 $lang->setCode( $code );
173 if ( $code == 'en' ) {
176 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
177 if ( !defined( 'MW_COMPILED' ) ) {
178 // Preload base classes to work around APC/PHP5 bug
179 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
180 include_once( "$IP/languages/classes/$class.deps.php" );
182 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
183 include_once( "$IP/languages/classes/$class.php" );
188 if ( $recursionLevel > 5 ) {
189 throw new MWException( "Language fallback loop detected when creating class $class\n" );
192 if ( !MWInit
::classExists( $class ) ) {
193 $fallback = Language
::getFallbackFor( $code );
195 $lang = Language
::newFromCode( $fallback );
197 $lang->setCode( $code );
205 * Returns true if a language code string is of a valid form, whether or
206 * not it exists. This includes codes which are used solely for
207 * customisation via the MediaWiki namespace.
209 public static function isValidCode( $code ) {
211 strcspn( $code, ":/\\\000" ) === strlen( $code )
212 && !preg_match( Title
::getTitleInvalidRegex(), $code );
216 * Returns true if a language code is of a valid form for the purposes of
217 * internal customisation of MediaWiki, via Messages*.php.
219 public static function isValidBuiltInCode( $code ) {
220 return preg_match( '/^[a-z0-9-]*$/i', $code );
224 * Get the LocalisationCache instance
226 * @return LocalisationCache
228 public static function getLocalisationCache() {
229 if ( is_null( self
::$dataCache ) ) {
230 global $wgLocalisationCacheConf;
231 $class = $wgLocalisationCacheConf['class'];
232 self
::$dataCache = new $class( $wgLocalisationCacheConf );
234 return self
::$dataCache;
237 function __construct() {
238 $this->mConverter
= new FakeConverter( $this );
239 // Set the code to the name of the descendant
240 if ( get_class( $this ) == 'Language' ) {
243 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
245 self
::getLocalisationCache();
249 * Reduce memory usage
251 function __destruct() {
252 foreach ( $this as $name => $value ) {
253 unset( $this->$name );
258 * Hook which will be called if this is the content language.
259 * Descendants can use this to register hook functions or modify globals
261 function initContLang() { }
264 * @deprecated Use User::getDefaultOptions()
267 function getDefaultUserOptions() {
268 wfDeprecated( __METHOD__
);
269 return User
::getDefaultOptions();
272 function getFallbackLanguageCode() {
273 if ( $this->mCode
=== 'en' ) {
276 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
281 * Exports $wgBookstoreListEn
284 function getBookstoreList() {
285 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
291 function getNamespaces() {
292 if ( is_null( $this->namespaceNames
) ) {
293 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
295 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
296 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
298 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
300 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
301 if ( $wgMetaNamespaceTalk ) {
302 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
304 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
305 $this->namespaceNames
[NS_PROJECT_TALK
] =
306 $this->fixVariableInNamespace( $talk );
309 # Sometimes a language will be localised but not actually exist on this wiki.
310 foreach( $this->namespaceNames
as $key => $text ) {
311 if ( !isset( $validNamespaces[$key] ) ) {
312 unset( $this->namespaceNames
[$key] );
316 # The above mixing may leave namespaces out of canonical order.
317 # Re-order by namespace ID number...
318 ksort( $this->namespaceNames
);
320 return $this->namespaceNames
;
324 * A convenience function that returns the same thing as
325 * getNamespaces() except with the array values changed to ' '
326 * where it found '_', useful for producing output to be displayed
327 * e.g. in <select> forms.
331 function getFormattedNamespaces() {
332 $ns = $this->getNamespaces();
333 foreach ( $ns as $k => $v ) {
334 $ns[$k] = strtr( $v, '_', ' ' );
340 * Get a namespace value by key
342 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
343 * echo $mw_ns; // prints 'MediaWiki'
346 * @param $index Int: the array key of the namespace to return
347 * @return mixed, string if the namespace value exists, otherwise false
349 function getNsText( $index ) {
350 $ns = $this->getNamespaces();
351 return isset( $ns[$index] ) ?
$ns[$index] : false;
355 * A convenience function that returns the same thing as
356 * getNsText() except with '_' changed to ' ', useful for
361 function getFormattedNsText( $index ) {
362 $ns = $this->getNsText( $index );
363 return strtr( $ns, '_', ' ' );
367 * Returns gender-dependent namespace alias if available.
368 * @param $index Int: namespace index
369 * @param $gender String: gender key (male, female... )
373 function getGenderNsText( $index, $gender ) {
374 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
375 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
379 * Whether this language makes distinguishes genders for example in
384 function needsGenderDistinction() {
385 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
386 return count( $aliases ) > 0;
390 * Get a namespace key by value, case insensitive.
391 * Only matches namespace names for the current language, not the
392 * canonical ones defined in Namespace.php.
394 * @param $text String
395 * @return mixed An integer if $text is a valid value otherwise false
397 function getLocalNsIndex( $text ) {
398 $lctext = $this->lc( $text );
399 $ids = $this->getNamespaceIds();
400 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
403 function getNamespaceAliases() {
404 if ( is_null( $this->namespaceAliases
) ) {
405 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
409 foreach ( $aliases as $name => $index ) {
410 if ( $index === NS_PROJECT_TALK
) {
411 unset( $aliases[$name] );
412 $name = $this->fixVariableInNamespace( $name );
413 $aliases[$name] = $index;
418 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
419 foreach ( $genders as $index => $forms ) {
420 foreach ( $forms as $alias ) {
421 $aliases[$alias] = $index;
425 $this->namespaceAliases
= $aliases;
427 return $this->namespaceAliases
;
430 function getNamespaceIds() {
431 if ( is_null( $this->mNamespaceIds
) ) {
432 global $wgNamespaceAliases;
433 # Put namespace names and aliases into a hashtable.
434 # If this is too slow, then we should arrange it so that it is done
435 # before caching. The catch is that at pre-cache time, the above
436 # class-specific fixup hasn't been done.
437 $this->mNamespaceIds
= array();
438 foreach ( $this->getNamespaces() as $index => $name ) {
439 $this->mNamespaceIds
[$this->lc( $name )] = $index;
441 foreach ( $this->getNamespaceAliases() as $name => $index ) {
442 $this->mNamespaceIds
[$this->lc( $name )] = $index;
444 if ( $wgNamespaceAliases ) {
445 foreach ( $wgNamespaceAliases as $name => $index ) {
446 $this->mNamespaceIds
[$this->lc( $name )] = $index;
450 return $this->mNamespaceIds
;
455 * Get a namespace key by value, case insensitive. Canonical namespace
456 * names override custom ones defined for the current language.
458 * @param $text String
459 * @return mixed An integer if $text is a valid value otherwise false
461 function getNsIndex( $text ) {
462 $lctext = $this->lc( $text );
463 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
466 $ids = $this->getNamespaceIds();
467 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
471 * short names for language variants used for language conversion links.
473 * @param $code String
476 function getVariantname( $code ) {
477 return $this->getMessageFromDB( "variantname-$code" );
480 function specialPage( $name ) {
481 $aliases = $this->getSpecialPageAliases();
482 if ( isset( $aliases[$name][0] ) ) {
483 $name = $aliases[$name][0];
485 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
488 function getQuickbarSettings() {
490 $this->getMessage( 'qbsettings-none' ),
491 $this->getMessage( 'qbsettings-fixedleft' ),
492 $this->getMessage( 'qbsettings-fixedright' ),
493 $this->getMessage( 'qbsettings-floatingleft' ),
494 $this->getMessage( 'qbsettings-floatingright' )
498 function getDatePreferences() {
499 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
502 function getDateFormats() {
503 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
506 function getDefaultDateFormat() {
507 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
508 if ( $df === 'dmy or mdy' ) {
509 global $wgAmericanDates;
510 return $wgAmericanDates ?
'mdy' : 'dmy';
516 function getDatePreferenceMigrationMap() {
517 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
520 function getImageFile( $image ) {
521 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
524 function getDefaultUserOptionOverrides() {
525 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
528 function getExtraUserToggles() {
529 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
532 function getUserToggle( $tog ) {
533 return $this->getMessageFromDB( "tog-$tog" );
537 * Get language names, indexed by code.
538 * If $customisedOnly is true, only returns codes with a messages file
540 public static function getLanguageNames( $customisedOnly = false ) {
541 global $wgExtraLanguageNames;
542 static $coreLanguageNames;
544 if ( $coreLanguageNames === null ) {
545 include( MWInit
::compiledPath( 'languages/Names.php' ) );
548 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
549 if ( !$customisedOnly ) {
555 $dir = opendir( "$IP/languages/messages" );
556 while ( false !== ( $file = readdir( $dir ) ) ) {
557 $code = self
::getCodeFromFileName( $file, 'Messages' );
558 if ( $code && isset( $allNames[$code] ) ) {
559 $names[$code] = $allNames[$code];
567 * Get translated language names. This is done on best effort and
568 * by default this is exactly the same as Language::getLanguageNames.
569 * The CLDR extension provides translated names.
570 * @param $code String Language code.
571 * @return Array language code => language name
574 public static function getTranslatedLanguageNames( $code ) {
576 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
578 foreach ( self
::getLanguageNames() as $code => $name ) {
579 if ( !isset( $names[$code] ) ) $names[$code] = $name;
586 * Get a message from the MediaWiki namespace.
588 * @param $msg String: message name
591 function getMessageFromDB( $msg ) {
592 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
595 function getLanguageName( $code ) {
596 $names = self
::getLanguageNames();
597 if ( !array_key_exists( $code, $names ) ) {
600 return $names[$code];
603 function getMonthName( $key ) {
604 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
607 function getMonthNameGen( $key ) {
608 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
611 function getMonthAbbreviation( $key ) {
612 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
615 function getWeekdayName( $key ) {
616 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
619 function getWeekdayAbbreviation( $key ) {
620 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
623 function getIranianCalendarMonthName( $key ) {
624 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
627 function getHebrewCalendarMonthName( $key ) {
628 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
631 function getHebrewCalendarMonthNameGen( $key ) {
632 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
635 function getHijriCalendarMonthName( $key ) {
636 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
640 * Used by date() and time() to adjust the time output.
642 * @param $ts Int the time in date('YmdHis') format
643 * @param $tz Mixed: adjust the time by this amount (default false, mean we
644 * get user timecorrection setting)
647 function userAdjust( $ts, $tz = false ) {
648 global $wgUser, $wgLocalTZoffset;
650 if ( $tz === false ) {
651 $tz = $wgUser->getOption( 'timecorrection' );
654 $data = explode( '|', $tz, 3 );
656 if ( $data[0] == 'ZoneInfo' ) {
657 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
658 $date = date_create( $ts, timezone_open( 'UTC' ) );
659 date_timezone_set( $date, timezone_open( $data[2] ) );
660 $date = date_format( $date, 'YmdHis' );
663 # Unrecognized timezone, default to 'Offset' with the stored offset.
668 if ( $data[0] == 'System' ||
$tz == '' ) {
669 # Global offset in minutes.
670 if ( isset( $wgLocalTZoffset ) ) {
671 $minDiff = $wgLocalTZoffset;
673 } else if ( $data[0] == 'Offset' ) {
674 $minDiff = intval( $data[1] );
676 $data = explode( ':', $tz );
677 if ( count( $data ) == 2 ) {
678 $data[0] = intval( $data[0] );
679 $data[1] = intval( $data[1] );
680 $minDiff = abs( $data[0] ) * 60 +
$data[1];
681 if ( $data[0] < 0 ) {
682 $minDiff = -$minDiff;
685 $minDiff = intval( $data[0] ) * 60;
689 # No difference ? Return time unchanged
690 if ( 0 == $minDiff ) {
694 wfSuppressWarnings(); // E_STRICT system time bitching
695 # Generate an adjusted date; take advantage of the fact that mktime
696 # will normalize out-of-range values so we don't have to split $minDiff
697 # into hours and minutes.
699 (int)substr( $ts, 8, 2 ) ), # Hours
700 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
701 (int)substr( $ts, 12, 2 ), # Seconds
702 (int)substr( $ts, 4, 2 ), # Month
703 (int)substr( $ts, 6, 2 ), # Day
704 (int)substr( $ts, 0, 4 ) ); # Year
706 $date = date( 'YmdHis', $t );
713 * This is a workalike of PHP's date() function, but with better
714 * internationalisation, a reduced set of format characters, and a better
717 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
718 * PHP manual for definitions. There are a number of extensions, which
721 * xn Do not translate digits of the next numeric format character
722 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
723 * xr Use roman numerals for the next numeric format character
724 * xh Use hebrew numerals for the next numeric format character
726 * xg Genitive month name
728 * xij j (day number) in Iranian calendar
729 * xiF F (month name) in Iranian calendar
730 * xin n (month number) in Iranian calendar
731 * xiY Y (full year) in Iranian calendar
733 * xjj j (day number) in Hebrew calendar
734 * xjF F (month name) in Hebrew calendar
735 * xjt t (days in month) in Hebrew calendar
736 * xjx xg (genitive month name) in Hebrew calendar
737 * xjn n (month number) in Hebrew calendar
738 * xjY Y (full year) in Hebrew calendar
740 * xmj j (day number) in Hijri calendar
741 * xmF F (month name) in Hijri calendar
742 * xmn n (month number) in Hijri calendar
743 * xmY Y (full year) in Hijri calendar
745 * xkY Y (full year) in Thai solar calendar. Months and days are
746 * identical to the Gregorian calendar
747 * xoY Y (full year) in Minguo calendar or Juche year.
748 * Months and days are identical to the
750 * xtY Y (full year) in Japanese nengo. Months and days are
751 * identical to the Gregorian calendar
753 * Characters enclosed in double quotes will be considered literal (with
754 * the quotes themselves removed). Unmatched quotes will be considered
755 * literal quotes. Example:
757 * "The month is" F => The month is January
760 * Backslash escaping is also supported.
762 * Input timestamp is assumed to be pre-normalized to the desired local
765 * @param $format String
766 * @param $ts String: 14-character timestamp
769 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
771 function sprintfDate( $format, $ts ) {
784 for ( $p = 0; $p < strlen( $format ); $p++
) {
787 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
788 $code .= $format[++
$p];
791 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
792 $code .= $format[++
$p];
803 $rawToggle = !$rawToggle;
812 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
815 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
816 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
819 $num = substr( $ts, 6, 2 );
822 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
823 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
826 $num = intval( substr( $ts, 6, 2 ) );
830 $iranian = self
::tsToIranian( $ts );
836 $hijri = self
::tsToHijri( $ts );
842 $hebrew = self
::tsToHebrew( $ts );
848 $unix = wfTimestamp( TS_UNIX
, $ts );
850 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
854 $unix = wfTimestamp( TS_UNIX
, $ts );
856 $w = gmdate( 'w', $unix );
861 $unix = wfTimestamp( TS_UNIX
, $ts );
863 $num = gmdate( 'w', $unix );
867 $unix = wfTimestamp( TS_UNIX
, $ts );
869 $num = gmdate( 'z', $unix );
873 $unix = wfTimestamp( TS_UNIX
, $ts );
875 $num = gmdate( 'W', $unix );
878 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
882 $iranian = self
::tsToIranian( $ts );
884 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
888 $hijri = self
::tsToHijri( $ts );
890 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
894 $hebrew = self
::tsToHebrew( $ts );
896 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
899 $num = substr( $ts, 4, 2 );
902 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
905 $num = intval( substr( $ts, 4, 2 ) );
909 $iranian = self
::tsToIranian( $ts );
915 $hijri = self
::tsToHijri ( $ts );
921 $hebrew = self
::tsToHebrew( $ts );
927 $unix = wfTimestamp( TS_UNIX
, $ts );
929 $num = gmdate( 't', $unix );
933 $hebrew = self
::tsToHebrew( $ts );
939 $unix = wfTimestamp( TS_UNIX
, $ts );
941 $num = gmdate( 'L', $unix );
945 $unix = wfTimestamp( TS_UNIX
, $ts );
947 $num = date( 'o', $unix );
950 $num = substr( $ts, 0, 4 );
954 $iranian = self
::tsToIranian( $ts );
960 $hijri = self
::tsToHijri( $ts );
966 $hebrew = self
::tsToHebrew( $ts );
972 $thai = self
::tsToYear( $ts, 'thai' );
978 $minguo = self
::tsToYear( $ts, 'minguo' );
984 $tenno = self
::tsToYear( $ts, 'tenno' );
989 $num = substr( $ts, 2, 2 );
992 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
995 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
998 $h = substr( $ts, 8, 2 );
999 $num = $h %
12 ?
$h %
12 : 12;
1002 $num = intval( substr( $ts, 8, 2 ) );
1005 $h = substr( $ts, 8, 2 );
1006 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1009 $num = substr( $ts, 8, 2 );
1012 $num = substr( $ts, 10, 2 );
1015 $num = substr( $ts, 12, 2 );
1019 $unix = wfTimestamp( TS_UNIX
, $ts );
1021 $s .= gmdate( 'c', $unix );
1025 $unix = wfTimestamp( TS_UNIX
, $ts );
1027 $s .= gmdate( 'r', $unix );
1031 $unix = wfTimestamp( TS_UNIX
, $ts );
1036 # Backslash escaping
1037 if ( $p < strlen( $format ) - 1 ) {
1038 $s .= $format[++
$p];
1045 if ( $p < strlen( $format ) - 1 ) {
1046 $endQuote = strpos( $format, '"', $p +
1 );
1047 if ( $endQuote === false ) {
1048 # No terminating quote, assume literal "
1051 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1055 # Quote at end of string, assume literal "
1062 if ( $num !== false ) {
1063 if ( $rawToggle ||
$raw ) {
1066 } elseif ( $roman ) {
1067 $s .= self
::romanNumeral( $num );
1069 } elseif ( $hebrewNum ) {
1070 $s .= self
::hebrewNumeral( $num );
1073 $s .= $this->formatNum( $num, true );
1080 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1081 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1083 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1084 * Gregorian dates to Iranian dates. Originally written in C, it
1085 * is released under the terms of GNU Lesser General Public
1086 * License. Conversion to PHP was performed by Niklas Laxström.
1088 * Link: http://www.farsiweb.info/jalali/jalali.c
1090 private static function tsToIranian( $ts ) {
1091 $gy = substr( $ts, 0, 4 ) -1600;
1092 $gm = substr( $ts, 4, 2 ) -1;
1093 $gd = (int)substr( $ts, 6, 2 ) -1;
1095 # Days passed from the beginning (including leap years)
1097 +
floor( ( $gy +
3 ) / 4 )
1098 - floor( ( $gy +
99 ) / 100 )
1099 +
floor( ( $gy +
399 ) / 400 );
1102 // Add days of the past months of this year
1103 for ( $i = 0; $i < $gm; $i++
) {
1104 $gDayNo +
= self
::$GREG_DAYS[$i];
1108 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1112 // Days passed in current month
1115 $jDayNo = $gDayNo - 79;
1117 $jNp = floor( $jDayNo / 12053 );
1120 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1123 if ( $jDayNo >= 366 ) {
1124 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1125 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1128 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1129 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1135 return array( $jy, $jm, $jd );
1139 * Converting Gregorian dates to Hijri dates.
1141 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1143 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1145 private static function tsToHijri( $ts ) {
1146 $year = substr( $ts, 0, 4 );
1147 $month = substr( $ts, 4, 2 );
1148 $day = substr( $ts, 6, 2 );
1156 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1157 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1160 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1161 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1162 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1165 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1166 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1169 $zl = $zjd -1948440 +
10632;
1170 $zn = (int)( ( $zl - 1 ) / 10631 );
1171 $zl = $zl - 10631 * $zn +
354;
1172 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1173 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1174 $zm = (int)( ( 24 * $zl ) / 709 );
1175 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1176 $zy = 30 * $zn +
$zj - 30;
1178 return array( $zy, $zm, $zd );
1182 * Converting Gregorian dates to Hebrew dates.
1184 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1185 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1186 * to translate the relevant functions into PHP and release them under
1189 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1190 * and Adar II is 14. In a non-leap year, Adar is 6.
1192 private static function tsToHebrew( $ts ) {
1194 $year = substr( $ts, 0, 4 );
1195 $month = substr( $ts, 4, 2 );
1196 $day = substr( $ts, 6, 2 );
1198 # Calculate Hebrew year
1199 $hebrewYear = $year +
3760;
1201 # Month number when September = 1, August = 12
1203 if ( $month > 12 ) {
1210 # Calculate day of year from 1 September
1212 for ( $i = 1; $i < $month; $i++
) {
1216 # Check if the year is leap
1217 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1220 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1227 # Calculate the start of the Hebrew year
1228 $start = self
::hebrewYearStart( $hebrewYear );
1230 # Calculate next year's start
1231 if ( $dayOfYear <= $start ) {
1232 # Day is before the start of the year - it is the previous year
1234 $nextStart = $start;
1238 # Add days since previous year's 1 September
1240 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1244 # Start of the new (previous) year
1245 $start = self
::hebrewYearStart( $hebrewYear );
1248 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1251 # Calculate Hebrew day of year
1252 $hebrewDayOfYear = $dayOfYear - $start;
1254 # Difference between year's days
1255 $diff = $nextStart - $start;
1256 # Add 12 (or 13 for leap years) days to ignore the difference between
1257 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1258 # difference is only about the year type
1259 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1265 # Check the year pattern, and is leap year
1266 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1267 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1268 # and non-leap years
1269 $yearPattern = $diff %
30;
1270 # Check if leap year
1271 $isLeap = $diff >= 30;
1273 # Calculate day in the month from number of day in the Hebrew year
1274 # Don't check Adar - if the day is not in Adar, we will stop before;
1275 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1276 $hebrewDay = $hebrewDayOfYear;
1279 while ( $hebrewMonth <= 12 ) {
1280 # Calculate days in this month
1281 if ( $isLeap && $hebrewMonth == 6 ) {
1282 # Adar in a leap year
1284 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1286 if ( $hebrewDay <= $days ) {
1290 # Subtract the days of Adar I
1291 $hebrewDay -= $days;
1294 if ( $hebrewDay <= $days ) {
1300 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1301 # Cheshvan in a complete year (otherwise as the rule below)
1303 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1304 # Kislev in an incomplete year (otherwise as the rule below)
1307 # Odd months have 30 days, even have 29
1308 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1310 if ( $hebrewDay <= $days ) {
1311 # In the current month
1314 # Subtract the days of the current month
1315 $hebrewDay -= $days;
1316 # Try in the next month
1321 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1325 * This calculates the Hebrew year start, as days since 1 September.
1326 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1327 * Used for Hebrew date.
1329 private static function hebrewYearStart( $year ) {
1330 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1331 $b = intval( ( $year - 1 ) %
4 );
1332 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1336 $Mar = intval( $m );
1342 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1343 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1345 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1347 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1351 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1356 * Algorithm to convert Gregorian dates to Thai solar dates,
1357 * Minguo dates or Minguo dates.
1359 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1360 * http://en.wikipedia.org/wiki/Minguo_calendar
1361 * http://en.wikipedia.org/wiki/Japanese_era_name
1363 * @param $ts String: 14-character timestamp
1364 * @param $cName String: calender name
1365 * @return Array: converted year, month, day
1367 private static function tsToYear( $ts, $cName ) {
1368 $gy = substr( $ts, 0, 4 );
1369 $gm = substr( $ts, 4, 2 );
1370 $gd = substr( $ts, 6, 2 );
1372 if ( !strcmp( $cName, 'thai' ) ) {
1374 # Add 543 years to the Gregorian calendar
1375 # Months and days are identical
1376 $gy_offset = $gy +
543;
1377 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1379 # Deduct 1911 years from the Gregorian calendar
1380 # Months and days are identical
1381 $gy_offset = $gy - 1911;
1382 } else if ( !strcmp( $cName, 'tenno' ) ) {
1383 # Nengō dates up to Meiji period
1384 # Deduct years from the Gregorian calendar
1385 # depending on the nengo periods
1386 # Months and days are identical
1387 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1389 $gy_gannen = $gy - 1868 +
1;
1390 $gy_offset = $gy_gannen;
1391 if ( $gy_gannen == 1 ) {
1394 $gy_offset = '明治' . $gy_offset;
1396 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1397 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1398 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1399 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1400 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1404 $gy_gannen = $gy - 1912 +
1;
1405 $gy_offset = $gy_gannen;
1406 if ( $gy_gannen == 1 ) {
1409 $gy_offset = '大正' . $gy_offset;
1411 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1412 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1413 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1417 $gy_gannen = $gy - 1926 +
1;
1418 $gy_offset = $gy_gannen;
1419 if ( $gy_gannen == 1 ) {
1422 $gy_offset = '昭和' . $gy_offset;
1425 $gy_gannen = $gy - 1989 +
1;
1426 $gy_offset = $gy_gannen;
1427 if ( $gy_gannen == 1 ) {
1430 $gy_offset = '平成' . $gy_offset;
1436 return array( $gy_offset, $gm, $gd );
1440 * Roman number formatting up to 3000
1442 static function romanNumeral( $num ) {
1443 static $table = array(
1444 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1445 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1446 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1447 array( '', 'M', 'MM', 'MMM' )
1450 $num = intval( $num );
1451 if ( $num > 3000 ||
$num <= 0 ) {
1456 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1457 if ( $num >= $pow10 ) {
1458 $s .= $table[$i][floor( $num / $pow10 )];
1460 $num = $num %
$pow10;
1466 * Hebrew Gematria number formatting up to 9999
1468 static function hebrewNumeral( $num ) {
1469 static $table = array(
1470 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1471 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1472 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1473 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1476 $num = intval( $num );
1477 if ( $num > 9999 ||
$num <= 0 ) {
1482 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1483 if ( $num >= $pow10 ) {
1484 if ( $num == 15 ||
$num == 16 ) {
1485 $s .= $table[0][9] . $table[0][$num - 9];
1488 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1489 if ( $pow10 == 1000 ) {
1494 $num = $num %
$pow10;
1496 if ( strlen( $s ) == 2 ) {
1499 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1500 $str .= substr( $s, strlen( $s ) - 2, 2 );
1502 $start = substr( $str, 0, strlen( $str ) - 2 );
1503 $end = substr( $str, strlen( $str ) - 2 );
1506 $str = $start . 'ך';
1509 $str = $start . 'ם';
1512 $str = $start . 'ן';
1515 $str = $start . 'ף';
1518 $str = $start . 'ץ';
1525 * This is meant to be used by time(), date(), and timeanddate() to get
1526 * the date preference they're supposed to use, it should be used in
1530 * function timeanddate([...], $format = true) {
1531 * $datePreference = $this->dateFormat($format);
1536 * @param $usePrefs Mixed: if true, the user's preference is used
1537 * if false, the site/language default is used
1538 * if int/string, assumed to be a format.
1541 function dateFormat( $usePrefs = true ) {
1544 if ( is_bool( $usePrefs ) ) {
1546 $datePreference = $wgUser->getDatePreference();
1548 $datePreference = (string)User
::getDefaultOption( 'date' );
1551 $datePreference = (string)$usePrefs;
1555 if ( $datePreference == '' ) {
1559 return $datePreference;
1563 * Get a format string for a given type and preference
1564 * @param $type May be date, time or both
1565 * @param $pref The format name as it appears in Messages*.php
1567 function getDateFormatString( $type, $pref ) {
1568 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1569 if ( $pref == 'default' ) {
1570 $pref = $this->getDefaultDateFormat();
1571 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1573 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1574 if ( is_null( $df ) ) {
1575 $pref = $this->getDefaultDateFormat();
1576 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1579 $this->dateFormatStrings
[$type][$pref] = $df;
1581 return $this->dateFormatStrings
[$type][$pref];
1585 * @param $ts Mixed: the time format which needs to be turned into a
1586 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1587 * @param $adj Bool: whether to adjust the time output according to the
1588 * user configured offset ($timecorrection)
1589 * @param $format Mixed: true to use user's date format preference
1590 * @param $timecorrection String: the time offset as returned by
1591 * validateTimeZone() in Special:Preferences
1594 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1595 $ts = wfTimestamp( TS_MW
, $ts );
1597 $ts = $this->userAdjust( $ts, $timecorrection );
1599 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1600 return $this->sprintfDate( $df, $ts );
1604 * @param $ts Mixed: the time format which needs to be turned into a
1605 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1606 * @param $adj Bool: whether to adjust the time output according to the
1607 * user configured offset ($timecorrection)
1608 * @param $format Mixed: true to use user's date format preference
1609 * @param $timecorrection String: the time offset as returned by
1610 * validateTimeZone() in Special:Preferences
1613 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1614 $ts = wfTimestamp( TS_MW
, $ts );
1616 $ts = $this->userAdjust( $ts, $timecorrection );
1618 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1619 return $this->sprintfDate( $df, $ts );
1623 * @param $ts Mixed: the time format which needs to be turned into a
1624 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1625 * @param $adj Bool: whether to adjust the time output according to the
1626 * user configured offset ($timecorrection)
1627 * @param $format Mixed: what format to return, if it's false output the
1628 * default one (default true)
1629 * @param $timecorrection String: the time offset as returned by
1630 * validateTimeZone() in Special:Preferences
1633 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1634 $ts = wfTimestamp( TS_MW
, $ts );
1636 $ts = $this->userAdjust( $ts, $timecorrection );
1638 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1639 return $this->sprintfDate( $df, $ts );
1642 function getMessage( $key ) {
1643 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1646 function getAllMessages() {
1647 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1650 function iconv( $in, $out, $string ) {
1651 # This is a wrapper for iconv in all languages except esperanto,
1652 # which does some nasty x-conversions beforehand
1654 # Even with //IGNORE iconv can whine about illegal characters in
1655 # *input* string. We just ignore those too.
1656 # REF: http://bugs.php.net/bug.php?id=37166
1657 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1658 wfSuppressWarnings();
1659 $text = iconv( $in, $out . '//IGNORE', $string );
1660 wfRestoreWarnings();
1664 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1665 function ucwordbreaksCallbackAscii( $matches ) {
1666 return $this->ucfirst( $matches[1] );
1669 function ucwordbreaksCallbackMB( $matches ) {
1670 return mb_strtoupper( $matches[0] );
1673 function ucCallback( $matches ) {
1674 list( $wikiUpperChars ) = self
::getCaseMaps();
1675 return strtr( $matches[1], $wikiUpperChars );
1678 function lcCallback( $matches ) {
1679 list( , $wikiLowerChars ) = self
::getCaseMaps();
1680 return strtr( $matches[1], $wikiLowerChars );
1683 function ucwordsCallbackMB( $matches ) {
1684 return mb_strtoupper( $matches[0] );
1687 function ucwordsCallbackWiki( $matches ) {
1688 list( $wikiUpperChars ) = self
::getCaseMaps();
1689 return strtr( $matches[0], $wikiUpperChars );
1693 * Make a string's first character uppercase
1695 function ucfirst( $str ) {
1697 if ( $o < 96 ) { // if already uppercase...
1699 } elseif ( $o < 128 ) {
1700 return ucfirst( $str ); // use PHP's ucfirst()
1702 // fall back to more complex logic in case of multibyte strings
1703 return $this->uc( $str, true );
1708 * Convert a string to uppercase
1710 function uc( $str, $first = false ) {
1711 if ( function_exists( 'mb_strtoupper' ) ) {
1713 if ( $this->isMultibyte( $str ) ) {
1714 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1716 return ucfirst( $str );
1719 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1722 if ( $this->isMultibyte( $str ) ) {
1723 $x = $first ?
'^' : '';
1724 return preg_replace_callback(
1725 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1726 array( $this, 'ucCallback' ),
1730 return $first ?
ucfirst( $str ) : strtoupper( $str );
1735 function lcfirst( $str ) {
1738 return strval( $str );
1739 } elseif ( $o >= 128 ) {
1740 return $this->lc( $str, true );
1741 } elseif ( $o > 96 ) {
1744 $str[0] = strtolower( $str[0] );
1749 function lc( $str, $first = false ) {
1750 if ( function_exists( 'mb_strtolower' ) ) {
1752 if ( $this->isMultibyte( $str ) ) {
1753 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1755 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1758 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1761 if ( $this->isMultibyte( $str ) ) {
1762 $x = $first ?
'^' : '';
1763 return preg_replace_callback(
1764 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1765 array( $this, 'lcCallback' ),
1769 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1774 function isMultibyte( $str ) {
1775 return (bool)preg_match( '/[\x80-\xff]/', $str );
1778 function ucwords( $str ) {
1779 if ( $this->isMultibyte( $str ) ) {
1780 $str = $this->lc( $str );
1782 // regexp to find first letter in each word (i.e. after each space)
1783 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1785 // function to use to capitalize a single char
1786 if ( function_exists( 'mb_strtoupper' ) ) {
1787 return preg_replace_callback(
1789 array( $this, 'ucwordsCallbackMB' ),
1793 return preg_replace_callback(
1795 array( $this, 'ucwordsCallbackWiki' ),
1800 return ucwords( strtolower( $str ) );
1804 # capitalize words at word breaks
1805 function ucwordbreaks( $str ) {
1806 if ( $this->isMultibyte( $str ) ) {
1807 $str = $this->lc( $str );
1809 // since \b doesn't work for UTF-8, we explicitely define word break chars
1810 $breaks = "[ \-\(\)\}\{\.,\?!]";
1812 // find first letter after word break
1813 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1815 if ( function_exists( 'mb_strtoupper' ) ) {
1816 return preg_replace_callback(
1818 array( $this, 'ucwordbreaksCallbackMB' ),
1822 return preg_replace_callback(
1824 array( $this, 'ucwordsCallbackWiki' ),
1829 return preg_replace_callback(
1830 '/\b([\w\x80-\xff]+)\b/',
1831 array( $this, 'ucwordbreaksCallbackAscii' ),
1838 * Return a case-folded representation of $s
1840 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1841 * and $s2 are the same except for the case of their characters. It is not
1842 * necessary for the value returned to make sense when displayed.
1844 * Do *not* perform any other normalisation in this function. If a caller
1845 * uses this function when it should be using a more general normalisation
1846 * function, then fix the caller.
1848 function caseFold( $s ) {
1849 return $this->uc( $s );
1852 function checkTitleEncoding( $s ) {
1853 if ( is_array( $s ) ) {
1854 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1856 # Check for non-UTF-8 URLs
1857 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1862 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1863 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1868 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1871 function fallback8bitEncoding() {
1872 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1876 * Most writing systems use whitespace to break up words.
1877 * Some languages such as Chinese don't conventionally do this,
1878 * which requires special handling when breaking up words for
1881 function hasWordBreaks() {
1886 * Some languages such as Chinese require word segmentation,
1887 * Specify such segmentation when overridden in derived class.
1889 * @param $string String
1892 function segmentByWord( $string ) {
1897 * Some languages have special punctuation need to be normalized.
1898 * Make such changes here.
1900 * @param $string String
1903 function normalizeForSearch( $string ) {
1904 return self
::convertDoubleWidth( $string );
1908 * convert double-width roman characters to single-width.
1909 * range: ff00-ff5f ~= 0020-007f
1911 protected static function convertDoubleWidth( $string ) {
1912 static $full = null;
1913 static $half = null;
1915 if ( $full === null ) {
1916 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1917 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1918 $full = str_split( $fullWidth, 3 );
1919 $half = str_split( $halfWidth );
1922 $string = str_replace( $full, $half, $string );
1926 protected static function insertSpace( $string, $pattern ) {
1927 $string = preg_replace( $pattern, " $1 ", $string );
1928 $string = preg_replace( '/ +/', ' ', $string );
1932 function convertForSearchResult( $termsArray ) {
1933 # some languages, e.g. Chinese, need to do a conversion
1934 # in order for search results to be displayed correctly
1939 * Get the first character of a string.
1944 function firstChar( $s ) {
1947 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1948 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1953 if ( isset( $matches[1] ) ) {
1954 if ( strlen( $matches[1] ) != 3 ) {
1958 // Break down Hangul syllables to grab the first jamo
1959 $code = utf8ToCodepoint( $matches[1] );
1960 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1962 } elseif ( $code < 0xb098 ) {
1963 return "\xe3\x84\xb1";
1964 } elseif ( $code < 0xb2e4 ) {
1965 return "\xe3\x84\xb4";
1966 } elseif ( $code < 0xb77c ) {
1967 return "\xe3\x84\xb7";
1968 } elseif ( $code < 0xb9c8 ) {
1969 return "\xe3\x84\xb9";
1970 } elseif ( $code < 0xbc14 ) {
1971 return "\xe3\x85\x81";
1972 } elseif ( $code < 0xc0ac ) {
1973 return "\xe3\x85\x82";
1974 } elseif ( $code < 0xc544 ) {
1975 return "\xe3\x85\x85";
1976 } elseif ( $code < 0xc790 ) {
1977 return "\xe3\x85\x87";
1978 } elseif ( $code < 0xcc28 ) {
1979 return "\xe3\x85\x88";
1980 } elseif ( $code < 0xce74 ) {
1981 return "\xe3\x85\x8a";
1982 } elseif ( $code < 0xd0c0 ) {
1983 return "\xe3\x85\x8b";
1984 } elseif ( $code < 0xd30c ) {
1985 return "\xe3\x85\x8c";
1986 } elseif ( $code < 0xd558 ) {
1987 return "\xe3\x85\x8d";
1989 return "\xe3\x85\x8e";
1996 function initEncoding() {
1997 # Some languages may have an alternate char encoding option
1998 # (Esperanto X-coding, Japanese furigana conversion, etc)
1999 # If this language is used as the primary content language,
2000 # an override to the defaults can be set here on startup.
2003 function recodeForEdit( $s ) {
2004 # For some languages we'll want to explicitly specify
2005 # which characters make it into the edit box raw
2006 # or are converted in some way or another.
2007 # Note that if wgOutputEncoding is different from
2008 # wgInputEncoding, this text will be further converted
2009 # to wgOutputEncoding.
2010 global $wgEditEncoding;
2011 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2014 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2018 function recodeInput( $s ) {
2019 # Take the previous into account.
2020 global $wgEditEncoding;
2021 if ( $wgEditEncoding != '' ) {
2022 $enc = $wgEditEncoding;
2026 if ( $enc == 'UTF-8' ) {
2029 return $this->iconv( $enc, 'UTF-8', $s );
2034 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2035 * also cleans up certain backwards-compatible sequences, converting them
2036 * to the modern Unicode equivalent.
2038 * This is language-specific for performance reasons only.
2040 function normalize( $s ) {
2041 global $wgAllUnicodeFixes;
2042 $s = UtfNormal
::cleanUp( $s );
2043 if ( $wgAllUnicodeFixes ) {
2044 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2045 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2052 * Transform a string using serialized data stored in the given file (which
2053 * must be in the serialized subdirectory of $IP). The file contains pairs
2054 * mapping source characters to destination characters.
2056 * The data is cached in process memory. This will go faster if you have the
2057 * FastStringSearch extension.
2059 function transformUsingPairFile( $file, $string ) {
2060 if ( !isset( $this->transformData
[$file] ) ) {
2061 $data = wfGetPrecompiledData( $file );
2062 if ( $data === false ) {
2063 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2065 $this->transformData
[$file] = new ReplacementArray( $data );
2067 return $this->transformData
[$file]->replace( $string );
2071 * For right-to-left language support
2076 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2080 * Return the correct HTML 'dir' attribute value for this language.
2084 return $this->isRTL() ?
'rtl' : 'ltr';
2088 * Return 'left' or 'right' as appropriate alignment for line-start
2089 * for this language's text direction.
2091 * Should be equivalent to CSS3 'start' text-align value....
2095 function alignStart() {
2096 return $this->isRTL() ?
'right' : 'left';
2100 * Return 'right' or 'left' as appropriate alignment for line-end
2101 * for this language's text direction.
2103 * Should be equivalent to CSS3 'end' text-align value....
2107 function alignEnd() {
2108 return $this->isRTL() ?
'left' : 'right';
2112 * A hidden direction mark (LRM or RLM), depending on the language direction
2116 function getDirMark() {
2117 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2120 function capitalizeAllNouns() {
2121 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2125 * An arrow, depending on the language direction
2129 function getArrow() {
2130 return $this->isRTL() ?
'←' : '→';
2134 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2138 function linkPrefixExtension() {
2139 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2142 function getMagicWords() {
2143 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2146 protected function doMagicHook() {
2147 if ( $this->mMagicHookDone
) {
2150 $this->mMagicHookDone
= true;
2151 wfProfileIn( 'LanguageGetMagic' );
2152 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2153 wfProfileOut( 'LanguageGetMagic' );
2156 # Fill a MagicWord object with data from here
2157 function getMagic( $mw ) {
2158 $this->doMagicHook();
2160 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2161 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2163 $magicWords = $this->getMagicWords();
2164 if ( isset( $magicWords[$mw->mId
] ) ) {
2165 $rawEntry = $magicWords[$mw->mId
];
2171 if ( !is_array( $rawEntry ) ) {
2172 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2174 $mw->mCaseSensitive
= $rawEntry[0];
2175 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2180 * Add magic words to the extension array
2182 function addMagicWordsByLang( $newWords ) {
2183 $code = $this->getCode();
2184 $fallbackChain = array();
2185 while ( $code && !in_array( $code, $fallbackChain ) ) {
2186 $fallbackChain[] = $code;
2187 $code = self
::getFallbackFor( $code );
2189 if ( !in_array( 'en', $fallbackChain ) ) {
2190 $fallbackChain[] = 'en';
2192 $fallbackChain = array_reverse( $fallbackChain );
2193 foreach ( $fallbackChain as $code ) {
2194 if ( isset( $newWords[$code] ) ) {
2195 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2201 * Get special page names, as an associative array
2202 * case folded alias => real name
2204 function getSpecialPageAliases() {
2205 // Cache aliases because it may be slow to load them
2206 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2208 $this->mExtendedSpecialPageAliases
=
2209 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2210 wfRunHooks( 'LanguageGetSpecialPageAliases',
2211 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2214 return $this->mExtendedSpecialPageAliases
;
2218 * Italic is unsuitable for some languages
2220 * @param $text String: the text to be emphasized.
2223 function emphasize( $text ) {
2224 return "<em>$text</em>";
2228 * Normally we output all numbers in plain en_US style, that is
2229 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2230 * point twohundredthirtyfive. However this is not sutable for all
2231 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2232 * Icelandic just want to use commas instead of dots, and dots instead
2233 * of commas like "293.291,235".
2235 * An example of this function being called:
2237 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2240 * See LanguageGu.php for the Gujarati implementation and
2241 * $separatorTransformTable on MessageIs.php for
2242 * the , => . and . => , implementation.
2244 * @todo check if it's viable to use localeconv() for the decimal
2246 * @param $number Mixed: the string to be formatted, should be an integer
2247 * or a floating point number.
2248 * @param $nocommafy Bool: set to true for special numbers like dates
2251 function formatNum( $number, $nocommafy = false ) {
2252 global $wgTranslateNumerals;
2253 if ( !$nocommafy ) {
2254 $number = $this->commafy( $number );
2255 $s = $this->separatorTransformTable();
2257 $number = strtr( $number, $s );
2261 if ( $wgTranslateNumerals ) {
2262 $s = $this->digitTransformTable();
2264 $number = strtr( $number, $s );
2271 function parseFormattedNumber( $number ) {
2272 $s = $this->digitTransformTable();
2274 $number = strtr( $number, array_flip( $s ) );
2277 $s = $this->separatorTransformTable();
2279 $number = strtr( $number, array_flip( $s ) );
2282 $number = strtr( $number, array( ',' => '' ) );
2287 * Adds commas to a given number
2292 function commafy( $_ ) {
2293 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2296 function digitTransformTable() {
2297 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2300 function separatorTransformTable() {
2301 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2305 * Take a list of strings and build a locale-friendly comma-separated
2306 * list, using the local comma-separator message.
2307 * The last two strings are chained with an "and".
2312 function listToText( $l ) {
2314 $m = count( $l ) - 1;
2316 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2318 for ( $i = $m; $i >= 0; $i-- ) {
2321 } else if ( $i == $m - 1 ) {
2322 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2324 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2332 * Take a list of strings and build a locale-friendly comma-separated
2333 * list, using the local comma-separator message.
2334 * @param $list array of strings to put in a comma list
2337 function commaList( $list ) {
2342 array( 'parsemag', 'escapenoentities', 'language' => $this )
2348 * Take a list of strings and build a locale-friendly semicolon-separated
2349 * list, using the local semicolon-separator message.
2350 * @param $list array of strings to put in a semicolon list
2353 function semicolonList( $list ) {
2357 'semicolon-separator',
2358 array( 'parsemag', 'escapenoentities', 'language' => $this )
2364 * Same as commaList, but separate it with the pipe instead.
2365 * @param $list array of strings to put in a pipe list
2368 function pipeList( $list ) {
2373 array( 'escapenoentities', 'language' => $this )
2379 * Truncate a string to a specified length in bytes, appending an optional
2380 * string (e.g. for ellipses)
2382 * The database offers limited byte lengths for some columns in the database;
2383 * multi-byte character sets mean we need to ensure that only whole characters
2384 * are included, otherwise broken characters can be passed to the user
2386 * If $length is negative, the string will be truncated from the beginning
2388 * @param $string String to truncate
2389 * @param $length Int: maximum length (including ellipses)
2390 * @param $ellipsis String to append to the truncated text
2391 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2392 * $adjustLength was introduced in 1.18, before that behaved as if false.
2395 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2396 # Use the localized ellipsis character
2397 if ( $ellipsis == '...' ) {
2398 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2400 # Check if there is no need to truncate
2401 if ( $length == 0 ) {
2402 return $ellipsis; // convention
2403 } elseif ( strlen( $string ) <= abs( $length ) ) {
2404 return $string; // no need to truncate
2406 $stringOriginal = $string;
2407 # If ellipsis length is >= $length then we can't apply $adjustLength
2408 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2409 $string = $ellipsis; // this can be slightly unexpected
2410 # Otherwise, truncate and add ellipsis...
2412 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2413 if ( $length > 0 ) {
2414 $length -= $eLength;
2415 $string = substr( $string, 0, $length ); // xyz...
2416 $string = $this->removeBadCharLast( $string );
2417 $string = $string . $ellipsis;
2419 $length +
= $eLength;
2420 $string = substr( $string, $length ); // ...xyz
2421 $string = $this->removeBadCharFirst( $string );
2422 $string = $ellipsis . $string;
2425 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2426 # This check is *not* redundant if $adjustLength, due to the single case where
2427 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2428 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2431 return $stringOriginal;
2436 * Remove bytes that represent an incomplete Unicode character
2437 * at the end of string (e.g. bytes of the char are missing)
2439 * @param $string String
2442 protected function removeBadCharLast( $string ) {
2443 if ( $string != '' ) {
2444 $char = ord( $string[strlen( $string ) - 1] );
2446 if ( $char >= 0xc0 ) {
2447 # We got the first byte only of a multibyte char; remove it.
2448 $string = substr( $string, 0, -1 );
2449 } elseif ( $char >= 0x80 &&
2450 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2451 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2453 # We chopped in the middle of a character; remove it
2461 * Remove bytes that represent an incomplete Unicode character
2462 * at the start of string (e.g. bytes of the char are missing)
2464 * @param $string String
2467 protected function removeBadCharFirst( $string ) {
2468 if ( $string != '' ) {
2469 $char = ord( $string[0] );
2470 if ( $char >= 0x80 && $char < 0xc0 ) {
2471 # We chopped in the middle of a character; remove the whole thing
2472 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2479 * Truncate a string of valid HTML to a specified length in bytes,
2480 * appending an optional string (e.g. for ellipses), and return valid HTML
2482 * This is only intended for styled/linked text, such as HTML with
2483 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2484 * Also, this will not detect things like "display:none" CSS.
2486 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2488 * @param string $text HTML string to truncate
2489 * @param int $length (zero/positive) Maximum length (including ellipses)
2490 * @param string $ellipsis String to append to the truncated text
2493 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2494 # Use the localized ellipsis character
2495 if ( $ellipsis == '...' ) {
2496 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2498 # Check if there is clearly no need to truncate
2499 if ( $length <= 0 ) {
2500 return $ellipsis; // no text shown, nothing to format (convention)
2501 } elseif ( strlen( $text ) <= $length ) {
2502 return $text; // string short enough even *with* HTML (short-circuit)
2505 $displayLen = 0; // innerHTML legth so far
2506 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2507 $tagType = 0; // 0-open, 1-close
2508 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2509 $entityState = 0; // 0-not entity, 1-entity
2510 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2511 $openTags = array(); // open tag stack
2512 $pOpenTags = array();
2514 $textLen = strlen( $text );
2515 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2516 for ( $pos = 0; true; ++
$pos ) {
2517 # Consider truncation once the display length has reached the maximim.
2518 # Check that we're not in the middle of a bracket/entity...
2519 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2520 if ( !$testingEllipsis ) {
2521 $testingEllipsis = true;
2522 # Save where we are; we will truncate here unless there turn out to
2523 # be so few remaining characters that truncation is not necessary.
2524 $pOpenTags = $openTags; // save state
2525 $pRet = $ret; // save state
2526 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2527 # String in fact does need truncation, the truncation point was OK.
2528 $openTags = $pOpenTags; // reload state
2529 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2530 $ret .= $ellipsis; // add ellipsis
2534 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2536 # Read the next char...
2538 $lastCh = $pos ?
$text[$pos - 1] : '';
2539 $ret .= $ch; // add to result string
2541 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2542 $entityState = 0; // for bad HTML
2543 $bracketState = 1; // tag started (checking for backslash)
2544 } elseif ( $ch == '>' ) {
2545 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2546 $entityState = 0; // for bad HTML
2547 $bracketState = 0; // out of brackets
2548 } elseif ( $bracketState == 1 ) {
2550 $tagType = 1; // close tag (e.g. "</span>")
2552 $tagType = 0; // open tag (e.g. "<span>")
2555 $bracketState = 2; // building tag name
2556 } elseif ( $bracketState == 2 ) {
2560 // Name found (e.g. "<a href=..."), add on tag attributes...
2561 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2563 } elseif ( $bracketState == 0 ) {
2564 if ( $entityState ) {
2567 $displayLen++
; // entity is one displayed char
2571 $entityState = 1; // entity found, (e.g. " ")
2573 $displayLen++
; // this char is displayed
2574 // Add the next $max display text chars after this in one swoop...
2575 $max = ( $testingEllipsis ?
$length : $neLength ) - $displayLen;
2576 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2577 $displayLen +
= $skipped;
2583 if ( $displayLen == 0 ) {
2584 return ''; // no text shown, nothing to format
2586 // Close the last tag if left unclosed by bad HTML
2587 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2588 while ( count( $openTags ) > 0 ) {
2589 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2594 // truncateHtml() helper function
2595 // like strcspn() but adds the skipped chars to $ret
2596 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2597 if ( $len === null ) {
2598 $len = -1; // -1 means "no limit" for strcspn
2599 } elseif ( $len < 0 ) {
2603 if ( $start < strlen( $text ) ) {
2604 $skipCount = strcspn( $text, $search, $start, $len );
2605 $ret .= substr( $text, $start, $skipCount );
2611 * truncateHtml() helper function
2612 * (a) push or pop $tag from $openTags as needed
2613 * (b) clear $tag value
2614 * @param String &$tag Current HTML tag name we are looking at
2615 * @param int $tagType (0-open tag, 1-close tag)
2616 * @param char $lastCh Character before the '>' that ended this tag
2617 * @param array &$openTags Open tag stack (not accounting for $tag)
2619 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2620 $tag = ltrim( $tag );
2622 if ( $tagType == 0 && $lastCh != '/' ) {
2623 $openTags[] = $tag; // tag opened (didn't close itself)
2624 } else if ( $tagType == 1 ) {
2625 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2626 array_pop( $openTags ); // tag closed
2634 * Grammatical transformations, needed for inflected languages
2635 * Invoked by putting {{grammar:case|word}} in a message
2637 * @param $word string
2638 * @param $case string
2641 function convertGrammar( $word, $case ) {
2642 global $wgGrammarForms;
2643 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2644 return $wgGrammarForms[$this->getCode()][$case][$word];
2650 * Provides an alternative text depending on specified gender.
2651 * Usage {{gender:username|masculine|feminine|neutral}}.
2652 * username is optional, in which case the gender of current user is used,
2653 * but only in (some) interface messages; otherwise default gender is used.
2654 * If second or third parameter are not specified, masculine is used.
2655 * These details may be overriden per language.
2657 function gender( $gender, $forms ) {
2658 if ( !count( $forms ) ) {
2661 $forms = $this->preConvertPlural( $forms, 2 );
2662 if ( $gender === 'male' ) {
2665 if ( $gender === 'female' ) {
2668 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2672 * Plural form transformations, needed for some languages.
2673 * For example, there are 3 form of plural in Russian and Polish,
2674 * depending on "count mod 10". See [[w:Plural]]
2675 * For English it is pretty simple.
2677 * Invoked by putting {{plural:count|wordform1|wordform2}}
2678 * or {{plural:count|wordform1|wordform2|wordform3}}
2680 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2682 * @param $count Integer: non-localized number
2683 * @param $forms Array: different plural forms
2684 * @return string Correct form of plural for $count in this language
2686 function convertPlural( $count, $forms ) {
2687 if ( !count( $forms ) ) {
2690 $forms = $this->preConvertPlural( $forms, 2 );
2692 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2696 * Checks that convertPlural was given an array and pads it to requested
2697 * amound of forms by copying the last one.
2699 * @param $count Integer: How many forms should there be at least
2700 * @param $forms Array of forms given to convertPlural
2701 * @return array Padded array of forms or an exception if not an array
2703 protected function preConvertPlural( /* Array */ $forms, $count ) {
2704 while ( count( $forms ) < $count ) {
2705 $forms[] = $forms[count( $forms ) - 1];
2711 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2712 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2713 * (which is an absolute timestamp).
2714 * @param $str String: the validated block duration in English
2715 * @return Somehow translated block duration
2716 * @see LanguageFi.php for example implementation
2718 function translateBlockExpiry( $str ) {
2719 foreach( SpecialBlock
::getSuggestedDurations( $this ) as $show => $value ){
2720 if ( strcmp( $str, $value ) == 0 ) {
2721 return htmlspecialchars( trim( $show ) );
2728 * languages like Chinese need to be segmented in order for the diff
2731 * @param $text String
2734 function segmentForDiff( $text ) {
2739 * and unsegment to show the result
2741 * @param $text String
2744 function unsegmentForDiff( $text ) {
2748 # convert text to all supported variants
2749 function autoConvertToAllVariants( $text ) {
2750 return $this->mConverter
->autoConvertToAllVariants( $text );
2753 # convert text to different variants of a language.
2754 function convert( $text ) {
2755 return $this->mConverter
->convert( $text );
2758 # Convert a Title object to a string in the preferred variant
2759 function convertTitle( $title ) {
2760 return $this->mConverter
->convertTitle( $title );
2763 # Check if this is a language with variants
2764 function hasVariants() {
2765 return sizeof( $this->getVariants() ) > 1;
2768 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2769 function armourMath( $text ) {
2770 return $this->mConverter
->armourMath( $text );
2774 * Perform output conversion on a string, and encode for safe HTML output.
2775 * @param $text String text to be converted
2776 * @param $isTitle Bool whether this conversion is for the article title
2778 * @todo this should get integrated somewhere sane
2780 function convertHtml( $text, $isTitle = false ) {
2781 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2784 function convertCategoryKey( $key ) {
2785 return $this->mConverter
->convertCategoryKey( $key );
2789 * Get the list of variants supported by this language
2790 * see sample implementation in LanguageZh.php
2792 * @return array an array of language codes
2794 function getVariants() {
2795 return $this->mConverter
->getVariants();
2798 function getPreferredVariant() {
2799 return $this->mConverter
->getPreferredVariant();
2802 function getDefaultVariant() {
2803 return $this->mConverter
->getDefaultVariant();
2806 function getURLVariant() {
2807 return $this->mConverter
->getURLVariant();
2811 * If a language supports multiple variants, it is
2812 * possible that non-existing link in one variant
2813 * actually exists in another variant. this function
2814 * tries to find it. See e.g. LanguageZh.php
2816 * @param $link String: the name of the link
2817 * @param $nt Mixed: the title object of the link
2818 * @param $ignoreOtherCond Boolean: to disable other conditions when
2819 * we need to transclude a template or update a category's link
2820 * @return null the input parameters may be modified upon return
2822 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2823 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2827 * If a language supports multiple variants, converts text
2828 * into an array of all possible variants of the text:
2829 * 'variant' => text in that variant
2831 * @deprecated Use autoConvertToAllVariants()
2833 function convertLinkToAllVariants( $text ) {
2834 return $this->mConverter
->convertLinkToAllVariants( $text );
2838 * returns language specific options used by User::getPageRenderHash()
2839 * for example, the preferred language variant
2843 function getExtraHashOptions() {
2844 return $this->mConverter
->getExtraHashOptions();
2848 * For languages that support multiple variants, the title of an
2849 * article may be displayed differently in different variants. this
2850 * function returns the apporiate title defined in the body of the article.
2854 function getParsedTitle() {
2855 return $this->mConverter
->getParsedTitle();
2859 * Enclose a string with the "no conversion" tag. This is used by
2860 * various functions in the Parser
2862 * @param $text String: text to be tagged for no conversion
2864 * @return string the tagged text
2866 function markNoConversion( $text, $noParse = false ) {
2867 return $this->mConverter
->markNoConversion( $text, $noParse );
2871 * A regular expression to match legal word-trailing characters
2872 * which should be merged onto a link of the form [[foo]]bar.
2876 function linkTrail() {
2877 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2880 function getLangObj() {
2885 * Get the RFC 3066 code for this language object
2887 function getCode() {
2888 return $this->mCode
;
2891 function setCode( $code ) {
2892 $this->mCode
= $code;
2896 * Get the name of a file for a certain language code
2897 * @param $prefix string Prepend this to the filename
2898 * @param $code string Language code
2899 * @param $suffix string Append this to the filename
2900 * @return string $prefix . $mangledCode . $suffix
2902 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2903 // Protect against path traversal
2904 if ( !Language
::isValidCode( $code )
2905 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2907 throw new MWException( "Invalid language code \"$code\"" );
2910 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2914 * Get the language code from a file name. Inverse of getFileName()
2915 * @param $filename string $prefix . $languageCode . $suffix
2916 * @param $prefix string Prefix before the language code
2917 * @param $suffix string Suffix after the language code
2918 * @return Language code, or false if $prefix or $suffix isn't found
2920 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2922 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2923 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2924 if ( !count( $m ) ) {
2927 return str_replace( '_', '-', strtolower( $m[1] ) );
2930 static function getMessagesFileName( $code ) {
2932 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2935 static function getClassFileName( $code ) {
2937 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2941 * Get the fallback for a given language
2943 static function getFallbackFor( $code ) {
2944 if ( $code === 'en' ) {
2948 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2953 * Get all messages for a given language
2954 * WARNING: this may take a long time
2956 static function getMessagesFor( $code ) {
2957 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2961 * Get a message for a given language
2963 static function getMessageFor( $key, $code ) {
2964 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2967 function fixVariableInNamespace( $talk ) {
2968 if ( strpos( $talk, '$1' ) === false ) {
2972 global $wgMetaNamespace;
2973 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2975 # Allow grammar transformations
2976 # Allowing full message-style parsing would make simple requests
2977 # such as action=raw much more expensive than they need to be.
2978 # This will hopefully cover most cases.
2979 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2980 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2981 return str_replace( ' ', '_', $talk );
2984 function replaceGrammarInNamespace( $m ) {
2985 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2988 static function getCaseMaps() {
2989 static $wikiUpperChars, $wikiLowerChars;
2990 if ( isset( $wikiUpperChars ) ) {
2991 return array( $wikiUpperChars, $wikiLowerChars );
2994 wfProfileIn( __METHOD__
);
2995 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2996 if ( $arr === false ) {
2997 throw new MWException(
2998 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3000 $wikiUpperChars = $arr['wikiUpperChars'];
3001 $wikiLowerChars = $arr['wikiLowerChars'];
3002 wfProfileOut( __METHOD__
);
3003 return array( $wikiUpperChars, $wikiLowerChars );
3007 * Decode an expiry (block, protection, etc) which has come from the DB
3009 * @param $expiry String: Database expiry String
3010 * @param $format Bool|Int true to process using language functions, or TS_ constant
3011 * to return the expiry in a given timestamp
3014 public function formatExpiry( $expiry, $format = true ) {
3015 static $infinity, $infinityMsg;
3016 if( $infinity === null ){
3017 $infinityMsg = wfMessage( 'infiniteblock' );
3018 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3021 if ( $expiry == '' ||
$expiry == $infinity ) {
3022 return $format === true
3026 return $format === true
3027 ?
$this->timeanddate( $expiry )
3028 : wfTimestamp( $format, $expiry );
3034 * @param $seconds String
3037 function formatTimePeriod( $seconds ) {
3038 if ( round( $seconds * 10 ) < 100 ) {
3039 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3040 } elseif ( round( $seconds ) < 60 ) {
3041 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3042 } elseif ( round( $seconds ) < 3600 ) {
3043 $minutes = floor( $seconds / 60 );
3044 $secondsPart = round( fmod( $seconds, 60 ) );
3045 if ( $secondsPart == 60 ) {
3049 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3050 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3052 $hours = floor( $seconds / 3600 );
3053 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3054 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3055 if ( $secondsPart == 60 ) {
3059 if ( $minutes == 60 ) {
3063 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3064 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3065 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3069 function formatBitrate( $bps ) {
3070 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3072 return $this->formatNum( $bps ) . $units[0];
3074 $unitIndex = floor( log10( $bps ) / 3 );
3075 $mantissa = $bps / pow( 1000, $unitIndex );
3076 if ( $mantissa < 10 ) {
3077 $mantissa = round( $mantissa, 1 );
3079 $mantissa = round( $mantissa );
3081 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3085 * Format a size in bytes for output, using an appropriate
3086 * unit (B, KB, MB or GB) according to the magnitude in question
3088 * @param $size Size to format
3089 * @return string Plain text (not HTML)
3091 function formatSize( $size ) {
3092 // For small sizes no decimal places necessary
3094 if ( $size > 1024 ) {
3095 $size = $size / 1024;
3096 if ( $size > 1024 ) {
3097 $size = $size / 1024;
3098 // For MB and bigger two decimal places are smarter
3100 if ( $size > 1024 ) {
3101 $size = $size / 1024;
3102 $msg = 'size-gigabytes';
3104 $msg = 'size-megabytes';
3107 $msg = 'size-kilobytes';
3110 $msg = 'size-bytes';
3112 $size = round( $size, $round );
3113 $text = $this->getMessageFromDB( $msg );
3114 return str_replace( '$1', $this->formatNum( $size ), $text );
3118 * Get the conversion rule title, if any.
3120 function getConvRuleTitle() {
3121 return $this->mConverter
->getConvRuleTitle();