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 = ( $s == iconv("UTF-8","UTF-8//IGNORE", $s));
1867 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1870 function fallback8bitEncoding() {
1871 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1875 * Most writing systems use whitespace to break up words.
1876 * Some languages such as Chinese don't conventionally do this,
1877 * which requires special handling when breaking up words for
1880 function hasWordBreaks() {
1885 * Some languages such as Chinese require word segmentation,
1886 * Specify such segmentation when overridden in derived class.
1888 * @param $string String
1891 function segmentByWord( $string ) {
1896 * Some languages have special punctuation need to be normalized.
1897 * Make such changes here.
1899 * @param $string String
1902 function normalizeForSearch( $string ) {
1903 return self
::convertDoubleWidth( $string );
1907 * convert double-width roman characters to single-width.
1908 * range: ff00-ff5f ~= 0020-007f
1910 protected static function convertDoubleWidth( $string ) {
1911 static $full = null;
1912 static $half = null;
1914 if ( $full === null ) {
1915 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1916 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1917 $full = str_split( $fullWidth, 3 );
1918 $half = str_split( $halfWidth );
1921 $string = str_replace( $full, $half, $string );
1925 protected static function insertSpace( $string, $pattern ) {
1926 $string = preg_replace( $pattern, " $1 ", $string );
1927 $string = preg_replace( '/ +/', ' ', $string );
1931 function convertForSearchResult( $termsArray ) {
1932 # some languages, e.g. Chinese, need to do a conversion
1933 # in order for search results to be displayed correctly
1938 * Get the first character of a string.
1943 function firstChar( $s ) {
1946 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1947 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1952 if ( isset( $matches[1] ) ) {
1953 if ( strlen( $matches[1] ) != 3 ) {
1957 // Break down Hangul syllables to grab the first jamo
1958 $code = utf8ToCodepoint( $matches[1] );
1959 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1961 } elseif ( $code < 0xb098 ) {
1962 return "\xe3\x84\xb1";
1963 } elseif ( $code < 0xb2e4 ) {
1964 return "\xe3\x84\xb4";
1965 } elseif ( $code < 0xb77c ) {
1966 return "\xe3\x84\xb7";
1967 } elseif ( $code < 0xb9c8 ) {
1968 return "\xe3\x84\xb9";
1969 } elseif ( $code < 0xbc14 ) {
1970 return "\xe3\x85\x81";
1971 } elseif ( $code < 0xc0ac ) {
1972 return "\xe3\x85\x82";
1973 } elseif ( $code < 0xc544 ) {
1974 return "\xe3\x85\x85";
1975 } elseif ( $code < 0xc790 ) {
1976 return "\xe3\x85\x87";
1977 } elseif ( $code < 0xcc28 ) {
1978 return "\xe3\x85\x88";
1979 } elseif ( $code < 0xce74 ) {
1980 return "\xe3\x85\x8a";
1981 } elseif ( $code < 0xd0c0 ) {
1982 return "\xe3\x85\x8b";
1983 } elseif ( $code < 0xd30c ) {
1984 return "\xe3\x85\x8c";
1985 } elseif ( $code < 0xd558 ) {
1986 return "\xe3\x85\x8d";
1988 return "\xe3\x85\x8e";
1995 function initEncoding() {
1996 # Some languages may have an alternate char encoding option
1997 # (Esperanto X-coding, Japanese furigana conversion, etc)
1998 # If this language is used as the primary content language,
1999 # an override to the defaults can be set here on startup.
2002 function recodeForEdit( $s ) {
2003 # For some languages we'll want to explicitly specify
2004 # which characters make it into the edit box raw
2005 # or are converted in some way or another.
2006 # Note that if wgOutputEncoding is different from
2007 # wgInputEncoding, this text will be further converted
2008 # to wgOutputEncoding.
2009 global $wgEditEncoding;
2010 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2013 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2017 function recodeInput( $s ) {
2018 # Take the previous into account.
2019 global $wgEditEncoding;
2020 if ( $wgEditEncoding != '' ) {
2021 $enc = $wgEditEncoding;
2025 if ( $enc == 'UTF-8' ) {
2028 return $this->iconv( $enc, 'UTF-8', $s );
2033 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2034 * also cleans up certain backwards-compatible sequences, converting them
2035 * to the modern Unicode equivalent.
2037 * This is language-specific for performance reasons only.
2039 function normalize( $s ) {
2040 global $wgAllUnicodeFixes;
2041 $s = UtfNormal
::cleanUp( $s );
2042 if ( $wgAllUnicodeFixes ) {
2043 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2044 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2051 * Transform a string using serialized data stored in the given file (which
2052 * must be in the serialized subdirectory of $IP). The file contains pairs
2053 * mapping source characters to destination characters.
2055 * The data is cached in process memory. This will go faster if you have the
2056 * FastStringSearch extension.
2058 function transformUsingPairFile( $file, $string ) {
2059 if ( !isset( $this->transformData
[$file] ) ) {
2060 $data = wfGetPrecompiledData( $file );
2061 if ( $data === false ) {
2062 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2064 $this->transformData
[$file] = new ReplacementArray( $data );
2066 return $this->transformData
[$file]->replace( $string );
2070 * For right-to-left language support
2075 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2079 * Return the correct HTML 'dir' attribute value for this language.
2083 return $this->isRTL() ?
'rtl' : 'ltr';
2087 * Return 'left' or 'right' as appropriate alignment for line-start
2088 * for this language's text direction.
2090 * Should be equivalent to CSS3 'start' text-align value....
2094 function alignStart() {
2095 return $this->isRTL() ?
'right' : 'left';
2099 * Return 'right' or 'left' as appropriate alignment for line-end
2100 * for this language's text direction.
2102 * Should be equivalent to CSS3 'end' text-align value....
2106 function alignEnd() {
2107 return $this->isRTL() ?
'left' : 'right';
2111 * A hidden direction mark (LRM or RLM), depending on the language direction
2115 function getDirMark() {
2116 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2119 function capitalizeAllNouns() {
2120 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2124 * An arrow, depending on the language direction
2128 function getArrow() {
2129 return $this->isRTL() ?
'←' : '→';
2133 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2137 function linkPrefixExtension() {
2138 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2141 function getMagicWords() {
2142 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2145 protected function doMagicHook() {
2146 if ( $this->mMagicHookDone
) {
2149 $this->mMagicHookDone
= true;
2150 wfProfileIn( 'LanguageGetMagic' );
2151 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2152 wfProfileOut( 'LanguageGetMagic' );
2155 # Fill a MagicWord object with data from here
2156 function getMagic( $mw ) {
2157 $this->doMagicHook();
2159 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2160 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2162 $magicWords = $this->getMagicWords();
2163 if ( isset( $magicWords[$mw->mId
] ) ) {
2164 $rawEntry = $magicWords[$mw->mId
];
2170 if ( !is_array( $rawEntry ) ) {
2171 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2173 $mw->mCaseSensitive
= $rawEntry[0];
2174 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2179 * Add magic words to the extension array
2181 function addMagicWordsByLang( $newWords ) {
2182 $code = $this->getCode();
2183 $fallbackChain = array();
2184 while ( $code && !in_array( $code, $fallbackChain ) ) {
2185 $fallbackChain[] = $code;
2186 $code = self
::getFallbackFor( $code );
2188 if ( !in_array( 'en', $fallbackChain ) ) {
2189 $fallbackChain[] = 'en';
2191 $fallbackChain = array_reverse( $fallbackChain );
2192 foreach ( $fallbackChain as $code ) {
2193 if ( isset( $newWords[$code] ) ) {
2194 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2200 * Get special page names, as an associative array
2201 * case folded alias => real name
2203 function getSpecialPageAliases() {
2204 // Cache aliases because it may be slow to load them
2205 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2207 $this->mExtendedSpecialPageAliases
=
2208 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2209 wfRunHooks( 'LanguageGetSpecialPageAliases',
2210 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2213 return $this->mExtendedSpecialPageAliases
;
2217 * Italic is unsuitable for some languages
2219 * @param $text String: the text to be emphasized.
2222 function emphasize( $text ) {
2223 return "<em>$text</em>";
2227 * Normally we output all numbers in plain en_US style, that is
2228 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2229 * point twohundredthirtyfive. However this is not sutable for all
2230 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2231 * Icelandic just want to use commas instead of dots, and dots instead
2232 * of commas like "293.291,235".
2234 * An example of this function being called:
2236 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2239 * See LanguageGu.php for the Gujarati implementation and
2240 * $separatorTransformTable on MessageIs.php for
2241 * the , => . and . => , implementation.
2243 * @todo check if it's viable to use localeconv() for the decimal
2245 * @param $number Mixed: the string to be formatted, should be an integer
2246 * or a floating point number.
2247 * @param $nocommafy Bool: set to true for special numbers like dates
2250 function formatNum( $number, $nocommafy = false ) {
2251 global $wgTranslateNumerals;
2252 if ( !$nocommafy ) {
2253 $number = $this->commafy( $number );
2254 $s = $this->separatorTransformTable();
2256 $number = strtr( $number, $s );
2260 if ( $wgTranslateNumerals ) {
2261 $s = $this->digitTransformTable();
2263 $number = strtr( $number, $s );
2270 function parseFormattedNumber( $number ) {
2271 $s = $this->digitTransformTable();
2273 $number = strtr( $number, array_flip( $s ) );
2276 $s = $this->separatorTransformTable();
2278 $number = strtr( $number, array_flip( $s ) );
2281 $number = strtr( $number, array( ',' => '' ) );
2286 * Adds commas to a given number
2291 function commafy( $_ ) {
2292 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2295 function digitTransformTable() {
2296 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2299 function separatorTransformTable() {
2300 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2304 * Take a list of strings and build a locale-friendly comma-separated
2305 * list, using the local comma-separator message.
2306 * The last two strings are chained with an "and".
2311 function listToText( $l ) {
2313 $m = count( $l ) - 1;
2315 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2317 for ( $i = $m; $i >= 0; $i-- ) {
2320 } else if ( $i == $m - 1 ) {
2321 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2323 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2331 * Take a list of strings and build a locale-friendly comma-separated
2332 * list, using the local comma-separator message.
2333 * @param $list array of strings to put in a comma list
2336 function commaList( $list ) {
2341 array( 'parsemag', 'escapenoentities', 'language' => $this )
2347 * Take a list of strings and build a locale-friendly semicolon-separated
2348 * list, using the local semicolon-separator message.
2349 * @param $list array of strings to put in a semicolon list
2352 function semicolonList( $list ) {
2356 'semicolon-separator',
2357 array( 'parsemag', 'escapenoentities', 'language' => $this )
2363 * Same as commaList, but separate it with the pipe instead.
2364 * @param $list array of strings to put in a pipe list
2367 function pipeList( $list ) {
2372 array( 'escapenoentities', 'language' => $this )
2378 * Truncate a string to a specified length in bytes, appending an optional
2379 * string (e.g. for ellipses)
2381 * The database offers limited byte lengths for some columns in the database;
2382 * multi-byte character sets mean we need to ensure that only whole characters
2383 * are included, otherwise broken characters can be passed to the user
2385 * If $length is negative, the string will be truncated from the beginning
2387 * @param $string String to truncate
2388 * @param $length Int: maximum length (including ellipses)
2389 * @param $ellipsis String to append to the truncated text
2390 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2391 * $adjustLength was introduced in 1.18, before that behaved as if false.
2394 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2395 # Use the localized ellipsis character
2396 if ( $ellipsis == '...' ) {
2397 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2399 # Check if there is no need to truncate
2400 if ( $length == 0 ) {
2401 return $ellipsis; // convention
2402 } elseif ( strlen( $string ) <= abs( $length ) ) {
2403 return $string; // no need to truncate
2405 $stringOriginal = $string;
2406 # If ellipsis length is >= $length then we can't apply $adjustLength
2407 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2408 $string = $ellipsis; // this can be slightly unexpected
2409 # Otherwise, truncate and add ellipsis...
2411 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2412 if ( $length > 0 ) {
2413 $length -= $eLength;
2414 $string = substr( $string, 0, $length ); // xyz...
2415 $string = $this->removeBadCharLast( $string );
2416 $string = $string . $ellipsis;
2418 $length +
= $eLength;
2419 $string = substr( $string, $length ); // ...xyz
2420 $string = $this->removeBadCharFirst( $string );
2421 $string = $ellipsis . $string;
2424 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2425 # This check is *not* redundant if $adjustLength, due to the single case where
2426 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2427 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2430 return $stringOriginal;
2435 * Remove bytes that represent an incomplete Unicode character
2436 * at the end of string (e.g. bytes of the char are missing)
2438 * @param $string String
2441 protected function removeBadCharLast( $string ) {
2442 if ( $string != '' ) {
2443 $char = ord( $string[strlen( $string ) - 1] );
2445 if ( $char >= 0xc0 ) {
2446 # We got the first byte only of a multibyte char; remove it.
2447 $string = substr( $string, 0, -1 );
2448 } elseif ( $char >= 0x80 &&
2449 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2450 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2452 # We chopped in the middle of a character; remove it
2460 * Remove bytes that represent an incomplete Unicode character
2461 * at the start of string (e.g. bytes of the char are missing)
2463 * @param $string String
2466 protected function removeBadCharFirst( $string ) {
2467 if ( $string != '' ) {
2468 $char = ord( $string[0] );
2469 if ( $char >= 0x80 && $char < 0xc0 ) {
2470 # We chopped in the middle of a character; remove the whole thing
2471 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2478 * Truncate a string of valid HTML to a specified length in bytes,
2479 * appending an optional string (e.g. for ellipses), and return valid HTML
2481 * This is only intended for styled/linked text, such as HTML with
2482 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2483 * Also, this will not detect things like "display:none" CSS.
2485 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2487 * @param string $text HTML string to truncate
2488 * @param int $length (zero/positive) Maximum length (including ellipses)
2489 * @param string $ellipsis String to append to the truncated text
2492 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2493 # Use the localized ellipsis character
2494 if ( $ellipsis == '...' ) {
2495 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2497 # Check if there is clearly no need to truncate
2498 if ( $length <= 0 ) {
2499 return $ellipsis; // no text shown, nothing to format (convention)
2500 } elseif ( strlen( $text ) <= $length ) {
2501 return $text; // string short enough even *with* HTML (short-circuit)
2504 $displayLen = 0; // innerHTML legth so far
2505 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2506 $tagType = 0; // 0-open, 1-close
2507 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2508 $entityState = 0; // 0-not entity, 1-entity
2509 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2510 $openTags = array(); // open tag stack
2511 $pOpenTags = array();
2513 $textLen = strlen( $text );
2514 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2515 for ( $pos = 0; true; ++
$pos ) {
2516 # Consider truncation once the display length has reached the maximim.
2517 # Check that we're not in the middle of a bracket/entity...
2518 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2519 if ( !$testingEllipsis ) {
2520 $testingEllipsis = true;
2521 # Save where we are; we will truncate here unless there turn out to
2522 # be so few remaining characters that truncation is not necessary.
2523 $pOpenTags = $openTags; // save state
2524 $pRet = $ret; // save state
2525 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2526 # String in fact does need truncation, the truncation point was OK.
2527 $openTags = $pOpenTags; // reload state
2528 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2529 $ret .= $ellipsis; // add ellipsis
2533 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2535 # Read the next char...
2537 $lastCh = $pos ?
$text[$pos - 1] : '';
2538 $ret .= $ch; // add to result string
2540 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2541 $entityState = 0; // for bad HTML
2542 $bracketState = 1; // tag started (checking for backslash)
2543 } elseif ( $ch == '>' ) {
2544 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2545 $entityState = 0; // for bad HTML
2546 $bracketState = 0; // out of brackets
2547 } elseif ( $bracketState == 1 ) {
2549 $tagType = 1; // close tag (e.g. "</span>")
2551 $tagType = 0; // open tag (e.g. "<span>")
2554 $bracketState = 2; // building tag name
2555 } elseif ( $bracketState == 2 ) {
2559 // Name found (e.g. "<a href=..."), add on tag attributes...
2560 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2562 } elseif ( $bracketState == 0 ) {
2563 if ( $entityState ) {
2566 $displayLen++
; // entity is one displayed char
2570 $entityState = 1; // entity found, (e.g. " ")
2572 $displayLen++
; // this char is displayed
2573 // Add the next $max display text chars after this in one swoop...
2574 $max = ( $testingEllipsis ?
$length : $neLength ) - $displayLen;
2575 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2576 $displayLen +
= $skipped;
2582 if ( $displayLen == 0 ) {
2583 return ''; // no text shown, nothing to format
2585 // Close the last tag if left unclosed by bad HTML
2586 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2587 while ( count( $openTags ) > 0 ) {
2588 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2593 // truncateHtml() helper function
2594 // like strcspn() but adds the skipped chars to $ret
2595 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2596 if ( $len === null ) {
2597 $len = -1; // -1 means "no limit" for strcspn
2598 } elseif ( $len < 0 ) {
2602 if ( $start < strlen( $text ) ) {
2603 $skipCount = strcspn( $text, $search, $start, $len );
2604 $ret .= substr( $text, $start, $skipCount );
2610 * truncateHtml() helper function
2611 * (a) push or pop $tag from $openTags as needed
2612 * (b) clear $tag value
2613 * @param String &$tag Current HTML tag name we are looking at
2614 * @param int $tagType (0-open tag, 1-close tag)
2615 * @param char $lastCh Character before the '>' that ended this tag
2616 * @param array &$openTags Open tag stack (not accounting for $tag)
2618 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2619 $tag = ltrim( $tag );
2621 if ( $tagType == 0 && $lastCh != '/' ) {
2622 $openTags[] = $tag; // tag opened (didn't close itself)
2623 } else if ( $tagType == 1 ) {
2624 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2625 array_pop( $openTags ); // tag closed
2633 * Grammatical transformations, needed for inflected languages
2634 * Invoked by putting {{grammar:case|word}} in a message
2636 * @param $word string
2637 * @param $case string
2640 function convertGrammar( $word, $case ) {
2641 global $wgGrammarForms;
2642 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2643 return $wgGrammarForms[$this->getCode()][$case][$word];
2649 * Provides an alternative text depending on specified gender.
2650 * Usage {{gender:username|masculine|feminine|neutral}}.
2651 * username is optional, in which case the gender of current user is used,
2652 * but only in (some) interface messages; otherwise default gender is used.
2653 * If second or third parameter are not specified, masculine is used.
2654 * These details may be overriden per language.
2656 function gender( $gender, $forms ) {
2657 if ( !count( $forms ) ) {
2660 $forms = $this->preConvertPlural( $forms, 2 );
2661 if ( $gender === 'male' ) {
2664 if ( $gender === 'female' ) {
2667 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2671 * Plural form transformations, needed for some languages.
2672 * For example, there are 3 form of plural in Russian and Polish,
2673 * depending on "count mod 10". See [[w:Plural]]
2674 * For English it is pretty simple.
2676 * Invoked by putting {{plural:count|wordform1|wordform2}}
2677 * or {{plural:count|wordform1|wordform2|wordform3}}
2679 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2681 * @param $count Integer: non-localized number
2682 * @param $forms Array: different plural forms
2683 * @return string Correct form of plural for $count in this language
2685 function convertPlural( $count, $forms ) {
2686 if ( !count( $forms ) ) {
2689 $forms = $this->preConvertPlural( $forms, 2 );
2691 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2695 * Checks that convertPlural was given an array and pads it to requested
2696 * amound of forms by copying the last one.
2698 * @param $count Integer: How many forms should there be at least
2699 * @param $forms Array of forms given to convertPlural
2700 * @return array Padded array of forms or an exception if not an array
2702 protected function preConvertPlural( /* Array */ $forms, $count ) {
2703 while ( count( $forms ) < $count ) {
2704 $forms[] = $forms[count( $forms ) - 1];
2710 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2711 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2712 * (which is an absolute timestamp).
2713 * @param $str String: the validated block duration in English
2714 * @return Somehow translated block duration
2715 * @see LanguageFi.php for example implementation
2717 function translateBlockExpiry( $str ) {
2718 foreach( SpecialBlock
::getSuggestedDurations( $this ) as $show => $value ){
2719 if ( strcmp( $str, $value ) == 0 ) {
2720 return htmlspecialchars( trim( $show ) );
2727 * languages like Chinese need to be segmented in order for the diff
2730 * @param $text String
2733 function segmentForDiff( $text ) {
2738 * and unsegment to show the result
2740 * @param $text String
2743 function unsegmentForDiff( $text ) {
2747 # convert text to all supported variants
2748 function autoConvertToAllVariants( $text ) {
2749 return $this->mConverter
->autoConvertToAllVariants( $text );
2752 # convert text to different variants of a language.
2753 function convert( $text ) {
2754 return $this->mConverter
->convert( $text );
2757 # Convert a Title object to a string in the preferred variant
2758 function convertTitle( $title ) {
2759 return $this->mConverter
->convertTitle( $title );
2762 # Check if this is a language with variants
2763 function hasVariants() {
2764 return sizeof( $this->getVariants() ) > 1;
2767 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2768 function armourMath( $text ) {
2769 return $this->mConverter
->armourMath( $text );
2773 * Perform output conversion on a string, and encode for safe HTML output.
2774 * @param $text String text to be converted
2775 * @param $isTitle Bool whether this conversion is for the article title
2777 * @todo this should get integrated somewhere sane
2779 function convertHtml( $text, $isTitle = false ) {
2780 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2783 function convertCategoryKey( $key ) {
2784 return $this->mConverter
->convertCategoryKey( $key );
2788 * Get the list of variants supported by this language
2789 * see sample implementation in LanguageZh.php
2791 * @return array an array of language codes
2793 function getVariants() {
2794 return $this->mConverter
->getVariants();
2797 function getPreferredVariant() {
2798 return $this->mConverter
->getPreferredVariant();
2801 function getDefaultVariant() {
2802 return $this->mConverter
->getDefaultVariant();
2805 function getURLVariant() {
2806 return $this->mConverter
->getURLVariant();
2810 * If a language supports multiple variants, it is
2811 * possible that non-existing link in one variant
2812 * actually exists in another variant. this function
2813 * tries to find it. See e.g. LanguageZh.php
2815 * @param $link String: the name of the link
2816 * @param $nt Mixed: the title object of the link
2817 * @param $ignoreOtherCond Boolean: to disable other conditions when
2818 * we need to transclude a template or update a category's link
2819 * @return null the input parameters may be modified upon return
2821 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2822 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2826 * If a language supports multiple variants, converts text
2827 * into an array of all possible variants of the text:
2828 * 'variant' => text in that variant
2830 * @deprecated Use autoConvertToAllVariants()
2832 function convertLinkToAllVariants( $text ) {
2833 return $this->mConverter
->convertLinkToAllVariants( $text );
2837 * returns language specific options used by User::getPageRenderHash()
2838 * for example, the preferred language variant
2842 function getExtraHashOptions() {
2843 return $this->mConverter
->getExtraHashOptions();
2847 * For languages that support multiple variants, the title of an
2848 * article may be displayed differently in different variants. this
2849 * function returns the apporiate title defined in the body of the article.
2853 function getParsedTitle() {
2854 return $this->mConverter
->getParsedTitle();
2858 * Enclose a string with the "no conversion" tag. This is used by
2859 * various functions in the Parser
2861 * @param $text String: text to be tagged for no conversion
2863 * @return string the tagged text
2865 function markNoConversion( $text, $noParse = false ) {
2866 return $this->mConverter
->markNoConversion( $text, $noParse );
2870 * A regular expression to match legal word-trailing characters
2871 * which should be merged onto a link of the form [[foo]]bar.
2875 function linkTrail() {
2876 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2879 function getLangObj() {
2884 * Get the RFC 3066 code for this language object
2886 function getCode() {
2887 return $this->mCode
;
2890 function setCode( $code ) {
2891 $this->mCode
= $code;
2895 * Get the name of a file for a certain language code
2896 * @param $prefix string Prepend this to the filename
2897 * @param $code string Language code
2898 * @param $suffix string Append this to the filename
2899 * @return string $prefix . $mangledCode . $suffix
2901 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2902 // Protect against path traversal
2903 if ( !Language
::isValidCode( $code )
2904 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2906 throw new MWException( "Invalid language code \"$code\"" );
2909 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2913 * Get the language code from a file name. Inverse of getFileName()
2914 * @param $filename string $prefix . $languageCode . $suffix
2915 * @param $prefix string Prefix before the language code
2916 * @param $suffix string Suffix after the language code
2917 * @return Language code, or false if $prefix or $suffix isn't found
2919 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2921 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2922 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2923 if ( !count( $m ) ) {
2926 return str_replace( '_', '-', strtolower( $m[1] ) );
2929 static function getMessagesFileName( $code ) {
2931 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2934 static function getClassFileName( $code ) {
2936 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2940 * Get the fallback for a given language
2942 static function getFallbackFor( $code ) {
2943 if ( $code === 'en' ) {
2947 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2952 * Get all messages for a given language
2953 * WARNING: this may take a long time
2955 static function getMessagesFor( $code ) {
2956 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2960 * Get a message for a given language
2962 static function getMessageFor( $key, $code ) {
2963 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2966 function fixVariableInNamespace( $talk ) {
2967 if ( strpos( $talk, '$1' ) === false ) {
2971 global $wgMetaNamespace;
2972 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2974 # Allow grammar transformations
2975 # Allowing full message-style parsing would make simple requests
2976 # such as action=raw much more expensive than they need to be.
2977 # This will hopefully cover most cases.
2978 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2979 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2980 return str_replace( ' ', '_', $talk );
2983 function replaceGrammarInNamespace( $m ) {
2984 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2987 static function getCaseMaps() {
2988 static $wikiUpperChars, $wikiLowerChars;
2989 if ( isset( $wikiUpperChars ) ) {
2990 return array( $wikiUpperChars, $wikiLowerChars );
2993 wfProfileIn( __METHOD__
);
2994 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2995 if ( $arr === false ) {
2996 throw new MWException(
2997 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2999 $wikiUpperChars = $arr['wikiUpperChars'];
3000 $wikiLowerChars = $arr['wikiLowerChars'];
3001 wfProfileOut( __METHOD__
);
3002 return array( $wikiUpperChars, $wikiLowerChars );
3006 * Decode an expiry (block, protection, etc) which has come from the DB
3008 * @param $expiry String: Database expiry String
3009 * @param $format Bool|Int true to process using language functions, or TS_ constant
3010 * to return the expiry in a given timestamp
3013 public function formatExpiry( $expiry, $format = true ) {
3014 static $infinity, $infinityMsg;
3015 if( $infinity === null ){
3016 $infinityMsg = wfMessage( 'infiniteblock' );
3017 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3020 if ( $expiry == '' ||
$expiry == $infinity ) {
3021 return $format === true
3025 return $format === true
3026 ?
$this->timeanddate( $expiry )
3027 : wfTimestamp( $format, $expiry );
3033 * @param $seconds String
3036 function formatTimePeriod( $seconds ) {
3037 if ( round( $seconds * 10 ) < 100 ) {
3038 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3039 } elseif ( round( $seconds ) < 60 ) {
3040 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3041 } elseif ( round( $seconds ) < 3600 ) {
3042 $minutes = floor( $seconds / 60 );
3043 $secondsPart = round( fmod( $seconds, 60 ) );
3044 if ( $secondsPart == 60 ) {
3048 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3049 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3051 $hours = floor( $seconds / 3600 );
3052 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3053 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3054 if ( $secondsPart == 60 ) {
3058 if ( $minutes == 60 ) {
3062 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3063 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3064 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3068 function formatBitrate( $bps ) {
3069 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3071 return $this->formatNum( $bps ) . $units[0];
3073 $unitIndex = floor( log10( $bps ) / 3 );
3074 $mantissa = $bps / pow( 1000, $unitIndex );
3075 if ( $mantissa < 10 ) {
3076 $mantissa = round( $mantissa, 1 );
3078 $mantissa = round( $mantissa );
3080 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3084 * Format a size in bytes for output, using an appropriate
3085 * unit (B, KB, MB or GB) according to the magnitude in question
3087 * @param $size Size to format
3088 * @return string Plain text (not HTML)
3090 function formatSize( $size ) {
3091 // For small sizes no decimal places necessary
3093 if ( $size > 1024 ) {
3094 $size = $size / 1024;
3095 if ( $size > 1024 ) {
3096 $size = $size / 1024;
3097 // For MB and bigger two decimal places are smarter
3099 if ( $size > 1024 ) {
3100 $size = $size / 1024;
3101 $msg = 'size-gigabytes';
3103 $msg = 'size-megabytes';
3106 $msg = 'size-kilobytes';
3109 $msg = 'size-bytes';
3111 $size = round( $size, $round );
3112 $text = $this->getMessageFromDB( $msg );
3113 return str_replace( '$1', $this->formatNum( $size ), $text );
3117 * Get the conversion rule title, if any.
3119 function getConvRuleTitle() {
3120 return $this->mConverter
->getConvRuleTitle();