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 getMathNames() {
499 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
502 function getDatePreferences() {
503 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
506 function getDateFormats() {
507 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
510 function getDefaultDateFormat() {
511 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
512 if ( $df === 'dmy or mdy' ) {
513 global $wgAmericanDates;
514 return $wgAmericanDates ?
'mdy' : 'dmy';
520 function getDatePreferenceMigrationMap() {
521 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
524 function getImageFile( $image ) {
525 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
528 function getDefaultUserOptionOverrides() {
529 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
532 function getExtraUserToggles() {
533 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
536 function getUserToggle( $tog ) {
537 return $this->getMessageFromDB( "tog-$tog" );
541 * Get language names, indexed by code.
542 * If $customisedOnly is true, only returns codes with a messages file
544 public static function getLanguageNames( $customisedOnly = false ) {
545 global $wgExtraLanguageNames;
546 static $coreLanguageNames;
548 if ( $coreLanguageNames === null ) {
549 include( MWInit
::compiledPath( 'languages/Names.php' ) );
552 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
553 if ( !$customisedOnly ) {
559 $dir = opendir( "$IP/languages/messages" );
560 while ( false !== ( $file = readdir( $dir ) ) ) {
561 $code = self
::getCodeFromFileName( $file, 'Messages' );
562 if ( $code && isset( $allNames[$code] ) ) {
563 $names[$code] = $allNames[$code];
571 * Get translated language names. This is done on best effort and
572 * by default this is exactly the same as Language::getLanguageNames.
573 * The CLDR extension provides translated names.
574 * @param $code String Language code.
575 * @return Array language code => language name
578 public static function getTranslatedLanguageNames( $code ) {
580 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
582 foreach ( self
::getLanguageNames() as $code => $name ) {
583 if ( !isset( $names[$code] ) ) $names[$code] = $name;
590 * Get a message from the MediaWiki namespace.
592 * @param $msg String: message name
595 function getMessageFromDB( $msg ) {
596 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
599 function getLanguageName( $code ) {
600 $names = self
::getLanguageNames();
601 if ( !array_key_exists( $code, $names ) ) {
604 return $names[$code];
607 function getMonthName( $key ) {
608 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
611 function getMonthNameGen( $key ) {
612 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
615 function getMonthAbbreviation( $key ) {
616 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
619 function getWeekdayName( $key ) {
620 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
623 function getWeekdayAbbreviation( $key ) {
624 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
627 function getIranianCalendarMonthName( $key ) {
628 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
631 function getHebrewCalendarMonthName( $key ) {
632 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
635 function getHebrewCalendarMonthNameGen( $key ) {
636 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
639 function getHijriCalendarMonthName( $key ) {
640 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
644 * Used by date() and time() to adjust the time output.
646 * @param $ts Int the time in date('YmdHis') format
647 * @param $tz Mixed: adjust the time by this amount (default false, mean we
648 * get user timecorrection setting)
651 function userAdjust( $ts, $tz = false ) {
652 global $wgUser, $wgLocalTZoffset;
654 if ( $tz === false ) {
655 $tz = $wgUser->getOption( 'timecorrection' );
658 $data = explode( '|', $tz, 3 );
660 if ( $data[0] == 'ZoneInfo' ) {
661 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
662 $date = date_create( $ts, timezone_open( 'UTC' ) );
663 date_timezone_set( $date, timezone_open( $data[2] ) );
664 $date = date_format( $date, 'YmdHis' );
667 # Unrecognized timezone, default to 'Offset' with the stored offset.
672 if ( $data[0] == 'System' ||
$tz == '' ) {
673 # Global offset in minutes.
674 if ( isset( $wgLocalTZoffset ) ) {
675 $minDiff = $wgLocalTZoffset;
677 } else if ( $data[0] == 'Offset' ) {
678 $minDiff = intval( $data[1] );
680 $data = explode( ':', $tz );
681 if ( count( $data ) == 2 ) {
682 $data[0] = intval( $data[0] );
683 $data[1] = intval( $data[1] );
684 $minDiff = abs( $data[0] ) * 60 +
$data[1];
685 if ( $data[0] < 0 ) {
686 $minDiff = -$minDiff;
689 $minDiff = intval( $data[0] ) * 60;
693 # No difference ? Return time unchanged
694 if ( 0 == $minDiff ) {
698 wfSuppressWarnings(); // E_STRICT system time bitching
699 # Generate an adjusted date; take advantage of the fact that mktime
700 # will normalize out-of-range values so we don't have to split $minDiff
701 # into hours and minutes.
703 (int)substr( $ts, 8, 2 ) ), # Hours
704 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
705 (int)substr( $ts, 12, 2 ), # Seconds
706 (int)substr( $ts, 4, 2 ), # Month
707 (int)substr( $ts, 6, 2 ), # Day
708 (int)substr( $ts, 0, 4 ) ); # Year
710 $date = date( 'YmdHis', $t );
717 * This is a workalike of PHP's date() function, but with better
718 * internationalisation, a reduced set of format characters, and a better
721 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
722 * PHP manual for definitions. There are a number of extensions, which
725 * xn Do not translate digits of the next numeric format character
726 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
727 * xr Use roman numerals for the next numeric format character
728 * xh Use hebrew numerals for the next numeric format character
730 * xg Genitive month name
732 * xij j (day number) in Iranian calendar
733 * xiF F (month name) in Iranian calendar
734 * xin n (month number) in Iranian calendar
735 * xiY Y (full year) in Iranian calendar
737 * xjj j (day number) in Hebrew calendar
738 * xjF F (month name) in Hebrew calendar
739 * xjt t (days in month) in Hebrew calendar
740 * xjx xg (genitive month name) in Hebrew calendar
741 * xjn n (month number) in Hebrew calendar
742 * xjY Y (full year) in Hebrew calendar
744 * xmj j (day number) in Hijri calendar
745 * xmF F (month name) in Hijri calendar
746 * xmn n (month number) in Hijri calendar
747 * xmY Y (full year) in Hijri calendar
749 * xkY Y (full year) in Thai solar calendar. Months and days are
750 * identical to the Gregorian calendar
751 * xoY Y (full year) in Minguo calendar or Juche year.
752 * Months and days are identical to the
754 * xtY Y (full year) in Japanese nengo. Months and days are
755 * identical to the Gregorian calendar
757 * Characters enclosed in double quotes will be considered literal (with
758 * the quotes themselves removed). Unmatched quotes will be considered
759 * literal quotes. Example:
761 * "The month is" F => The month is January
764 * Backslash escaping is also supported.
766 * Input timestamp is assumed to be pre-normalized to the desired local
769 * @param $format String
770 * @param $ts String: 14-character timestamp
773 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
775 function sprintfDate( $format, $ts ) {
788 for ( $p = 0; $p < strlen( $format ); $p++
) {
791 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
792 $code .= $format[++
$p];
795 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
796 $code .= $format[++
$p];
807 $rawToggle = !$rawToggle;
816 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
819 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
820 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
823 $num = substr( $ts, 6, 2 );
826 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
827 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
830 $num = intval( substr( $ts, 6, 2 ) );
834 $iranian = self
::tsToIranian( $ts );
840 $hijri = self
::tsToHijri( $ts );
846 $hebrew = self
::tsToHebrew( $ts );
852 $unix = wfTimestamp( TS_UNIX
, $ts );
854 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
858 $unix = wfTimestamp( TS_UNIX
, $ts );
860 $w = gmdate( 'w', $unix );
865 $unix = wfTimestamp( TS_UNIX
, $ts );
867 $num = gmdate( 'w', $unix );
871 $unix = wfTimestamp( TS_UNIX
, $ts );
873 $num = gmdate( 'z', $unix );
877 $unix = wfTimestamp( TS_UNIX
, $ts );
879 $num = gmdate( 'W', $unix );
882 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
886 $iranian = self
::tsToIranian( $ts );
888 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
892 $hijri = self
::tsToHijri( $ts );
894 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
898 $hebrew = self
::tsToHebrew( $ts );
900 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
903 $num = substr( $ts, 4, 2 );
906 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
909 $num = intval( substr( $ts, 4, 2 ) );
913 $iranian = self
::tsToIranian( $ts );
919 $hijri = self
::tsToHijri ( $ts );
925 $hebrew = self
::tsToHebrew( $ts );
931 $unix = wfTimestamp( TS_UNIX
, $ts );
933 $num = gmdate( 't', $unix );
937 $hebrew = self
::tsToHebrew( $ts );
943 $unix = wfTimestamp( TS_UNIX
, $ts );
945 $num = gmdate( 'L', $unix );
949 $unix = wfTimestamp( TS_UNIX
, $ts );
951 $num = date( 'o', $unix );
954 $num = substr( $ts, 0, 4 );
958 $iranian = self
::tsToIranian( $ts );
964 $hijri = self
::tsToHijri( $ts );
970 $hebrew = self
::tsToHebrew( $ts );
976 $thai = self
::tsToYear( $ts, 'thai' );
982 $minguo = self
::tsToYear( $ts, 'minguo' );
988 $tenno = self
::tsToYear( $ts, 'tenno' );
993 $num = substr( $ts, 2, 2 );
996 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
999 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1002 $h = substr( $ts, 8, 2 );
1003 $num = $h %
12 ?
$h %
12 : 12;
1006 $num = intval( substr( $ts, 8, 2 ) );
1009 $h = substr( $ts, 8, 2 );
1010 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1013 $num = substr( $ts, 8, 2 );
1016 $num = substr( $ts, 10, 2 );
1019 $num = substr( $ts, 12, 2 );
1023 $unix = wfTimestamp( TS_UNIX
, $ts );
1025 $s .= gmdate( 'c', $unix );
1029 $unix = wfTimestamp( TS_UNIX
, $ts );
1031 $s .= gmdate( 'r', $unix );
1035 $unix = wfTimestamp( TS_UNIX
, $ts );
1040 # Backslash escaping
1041 if ( $p < strlen( $format ) - 1 ) {
1042 $s .= $format[++
$p];
1049 if ( $p < strlen( $format ) - 1 ) {
1050 $endQuote = strpos( $format, '"', $p +
1 );
1051 if ( $endQuote === false ) {
1052 # No terminating quote, assume literal "
1055 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1059 # Quote at end of string, assume literal "
1066 if ( $num !== false ) {
1067 if ( $rawToggle ||
$raw ) {
1070 } elseif ( $roman ) {
1071 $s .= self
::romanNumeral( $num );
1073 } elseif ( $hebrewNum ) {
1074 $s .= self
::hebrewNumeral( $num );
1077 $s .= $this->formatNum( $num, true );
1084 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1085 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1087 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1088 * Gregorian dates to Iranian dates. Originally written in C, it
1089 * is released under the terms of GNU Lesser General Public
1090 * License. Conversion to PHP was performed by Niklas Laxström.
1092 * Link: http://www.farsiweb.info/jalali/jalali.c
1094 private static function tsToIranian( $ts ) {
1095 $gy = substr( $ts, 0, 4 ) -1600;
1096 $gm = substr( $ts, 4, 2 ) -1;
1097 $gd = (int)substr( $ts, 6, 2 ) -1;
1099 # Days passed from the beginning (including leap years)
1101 +
floor( ( $gy +
3 ) / 4 )
1102 - floor( ( $gy +
99 ) / 100 )
1103 +
floor( ( $gy +
399 ) / 400 );
1106 // Add days of the past months of this year
1107 for ( $i = 0; $i < $gm; $i++
) {
1108 $gDayNo +
= self
::$GREG_DAYS[$i];
1112 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1116 // Days passed in current month
1119 $jDayNo = $gDayNo - 79;
1121 $jNp = floor( $jDayNo / 12053 );
1124 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1127 if ( $jDayNo >= 366 ) {
1128 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1129 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1132 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1133 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1139 return array( $jy, $jm, $jd );
1143 * Converting Gregorian dates to Hijri dates.
1145 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1147 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1149 private static function tsToHijri( $ts ) {
1150 $year = substr( $ts, 0, 4 );
1151 $month = substr( $ts, 4, 2 );
1152 $day = substr( $ts, 6, 2 );
1160 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1161 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1164 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1165 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1166 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1169 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1170 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1173 $zl = $zjd -1948440 +
10632;
1174 $zn = (int)( ( $zl - 1 ) / 10631 );
1175 $zl = $zl - 10631 * $zn +
354;
1176 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1177 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1178 $zm = (int)( ( 24 * $zl ) / 709 );
1179 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1180 $zy = 30 * $zn +
$zj - 30;
1182 return array( $zy, $zm, $zd );
1186 * Converting Gregorian dates to Hebrew dates.
1188 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1189 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1190 * to translate the relevant functions into PHP and release them under
1193 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1194 * and Adar II is 14. In a non-leap year, Adar is 6.
1196 private static function tsToHebrew( $ts ) {
1198 $year = substr( $ts, 0, 4 );
1199 $month = substr( $ts, 4, 2 );
1200 $day = substr( $ts, 6, 2 );
1202 # Calculate Hebrew year
1203 $hebrewYear = $year +
3760;
1205 # Month number when September = 1, August = 12
1207 if ( $month > 12 ) {
1214 # Calculate day of year from 1 September
1216 for ( $i = 1; $i < $month; $i++
) {
1220 # Check if the year is leap
1221 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1224 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1231 # Calculate the start of the Hebrew year
1232 $start = self
::hebrewYearStart( $hebrewYear );
1234 # Calculate next year's start
1235 if ( $dayOfYear <= $start ) {
1236 # Day is before the start of the year - it is the previous year
1238 $nextStart = $start;
1242 # Add days since previous year's 1 September
1244 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1248 # Start of the new (previous) year
1249 $start = self
::hebrewYearStart( $hebrewYear );
1252 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1255 # Calculate Hebrew day of year
1256 $hebrewDayOfYear = $dayOfYear - $start;
1258 # Difference between year's days
1259 $diff = $nextStart - $start;
1260 # Add 12 (or 13 for leap years) days to ignore the difference between
1261 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1262 # difference is only about the year type
1263 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1269 # Check the year pattern, and is leap year
1270 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1271 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1272 # and non-leap years
1273 $yearPattern = $diff %
30;
1274 # Check if leap year
1275 $isLeap = $diff >= 30;
1277 # Calculate day in the month from number of day in the Hebrew year
1278 # Don't check Adar - if the day is not in Adar, we will stop before;
1279 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1280 $hebrewDay = $hebrewDayOfYear;
1283 while ( $hebrewMonth <= 12 ) {
1284 # Calculate days in this month
1285 if ( $isLeap && $hebrewMonth == 6 ) {
1286 # Adar in a leap year
1288 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1290 if ( $hebrewDay <= $days ) {
1294 # Subtract the days of Adar I
1295 $hebrewDay -= $days;
1298 if ( $hebrewDay <= $days ) {
1304 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1305 # Cheshvan in a complete year (otherwise as the rule below)
1307 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1308 # Kislev in an incomplete year (otherwise as the rule below)
1311 # Odd months have 30 days, even have 29
1312 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1314 if ( $hebrewDay <= $days ) {
1315 # In the current month
1318 # Subtract the days of the current month
1319 $hebrewDay -= $days;
1320 # Try in the next month
1325 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1329 * This calculates the Hebrew year start, as days since 1 September.
1330 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1331 * Used for Hebrew date.
1333 private static function hebrewYearStart( $year ) {
1334 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1335 $b = intval( ( $year - 1 ) %
4 );
1336 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1340 $Mar = intval( $m );
1346 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1347 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1349 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1351 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1355 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1360 * Algorithm to convert Gregorian dates to Thai solar dates,
1361 * Minguo dates or Minguo dates.
1363 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1364 * http://en.wikipedia.org/wiki/Minguo_calendar
1365 * http://en.wikipedia.org/wiki/Japanese_era_name
1367 * @param $ts String: 14-character timestamp
1368 * @param $cName String: calender name
1369 * @return Array: converted year, month, day
1371 private static function tsToYear( $ts, $cName ) {
1372 $gy = substr( $ts, 0, 4 );
1373 $gm = substr( $ts, 4, 2 );
1374 $gd = substr( $ts, 6, 2 );
1376 if ( !strcmp( $cName, 'thai' ) ) {
1378 # Add 543 years to the Gregorian calendar
1379 # Months and days are identical
1380 $gy_offset = $gy +
543;
1381 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1383 # Deduct 1911 years from the Gregorian calendar
1384 # Months and days are identical
1385 $gy_offset = $gy - 1911;
1386 } else if ( !strcmp( $cName, 'tenno' ) ) {
1387 # Nengō dates up to Meiji period
1388 # Deduct years from the Gregorian calendar
1389 # depending on the nengo periods
1390 # Months and days are identical
1391 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1393 $gy_gannen = $gy - 1868 +
1;
1394 $gy_offset = $gy_gannen;
1395 if ( $gy_gannen == 1 ) {
1398 $gy_offset = '明治' . $gy_offset;
1400 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1401 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1402 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1403 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1404 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1408 $gy_gannen = $gy - 1912 +
1;
1409 $gy_offset = $gy_gannen;
1410 if ( $gy_gannen == 1 ) {
1413 $gy_offset = '大正' . $gy_offset;
1415 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1416 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1417 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1421 $gy_gannen = $gy - 1926 +
1;
1422 $gy_offset = $gy_gannen;
1423 if ( $gy_gannen == 1 ) {
1426 $gy_offset = '昭和' . $gy_offset;
1429 $gy_gannen = $gy - 1989 +
1;
1430 $gy_offset = $gy_gannen;
1431 if ( $gy_gannen == 1 ) {
1434 $gy_offset = '平成' . $gy_offset;
1440 return array( $gy_offset, $gm, $gd );
1444 * Roman number formatting up to 3000
1446 static function romanNumeral( $num ) {
1447 static $table = array(
1448 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1449 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1450 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1451 array( '', 'M', 'MM', 'MMM' )
1454 $num = intval( $num );
1455 if ( $num > 3000 ||
$num <= 0 ) {
1460 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1461 if ( $num >= $pow10 ) {
1462 $s .= $table[$i][floor( $num / $pow10 )];
1464 $num = $num %
$pow10;
1470 * Hebrew Gematria number formatting up to 9999
1472 static function hebrewNumeral( $num ) {
1473 static $table = array(
1474 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1475 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1476 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1477 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1480 $num = intval( $num );
1481 if ( $num > 9999 ||
$num <= 0 ) {
1486 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1487 if ( $num >= $pow10 ) {
1488 if ( $num == 15 ||
$num == 16 ) {
1489 $s .= $table[0][9] . $table[0][$num - 9];
1492 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1493 if ( $pow10 == 1000 ) {
1498 $num = $num %
$pow10;
1500 if ( strlen( $s ) == 2 ) {
1503 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1504 $str .= substr( $s, strlen( $s ) - 2, 2 );
1506 $start = substr( $str, 0, strlen( $str ) - 2 );
1507 $end = substr( $str, strlen( $str ) - 2 );
1510 $str = $start . 'ך';
1513 $str = $start . 'ם';
1516 $str = $start . 'ן';
1519 $str = $start . 'ף';
1522 $str = $start . 'ץ';
1529 * This is meant to be used by time(), date(), and timeanddate() to get
1530 * the date preference they're supposed to use, it should be used in
1534 * function timeanddate([...], $format = true) {
1535 * $datePreference = $this->dateFormat($format);
1540 * @param $usePrefs Mixed: if true, the user's preference is used
1541 * if false, the site/language default is used
1542 * if int/string, assumed to be a format.
1545 function dateFormat( $usePrefs = true ) {
1548 if ( is_bool( $usePrefs ) ) {
1550 $datePreference = $wgUser->getDatePreference();
1552 $datePreference = (string)User
::getDefaultOption( 'date' );
1555 $datePreference = (string)$usePrefs;
1559 if ( $datePreference == '' ) {
1563 return $datePreference;
1567 * Get a format string for a given type and preference
1568 * @param $type May be date, time or both
1569 * @param $pref The format name as it appears in Messages*.php
1571 function getDateFormatString( $type, $pref ) {
1572 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1573 if ( $pref == 'default' ) {
1574 $pref = $this->getDefaultDateFormat();
1575 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1577 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1578 if ( is_null( $df ) ) {
1579 $pref = $this->getDefaultDateFormat();
1580 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1583 $this->dateFormatStrings
[$type][$pref] = $df;
1585 return $this->dateFormatStrings
[$type][$pref];
1589 * @param $ts Mixed: the time format which needs to be turned into a
1590 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1591 * @param $adj Bool: whether to adjust the time output according to the
1592 * user configured offset ($timecorrection)
1593 * @param $format Mixed: true to use user's date format preference
1594 * @param $timecorrection String: the time offset as returned by
1595 * validateTimeZone() in Special:Preferences
1598 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1599 $ts = wfTimestamp( TS_MW
, $ts );
1601 $ts = $this->userAdjust( $ts, $timecorrection );
1603 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1604 return $this->sprintfDate( $df, $ts );
1608 * @param $ts Mixed: the time format which needs to be turned into a
1609 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1610 * @param $adj Bool: whether to adjust the time output according to the
1611 * user configured offset ($timecorrection)
1612 * @param $format Mixed: true to use user's date format preference
1613 * @param $timecorrection String: the time offset as returned by
1614 * validateTimeZone() in Special:Preferences
1617 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1618 $ts = wfTimestamp( TS_MW
, $ts );
1620 $ts = $this->userAdjust( $ts, $timecorrection );
1622 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1623 return $this->sprintfDate( $df, $ts );
1627 * @param $ts Mixed: the time format which needs to be turned into a
1628 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1629 * @param $adj Bool: whether to adjust the time output according to the
1630 * user configured offset ($timecorrection)
1631 * @param $format Mixed: what format to return, if it's false output the
1632 * default one (default true)
1633 * @param $timecorrection String: the time offset as returned by
1634 * validateTimeZone() in Special:Preferences
1637 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1638 $ts = wfTimestamp( TS_MW
, $ts );
1640 $ts = $this->userAdjust( $ts, $timecorrection );
1642 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1643 return $this->sprintfDate( $df, $ts );
1646 function getMessage( $key ) {
1647 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1650 function getAllMessages() {
1651 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1654 function iconv( $in, $out, $string ) {
1655 # This is a wrapper for iconv in all languages except esperanto,
1656 # which does some nasty x-conversions beforehand
1658 # Even with //IGNORE iconv can whine about illegal characters in
1659 # *input* string. We just ignore those too.
1660 # REF: http://bugs.php.net/bug.php?id=37166
1661 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1662 wfSuppressWarnings();
1663 $text = iconv( $in, $out . '//IGNORE', $string );
1664 wfRestoreWarnings();
1668 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1669 function ucwordbreaksCallbackAscii( $matches ) {
1670 return $this->ucfirst( $matches[1] );
1673 function ucwordbreaksCallbackMB( $matches ) {
1674 return mb_strtoupper( $matches[0] );
1677 function ucCallback( $matches ) {
1678 list( $wikiUpperChars ) = self
::getCaseMaps();
1679 return strtr( $matches[1], $wikiUpperChars );
1682 function lcCallback( $matches ) {
1683 list( , $wikiLowerChars ) = self
::getCaseMaps();
1684 return strtr( $matches[1], $wikiLowerChars );
1687 function ucwordsCallbackMB( $matches ) {
1688 return mb_strtoupper( $matches[0] );
1691 function ucwordsCallbackWiki( $matches ) {
1692 list( $wikiUpperChars ) = self
::getCaseMaps();
1693 return strtr( $matches[0], $wikiUpperChars );
1697 * Make a string's first character uppercase
1699 function ucfirst( $str ) {
1701 if ( $o < 96 ) { // if already uppercase...
1703 } elseif ( $o < 128 ) {
1704 return ucfirst( $str ); // use PHP's ucfirst()
1706 // fall back to more complex logic in case of multibyte strings
1707 return $this->uc( $str, true );
1712 * Convert a string to uppercase
1714 function uc( $str, $first = false ) {
1715 if ( function_exists( 'mb_strtoupper' ) ) {
1717 if ( $this->isMultibyte( $str ) ) {
1718 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1720 return ucfirst( $str );
1723 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1726 if ( $this->isMultibyte( $str ) ) {
1727 $x = $first ?
'^' : '';
1728 return preg_replace_callback(
1729 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1730 array( $this, 'ucCallback' ),
1734 return $first ?
ucfirst( $str ) : strtoupper( $str );
1739 function lcfirst( $str ) {
1742 return strval( $str );
1743 } elseif ( $o >= 128 ) {
1744 return $this->lc( $str, true );
1745 } elseif ( $o > 96 ) {
1748 $str[0] = strtolower( $str[0] );
1753 function lc( $str, $first = false ) {
1754 if ( function_exists( 'mb_strtolower' ) ) {
1756 if ( $this->isMultibyte( $str ) ) {
1757 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1759 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1762 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1765 if ( $this->isMultibyte( $str ) ) {
1766 $x = $first ?
'^' : '';
1767 return preg_replace_callback(
1768 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1769 array( $this, 'lcCallback' ),
1773 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1778 function isMultibyte( $str ) {
1779 return (bool)preg_match( '/[\x80-\xff]/', $str );
1782 function ucwords( $str ) {
1783 if ( $this->isMultibyte( $str ) ) {
1784 $str = $this->lc( $str );
1786 // regexp to find first letter in each word (i.e. after each space)
1787 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1789 // function to use to capitalize a single char
1790 if ( function_exists( 'mb_strtoupper' ) ) {
1791 return preg_replace_callback(
1793 array( $this, 'ucwordsCallbackMB' ),
1797 return preg_replace_callback(
1799 array( $this, 'ucwordsCallbackWiki' ),
1804 return ucwords( strtolower( $str ) );
1808 # capitalize words at word breaks
1809 function ucwordbreaks( $str ) {
1810 if ( $this->isMultibyte( $str ) ) {
1811 $str = $this->lc( $str );
1813 // since \b doesn't work for UTF-8, we explicitely define word break chars
1814 $breaks = "[ \-\(\)\}\{\.,\?!]";
1816 // find first letter after word break
1817 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1819 if ( function_exists( 'mb_strtoupper' ) ) {
1820 return preg_replace_callback(
1822 array( $this, 'ucwordbreaksCallbackMB' ),
1826 return preg_replace_callback(
1828 array( $this, 'ucwordsCallbackWiki' ),
1833 return preg_replace_callback(
1834 '/\b([\w\x80-\xff]+)\b/',
1835 array( $this, 'ucwordbreaksCallbackAscii' ),
1842 * Return a case-folded representation of $s
1844 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1845 * and $s2 are the same except for the case of their characters. It is not
1846 * necessary for the value returned to make sense when displayed.
1848 * Do *not* perform any other normalisation in this function. If a caller
1849 * uses this function when it should be using a more general normalisation
1850 * function, then fix the caller.
1852 function caseFold( $s ) {
1853 return $this->uc( $s );
1856 function checkTitleEncoding( $s ) {
1857 if ( is_array( $s ) ) {
1858 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1860 # Check for non-UTF-8 URLs
1861 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1866 $isutf8 = ( $s == iconv("UTF-8","UTF-8//IGNORE", $s));
1871 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1874 function fallback8bitEncoding() {
1875 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1879 * Most writing systems use whitespace to break up words.
1880 * Some languages such as Chinese don't conventionally do this,
1881 * which requires special handling when breaking up words for
1884 function hasWordBreaks() {
1889 * Some languages such as Chinese require word segmentation,
1890 * Specify such segmentation when overridden in derived class.
1892 * @param $string String
1895 function segmentByWord( $string ) {
1900 * Some languages have special punctuation need to be normalized.
1901 * Make such changes here.
1903 * @param $string String
1906 function normalizeForSearch( $string ) {
1907 return self
::convertDoubleWidth( $string );
1911 * convert double-width roman characters to single-width.
1912 * range: ff00-ff5f ~= 0020-007f
1914 protected static function convertDoubleWidth( $string ) {
1915 static $full = null;
1916 static $half = null;
1918 if ( $full === null ) {
1919 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1920 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1921 $full = str_split( $fullWidth, 3 );
1922 $half = str_split( $halfWidth );
1925 $string = str_replace( $full, $half, $string );
1929 protected static function insertSpace( $string, $pattern ) {
1930 $string = preg_replace( $pattern, " $1 ", $string );
1931 $string = preg_replace( '/ +/', ' ', $string );
1935 function convertForSearchResult( $termsArray ) {
1936 # some languages, e.g. Chinese, need to do a conversion
1937 # in order for search results to be displayed correctly
1942 * Get the first character of a string.
1947 function firstChar( $s ) {
1950 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1951 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1956 if ( isset( $matches[1] ) ) {
1957 if ( strlen( $matches[1] ) != 3 ) {
1961 // Break down Hangul syllables to grab the first jamo
1962 $code = utf8ToCodepoint( $matches[1] );
1963 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1965 } elseif ( $code < 0xb098 ) {
1966 return "\xe3\x84\xb1";
1967 } elseif ( $code < 0xb2e4 ) {
1968 return "\xe3\x84\xb4";
1969 } elseif ( $code < 0xb77c ) {
1970 return "\xe3\x84\xb7";
1971 } elseif ( $code < 0xb9c8 ) {
1972 return "\xe3\x84\xb9";
1973 } elseif ( $code < 0xbc14 ) {
1974 return "\xe3\x85\x81";
1975 } elseif ( $code < 0xc0ac ) {
1976 return "\xe3\x85\x82";
1977 } elseif ( $code < 0xc544 ) {
1978 return "\xe3\x85\x85";
1979 } elseif ( $code < 0xc790 ) {
1980 return "\xe3\x85\x87";
1981 } elseif ( $code < 0xcc28 ) {
1982 return "\xe3\x85\x88";
1983 } elseif ( $code < 0xce74 ) {
1984 return "\xe3\x85\x8a";
1985 } elseif ( $code < 0xd0c0 ) {
1986 return "\xe3\x85\x8b";
1987 } elseif ( $code < 0xd30c ) {
1988 return "\xe3\x85\x8c";
1989 } elseif ( $code < 0xd558 ) {
1990 return "\xe3\x85\x8d";
1992 return "\xe3\x85\x8e";
1999 function initEncoding() {
2000 # Some languages may have an alternate char encoding option
2001 # (Esperanto X-coding, Japanese furigana conversion, etc)
2002 # If this language is used as the primary content language,
2003 # an override to the defaults can be set here on startup.
2006 function recodeForEdit( $s ) {
2007 # For some languages we'll want to explicitly specify
2008 # which characters make it into the edit box raw
2009 # or are converted in some way or another.
2010 # Note that if wgOutputEncoding is different from
2011 # wgInputEncoding, this text will be further converted
2012 # to wgOutputEncoding.
2013 global $wgEditEncoding;
2014 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2017 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2021 function recodeInput( $s ) {
2022 # Take the previous into account.
2023 global $wgEditEncoding;
2024 if ( $wgEditEncoding != '' ) {
2025 $enc = $wgEditEncoding;
2029 if ( $enc == 'UTF-8' ) {
2032 return $this->iconv( $enc, 'UTF-8', $s );
2037 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2038 * also cleans up certain backwards-compatible sequences, converting them
2039 * to the modern Unicode equivalent.
2041 * This is language-specific for performance reasons only.
2043 function normalize( $s ) {
2044 global $wgAllUnicodeFixes;
2045 $s = UtfNormal
::cleanUp( $s );
2046 if ( $wgAllUnicodeFixes ) {
2047 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2048 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2055 * Transform a string using serialized data stored in the given file (which
2056 * must be in the serialized subdirectory of $IP). The file contains pairs
2057 * mapping source characters to destination characters.
2059 * The data is cached in process memory. This will go faster if you have the
2060 * FastStringSearch extension.
2062 function transformUsingPairFile( $file, $string ) {
2063 if ( !isset( $this->transformData
[$file] ) ) {
2064 $data = wfGetPrecompiledData( $file );
2065 if ( $data === false ) {
2066 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2068 $this->transformData
[$file] = new ReplacementArray( $data );
2070 return $this->transformData
[$file]->replace( $string );
2074 * For right-to-left language support
2079 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2083 * Return the correct HTML 'dir' attribute value for this language.
2087 return $this->isRTL() ?
'rtl' : 'ltr';
2091 * Return 'left' or 'right' as appropriate alignment for line-start
2092 * for this language's text direction.
2094 * Should be equivalent to CSS3 'start' text-align value....
2098 function alignStart() {
2099 return $this->isRTL() ?
'right' : 'left';
2103 * Return 'right' or 'left' as appropriate alignment for line-end
2104 * for this language's text direction.
2106 * Should be equivalent to CSS3 'end' text-align value....
2110 function alignEnd() {
2111 return $this->isRTL() ?
'left' : 'right';
2115 * A hidden direction mark (LRM or RLM), depending on the language direction
2119 function getDirMark() {
2120 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2123 function capitalizeAllNouns() {
2124 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2128 * An arrow, depending on the language direction
2132 function getArrow() {
2133 return $this->isRTL() ?
'←' : '→';
2137 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2141 function linkPrefixExtension() {
2142 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2145 function getMagicWords() {
2146 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2149 protected function doMagicHook() {
2150 if ( $this->mMagicHookDone
) {
2153 $this->mMagicHookDone
= true;
2154 wfProfileIn( 'LanguageGetMagic' );
2155 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2156 wfProfileOut( 'LanguageGetMagic' );
2159 # Fill a MagicWord object with data from here
2160 function getMagic( $mw ) {
2161 $this->doMagicHook();
2163 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2164 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2166 $magicWords = $this->getMagicWords();
2167 if ( isset( $magicWords[$mw->mId
] ) ) {
2168 $rawEntry = $magicWords[$mw->mId
];
2174 if ( !is_array( $rawEntry ) ) {
2175 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2177 $mw->mCaseSensitive
= $rawEntry[0];
2178 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2183 * Add magic words to the extension array
2185 function addMagicWordsByLang( $newWords ) {
2186 $code = $this->getCode();
2187 $fallbackChain = array();
2188 while ( $code && !in_array( $code, $fallbackChain ) ) {
2189 $fallbackChain[] = $code;
2190 $code = self
::getFallbackFor( $code );
2192 if ( !in_array( 'en', $fallbackChain ) ) {
2193 $fallbackChain[] = 'en';
2195 $fallbackChain = array_reverse( $fallbackChain );
2196 foreach ( $fallbackChain as $code ) {
2197 if ( isset( $newWords[$code] ) ) {
2198 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2204 * Get special page names, as an associative array
2205 * case folded alias => real name
2207 function getSpecialPageAliases() {
2208 // Cache aliases because it may be slow to load them
2209 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2211 $this->mExtendedSpecialPageAliases
=
2212 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2213 wfRunHooks( 'LanguageGetSpecialPageAliases',
2214 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2217 return $this->mExtendedSpecialPageAliases
;
2221 * Italic is unsuitable for some languages
2223 * @param $text String: the text to be emphasized.
2226 function emphasize( $text ) {
2227 return "<em>$text</em>";
2231 * Normally we output all numbers in plain en_US style, that is
2232 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2233 * point twohundredthirtyfive. However this is not sutable for all
2234 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2235 * Icelandic just want to use commas instead of dots, and dots instead
2236 * of commas like "293.291,235".
2238 * An example of this function being called:
2240 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2243 * See LanguageGu.php for the Gujarati implementation and
2244 * $separatorTransformTable on MessageIs.php for
2245 * the , => . and . => , implementation.
2247 * @todo check if it's viable to use localeconv() for the decimal
2249 * @param $number Mixed: the string to be formatted, should be an integer
2250 * or a floating point number.
2251 * @param $nocommafy Bool: set to true for special numbers like dates
2254 function formatNum( $number, $nocommafy = false ) {
2255 global $wgTranslateNumerals;
2256 if ( !$nocommafy ) {
2257 $number = $this->commafy( $number );
2258 $s = $this->separatorTransformTable();
2260 $number = strtr( $number, $s );
2264 if ( $wgTranslateNumerals ) {
2265 $s = $this->digitTransformTable();
2267 $number = strtr( $number, $s );
2274 function parseFormattedNumber( $number ) {
2275 $s = $this->digitTransformTable();
2277 $number = strtr( $number, array_flip( $s ) );
2280 $s = $this->separatorTransformTable();
2282 $number = strtr( $number, array_flip( $s ) );
2285 $number = strtr( $number, array( ',' => '' ) );
2290 * Adds commas to a given number
2295 function commafy( $_ ) {
2296 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2299 function digitTransformTable() {
2300 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2303 function separatorTransformTable() {
2304 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2308 * Take a list of strings and build a locale-friendly comma-separated
2309 * list, using the local comma-separator message.
2310 * The last two strings are chained with an "and".
2315 function listToText( $l ) {
2317 $m = count( $l ) - 1;
2319 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2321 for ( $i = $m; $i >= 0; $i-- ) {
2324 } else if ( $i == $m - 1 ) {
2325 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2327 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2335 * Take a list of strings and build a locale-friendly comma-separated
2336 * list, using the local comma-separator message.
2337 * @param $list array of strings to put in a comma list
2340 function commaList( $list ) {
2345 array( 'parsemag', 'escapenoentities', 'language' => $this )
2351 * Take a list of strings and build a locale-friendly semicolon-separated
2352 * list, using the local semicolon-separator message.
2353 * @param $list array of strings to put in a semicolon list
2356 function semicolonList( $list ) {
2360 'semicolon-separator',
2361 array( 'parsemag', 'escapenoentities', 'language' => $this )
2367 * Same as commaList, but separate it with the pipe instead.
2368 * @param $list array of strings to put in a pipe list
2371 function pipeList( $list ) {
2376 array( 'escapenoentities', 'language' => $this )
2382 * Truncate a string to a specified length in bytes, appending an optional
2383 * string (e.g. for ellipses)
2385 * The database offers limited byte lengths for some columns in the database;
2386 * multi-byte character sets mean we need to ensure that only whole characters
2387 * are included, otherwise broken characters can be passed to the user
2389 * If $length is negative, the string will be truncated from the beginning
2391 * @param $string String to truncate
2392 * @param $length Int: maximum length (including ellipses)
2393 * @param $ellipsis String to append to the truncated text
2394 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2395 * $adjustLength was introduced in 1.18, before that behaved as if false.
2398 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2399 # Use the localized ellipsis character
2400 if ( $ellipsis == '...' ) {
2401 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2403 # Check if there is no need to truncate
2404 if ( $length == 0 ) {
2405 return $ellipsis; // convention
2406 } elseif ( strlen( $string ) <= abs( $length ) ) {
2407 return $string; // no need to truncate
2409 $stringOriginal = $string;
2410 # If ellipsis length is >= $length then we can't apply $adjustLength
2411 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2412 $string = $ellipsis; // this can be slightly unexpected
2413 # Otherwise, truncate and add ellipsis...
2415 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2416 if ( $length > 0 ) {
2417 $length -= $eLength;
2418 $string = substr( $string, 0, $length ); // xyz...
2419 $string = $this->removeBadCharLast( $string );
2420 $string = $string . $ellipsis;
2422 $length +
= $eLength;
2423 $string = substr( $string, $length ); // ...xyz
2424 $string = $this->removeBadCharFirst( $string );
2425 $string = $ellipsis . $string;
2428 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2429 # This check is *not* redundant if $adjustLength, due to the single case where
2430 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2431 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2434 return $stringOriginal;
2439 * Remove bytes that represent an incomplete Unicode character
2440 * at the end of string (e.g. bytes of the char are missing)
2442 * @param $string String
2445 protected function removeBadCharLast( $string ) {
2446 if ( $string != '' ) {
2447 $char = ord( $string[strlen( $string ) - 1] );
2449 if ( $char >= 0xc0 ) {
2450 # We got the first byte only of a multibyte char; remove it.
2451 $string = substr( $string, 0, -1 );
2452 } elseif ( $char >= 0x80 &&
2453 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2454 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2456 # We chopped in the middle of a character; remove it
2464 * Remove bytes that represent an incomplete Unicode character
2465 * at the start of string (e.g. bytes of the char are missing)
2467 * @param $string String
2470 protected function removeBadCharFirst( $string ) {
2471 if ( $string != '' ) {
2472 $char = ord( $string[0] );
2473 if ( $char >= 0x80 && $char < 0xc0 ) {
2474 # We chopped in the middle of a character; remove the whole thing
2475 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2482 * Truncate a string of valid HTML to a specified length in bytes,
2483 * appending an optional string (e.g. for ellipses), and return valid HTML
2485 * This is only intended for styled/linked text, such as HTML with
2486 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2487 * Also, this will not detect things like "display:none" CSS.
2489 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2491 * @param string $text HTML string to truncate
2492 * @param int $length (zero/positive) Maximum length (including ellipses)
2493 * @param string $ellipsis String to append to the truncated text
2496 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2497 # Use the localized ellipsis character
2498 if ( $ellipsis == '...' ) {
2499 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2501 # Check if there is clearly no need to truncate
2502 if ( $length <= 0 ) {
2503 return $ellipsis; // no text shown, nothing to format (convention)
2504 } elseif ( strlen( $text ) <= $length ) {
2505 return $text; // string short enough even *with* HTML (short-circuit)
2508 $displayLen = 0; // innerHTML legth so far
2509 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2510 $tagType = 0; // 0-open, 1-close
2511 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2512 $entityState = 0; // 0-not entity, 1-entity
2513 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2514 $openTags = array(); // open tag stack
2515 $pOpenTags = array();
2517 $textLen = strlen( $text );
2518 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2519 for ( $pos = 0; true; ++
$pos ) {
2520 # Consider truncation once the display length has reached the maximim.
2521 # Check that we're not in the middle of a bracket/entity...
2522 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2523 if ( !$testingEllipsis ) {
2524 $testingEllipsis = true;
2525 # Save where we are; we will truncate here unless there turn out to
2526 # be so few remaining characters that truncation is not necessary.
2527 $pOpenTags = $openTags; // save state
2528 $pRet = $ret; // save state
2529 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2530 # String in fact does need truncation, the truncation point was OK.
2531 $openTags = $pOpenTags; // reload state
2532 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2533 $ret .= $ellipsis; // add ellipsis
2537 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2539 # Read the next char...
2541 $lastCh = $pos ?
$text[$pos - 1] : '';
2542 $ret .= $ch; // add to result string
2544 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2545 $entityState = 0; // for bad HTML
2546 $bracketState = 1; // tag started (checking for backslash)
2547 } elseif ( $ch == '>' ) {
2548 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2549 $entityState = 0; // for bad HTML
2550 $bracketState = 0; // out of brackets
2551 } elseif ( $bracketState == 1 ) {
2553 $tagType = 1; // close tag (e.g. "</span>")
2555 $tagType = 0; // open tag (e.g. "<span>")
2558 $bracketState = 2; // building tag name
2559 } elseif ( $bracketState == 2 ) {
2563 // Name found (e.g. "<a href=..."), add on tag attributes...
2564 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2566 } elseif ( $bracketState == 0 ) {
2567 if ( $entityState ) {
2570 $displayLen++
; // entity is one displayed char
2574 $entityState = 1; // entity found, (e.g. " ")
2576 $displayLen++
; // this char is displayed
2577 // Add the next $max display text chars after this in one swoop...
2578 $max = ( $testingEllipsis ?
$length : $neLength ) - $displayLen;
2579 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2580 $displayLen +
= $skipped;
2586 if ( $displayLen == 0 ) {
2587 return ''; // no text shown, nothing to format
2589 // Close the last tag if left unclosed by bad HTML
2590 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2591 while ( count( $openTags ) > 0 ) {
2592 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2597 // truncateHtml() helper function
2598 // like strcspn() but adds the skipped chars to $ret
2599 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2600 if ( $len === null ) {
2601 $len = -1; // -1 means "no limit" for strcspn
2602 } elseif ( $len < 0 ) {
2606 if ( $start < strlen( $text ) ) {
2607 $skipCount = strcspn( $text, $search, $start, $len );
2608 $ret .= substr( $text, $start, $skipCount );
2614 * truncateHtml() helper function
2615 * (a) push or pop $tag from $openTags as needed
2616 * (b) clear $tag value
2617 * @param String &$tag Current HTML tag name we are looking at
2618 * @param int $tagType (0-open tag, 1-close tag)
2619 * @param char $lastCh Character before the '>' that ended this tag
2620 * @param array &$openTags Open tag stack (not accounting for $tag)
2622 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2623 $tag = ltrim( $tag );
2625 if ( $tagType == 0 && $lastCh != '/' ) {
2626 $openTags[] = $tag; // tag opened (didn't close itself)
2627 } else if ( $tagType == 1 ) {
2628 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2629 array_pop( $openTags ); // tag closed
2637 * Grammatical transformations, needed for inflected languages
2638 * Invoked by putting {{grammar:case|word}} in a message
2640 * @param $word string
2641 * @param $case string
2644 function convertGrammar( $word, $case ) {
2645 global $wgGrammarForms;
2646 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2647 return $wgGrammarForms[$this->getCode()][$case][$word];
2653 * Provides an alternative text depending on specified gender.
2654 * Usage {{gender:username|masculine|feminine|neutral}}.
2655 * username is optional, in which case the gender of current user is used,
2656 * but only in (some) interface messages; otherwise default gender is used.
2657 * If second or third parameter are not specified, masculine is used.
2658 * These details may be overriden per language.
2660 function gender( $gender, $forms ) {
2661 if ( !count( $forms ) ) {
2664 $forms = $this->preConvertPlural( $forms, 2 );
2665 if ( $gender === 'male' ) {
2668 if ( $gender === 'female' ) {
2671 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2675 * Plural form transformations, needed for some languages.
2676 * For example, there are 3 form of plural in Russian and Polish,
2677 * depending on "count mod 10". See [[w:Plural]]
2678 * For English it is pretty simple.
2680 * Invoked by putting {{plural:count|wordform1|wordform2}}
2681 * or {{plural:count|wordform1|wordform2|wordform3}}
2683 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2685 * @param $count Integer: non-localized number
2686 * @param $forms Array: different plural forms
2687 * @return string Correct form of plural for $count in this language
2689 function convertPlural( $count, $forms ) {
2690 if ( !count( $forms ) ) {
2693 $forms = $this->preConvertPlural( $forms, 2 );
2695 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2699 * Checks that convertPlural was given an array and pads it to requested
2700 * amound of forms by copying the last one.
2702 * @param $count Integer: How many forms should there be at least
2703 * @param $forms Array of forms given to convertPlural
2704 * @return array Padded array of forms or an exception if not an array
2706 protected function preConvertPlural( /* Array */ $forms, $count ) {
2707 while ( count( $forms ) < $count ) {
2708 $forms[] = $forms[count( $forms ) - 1];
2714 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2715 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2716 * (which is an absolute timestamp).
2717 * @param $str String: the validated block duration in English
2718 * @return Somehow translated block duration
2719 * @see LanguageFi.php for example implementation
2721 function translateBlockExpiry( $str ) {
2722 foreach( SpecialBlock
::getSuggestedDurations( $this ) as $show => $value ){
2723 if ( strcmp( $str, $value ) == 0 ) {
2724 return htmlspecialchars( trim( $show ) );
2731 * languages like Chinese need to be segmented in order for the diff
2734 * @param $text String
2737 function segmentForDiff( $text ) {
2742 * and unsegment to show the result
2744 * @param $text String
2747 function unsegmentForDiff( $text ) {
2751 # convert text to all supported variants
2752 function autoConvertToAllVariants( $text ) {
2753 return $this->mConverter
->autoConvertToAllVariants( $text );
2756 # convert text to different variants of a language.
2757 function convert( $text ) {
2758 return $this->mConverter
->convert( $text );
2761 # Convert a Title object to a string in the preferred variant
2762 function convertTitle( $title ) {
2763 return $this->mConverter
->convertTitle( $title );
2766 # Check if this is a language with variants
2767 function hasVariants() {
2768 return sizeof( $this->getVariants() ) > 1;
2771 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2772 function armourMath( $text ) {
2773 return $this->mConverter
->armourMath( $text );
2777 * Perform output conversion on a string, and encode for safe HTML output.
2778 * @param $text String text to be converted
2779 * @param $isTitle Bool whether this conversion is for the article title
2781 * @todo this should get integrated somewhere sane
2783 function convertHtml( $text, $isTitle = false ) {
2784 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2787 function convertCategoryKey( $key ) {
2788 return $this->mConverter
->convertCategoryKey( $key );
2792 * Get the list of variants supported by this language
2793 * see sample implementation in LanguageZh.php
2795 * @return array an array of language codes
2797 function getVariants() {
2798 return $this->mConverter
->getVariants();
2801 function getPreferredVariant() {
2802 return $this->mConverter
->getPreferredVariant();
2805 function getDefaultVariant() {
2806 return $this->mConverter
->getDefaultVariant();
2809 function getURLVariant() {
2810 return $this->mConverter
->getURLVariant();
2814 * If a language supports multiple variants, it is
2815 * possible that non-existing link in one variant
2816 * actually exists in another variant. this function
2817 * tries to find it. See e.g. LanguageZh.php
2819 * @param $link String: the name of the link
2820 * @param $nt Mixed: the title object of the link
2821 * @param $ignoreOtherCond Boolean: to disable other conditions when
2822 * we need to transclude a template or update a category's link
2823 * @return null the input parameters may be modified upon return
2825 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2826 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2830 * If a language supports multiple variants, converts text
2831 * into an array of all possible variants of the text:
2832 * 'variant' => text in that variant
2834 * @deprecated Use autoConvertToAllVariants()
2836 function convertLinkToAllVariants( $text ) {
2837 return $this->mConverter
->convertLinkToAllVariants( $text );
2841 * returns language specific options used by User::getPageRenderHash()
2842 * for example, the preferred language variant
2846 function getExtraHashOptions() {
2847 return $this->mConverter
->getExtraHashOptions();
2851 * For languages that support multiple variants, the title of an
2852 * article may be displayed differently in different variants. this
2853 * function returns the apporiate title defined in the body of the article.
2857 function getParsedTitle() {
2858 return $this->mConverter
->getParsedTitle();
2862 * Enclose a string with the "no conversion" tag. This is used by
2863 * various functions in the Parser
2865 * @param $text String: text to be tagged for no conversion
2867 * @return string the tagged text
2869 function markNoConversion( $text, $noParse = false ) {
2870 return $this->mConverter
->markNoConversion( $text, $noParse );
2874 * A regular expression to match legal word-trailing characters
2875 * which should be merged onto a link of the form [[foo]]bar.
2879 function linkTrail() {
2880 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2883 function getLangObj() {
2888 * Get the RFC 3066 code for this language object
2890 function getCode() {
2891 return $this->mCode
;
2894 function setCode( $code ) {
2895 $this->mCode
= $code;
2899 * Get the name of a file for a certain language code
2900 * @param $prefix string Prepend this to the filename
2901 * @param $code string Language code
2902 * @param $suffix string Append this to the filename
2903 * @return string $prefix . $mangledCode . $suffix
2905 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2906 // Protect against path traversal
2907 if ( !Language
::isValidCode( $code )
2908 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2910 throw new MWException( "Invalid language code \"$code\"" );
2913 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2917 * Get the language code from a file name. Inverse of getFileName()
2918 * @param $filename string $prefix . $languageCode . $suffix
2919 * @param $prefix string Prefix before the language code
2920 * @param $suffix string Suffix after the language code
2921 * @return Language code, or false if $prefix or $suffix isn't found
2923 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2925 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2926 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2927 if ( !count( $m ) ) {
2930 return str_replace( '_', '-', strtolower( $m[1] ) );
2933 static function getMessagesFileName( $code ) {
2935 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2938 static function getClassFileName( $code ) {
2940 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2944 * Get the fallback for a given language
2946 static function getFallbackFor( $code ) {
2947 if ( $code === 'en' ) {
2951 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2956 * Get all messages for a given language
2957 * WARNING: this may take a long time
2959 static function getMessagesFor( $code ) {
2960 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2964 * Get a message for a given language
2966 static function getMessageFor( $key, $code ) {
2967 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2970 function fixVariableInNamespace( $talk ) {
2971 if ( strpos( $talk, '$1' ) === false ) {
2975 global $wgMetaNamespace;
2976 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2978 # Allow grammar transformations
2979 # Allowing full message-style parsing would make simple requests
2980 # such as action=raw much more expensive than they need to be.
2981 # This will hopefully cover most cases.
2982 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2983 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2984 return str_replace( ' ', '_', $talk );
2987 function replaceGrammarInNamespace( $m ) {
2988 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2991 static function getCaseMaps() {
2992 static $wikiUpperChars, $wikiLowerChars;
2993 if ( isset( $wikiUpperChars ) ) {
2994 return array( $wikiUpperChars, $wikiLowerChars );
2997 wfProfileIn( __METHOD__
);
2998 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2999 if ( $arr === false ) {
3000 throw new MWException(
3001 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3003 $wikiUpperChars = $arr['wikiUpperChars'];
3004 $wikiLowerChars = $arr['wikiLowerChars'];
3005 wfProfileOut( __METHOD__
);
3006 return array( $wikiUpperChars, $wikiLowerChars );
3010 * Decode an expiry (block, protection, etc) which has come from the DB
3012 * @param $expiry String: Database expiry String
3013 * @param $format Bool|Int true to process using language functions, or TS_ constant
3014 * to return the expiry in a given timestamp
3017 public function formatExpiry( $expiry, $format = true ) {
3018 static $infinity, $infinityMsg;
3019 if( $infinity === null ){
3020 $infinityMsg = wfMessage( 'infiniteblock' );
3021 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3024 if ( $expiry == '' ||
$expiry == $infinity ) {
3025 return $format === true
3029 return $format === true
3030 ?
$this->timeanddate( $expiry )
3031 : wfTimestamp( $format, $expiry );
3037 * @param $seconds String
3040 function formatTimePeriod( $seconds ) {
3041 if ( round( $seconds * 10 ) < 100 ) {
3042 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3043 } elseif ( round( $seconds ) < 60 ) {
3044 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3045 } elseif ( round( $seconds ) < 3600 ) {
3046 $minutes = floor( $seconds / 60 );
3047 $secondsPart = round( fmod( $seconds, 60 ) );
3048 if ( $secondsPart == 60 ) {
3052 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3053 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3055 $hours = floor( $seconds / 3600 );
3056 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3057 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3058 if ( $secondsPart == 60 ) {
3062 if ( $minutes == 60 ) {
3066 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3067 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3068 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3072 function formatBitrate( $bps ) {
3073 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3075 return $this->formatNum( $bps ) . $units[0];
3077 $unitIndex = floor( log10( $bps ) / 3 );
3078 $mantissa = $bps / pow( 1000, $unitIndex );
3079 if ( $mantissa < 10 ) {
3080 $mantissa = round( $mantissa, 1 );
3082 $mantissa = round( $mantissa );
3084 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3088 * Format a size in bytes for output, using an appropriate
3089 * unit (B, KB, MB or GB) according to the magnitude in question
3091 * @param $size Size to format
3092 * @return string Plain text (not HTML)
3094 function formatSize( $size ) {
3095 // For small sizes no decimal places necessary
3097 if ( $size > 1024 ) {
3098 $size = $size / 1024;
3099 if ( $size > 1024 ) {
3100 $size = $size / 1024;
3101 // For MB and bigger two decimal places are smarter
3103 if ( $size > 1024 ) {
3104 $size = $size / 1024;
3105 $msg = 'size-gigabytes';
3107 $msg = 'size-megabytes';
3110 $msg = 'size-kilobytes';
3113 $msg = 'size-bytes';
3115 $size = round( $size, $round );
3116 $text = $this->getMessageFromDB( $msg );
3117 return str_replace( '$1', $this->formatNum( $size ), $text );
3121 * Get the conversion rule title, if any.
3123 function getConvRuleTitle() {
3124 return $this->mConverter
->getConvRuleTitle();