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();
77 * @var LocalisationCache
79 static public $dataCache;
81 static public $mLangObjCache = array();
83 static public $mWeekdayMsgs = array(
84 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
88 static public $mWeekdayAbbrevMsgs = array(
89 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
92 static public $mMonthMsgs = array(
93 'january', 'february', 'march', 'april', 'may_long', 'june',
94 'july', 'august', 'september', 'october', 'november',
97 static public $mMonthGenMsgs = array(
98 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
99 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
102 static public $mMonthAbbrevMsgs = array(
103 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
104 'sep', 'oct', 'nov', 'dec'
107 static public $mIranianCalendarMonthMsgs = array(
108 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
109 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
110 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
111 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
114 static public $mHebrewCalendarMonthMsgs = array(
115 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
116 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
117 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
118 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
119 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
122 static public $mHebrewCalendarMonthGenMsgs = array(
123 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
124 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
125 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
126 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
127 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
130 static public $mHijriCalendarMonthMsgs = array(
131 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
132 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
133 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
134 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
138 * Get a cached language object for a given language code
139 * @param $code String
142 static function factory( $code ) {
143 if ( !isset( self
::$mLangObjCache[$code] ) ) {
144 if ( count( self
::$mLangObjCache ) > 10 ) {
145 // Don't keep a billion objects around, that's stupid.
146 self
::$mLangObjCache = array();
148 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
150 return self
::$mLangObjCache[$code];
154 * Create a language object for a given language code
155 * @param $code String
158 protected static function newFromCode( $code ) {
160 static $recursionLevel = 0;
162 // Protect against path traversal below
163 if ( !Language
::isValidCode( $code )
164 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
166 throw new MWException( "Invalid language code \"$code\"" );
169 if ( !Language
::isValidBuiltInCode( $code ) ) {
170 // It's not possible to customise this code with class files, so
171 // just return a Language object. This is to support uselang= hacks.
172 $lang = new Language
;
173 $lang->setCode( $code );
177 if ( $code == 'en' ) {
180 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
181 if ( !defined( 'MW_COMPILED' ) ) {
182 // Preload base classes to work around APC/PHP5 bug
183 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
184 include_once( "$IP/languages/classes/$class.deps.php" );
186 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
187 include_once( "$IP/languages/classes/$class.php" );
192 if ( $recursionLevel > 5 ) {
193 throw new MWException( "Language fallback loop detected when creating class $class\n" );
196 if ( !MWInit
::classExists( $class ) ) {
197 $fallback = Language
::getFallbackFor( $code );
199 $lang = Language
::newFromCode( $fallback );
201 $lang->setCode( $code );
209 * Returns true if a language code string is of a valid form, whether or
210 * not it exists. This includes codes which are used solely for
211 * customisation via the MediaWiki namespace.
213 public static function isValidCode( $code ) {
215 strcspn( $code, ":/\\\000" ) === strlen( $code )
216 && !preg_match( Title
::getTitleInvalidRegex(), $code );
220 * Returns true if a language code is of a valid form for the purposes of
221 * internal customisation of MediaWiki, via Messages*.php.
223 public static function isValidBuiltInCode( $code ) {
224 return preg_match( '/^[a-z0-9-]*$/i', $code );
228 * Get the LocalisationCache instance
230 * @return LocalisationCache
232 public static function getLocalisationCache() {
233 if ( is_null( self
::$dataCache ) ) {
234 global $wgLocalisationCacheConf;
235 $class = $wgLocalisationCacheConf['class'];
236 self
::$dataCache = new $class( $wgLocalisationCacheConf );
238 return self
::$dataCache;
241 function __construct() {
242 $this->mConverter
= new FakeConverter( $this );
243 // Set the code to the name of the descendant
244 if ( get_class( $this ) == 'Language' ) {
247 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
249 self
::getLocalisationCache();
253 * Reduce memory usage
255 function __destruct() {
256 foreach ( $this as $name => $value ) {
257 unset( $this->$name );
262 * Hook which will be called if this is the content language.
263 * Descendants can use this to register hook functions or modify globals
265 function initContLang() { }
268 * @deprecated Use User::getDefaultOptions()
271 function getDefaultUserOptions() {
272 wfDeprecated( __METHOD__
);
273 return User
::getDefaultOptions();
276 function getFallbackLanguageCode() {
277 if ( $this->mCode
=== 'en' ) {
280 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
285 * Exports $wgBookstoreListEn
288 function getBookstoreList() {
289 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
295 function getNamespaces() {
296 if ( is_null( $this->namespaceNames
) ) {
297 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
299 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
300 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
302 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
304 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
305 if ( $wgMetaNamespaceTalk ) {
306 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
308 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
309 $this->namespaceNames
[NS_PROJECT_TALK
] =
310 $this->fixVariableInNamespace( $talk );
313 # Sometimes a language will be localised but not actually exist on this wiki.
314 foreach( $this->namespaceNames
as $key => $text ) {
315 if ( !isset( $validNamespaces[$key] ) ) {
316 unset( $this->namespaceNames
[$key] );
320 # The above mixing may leave namespaces out of canonical order.
321 # Re-order by namespace ID number...
322 ksort( $this->namespaceNames
);
324 return $this->namespaceNames
;
328 * A convenience function that returns the same thing as
329 * getNamespaces() except with the array values changed to ' '
330 * where it found '_', useful for producing output to be displayed
331 * e.g. in <select> forms.
335 function getFormattedNamespaces() {
336 $ns = $this->getNamespaces();
337 foreach ( $ns as $k => $v ) {
338 $ns[$k] = strtr( $v, '_', ' ' );
344 * Get a namespace value by key
346 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
347 * echo $mw_ns; // prints 'MediaWiki'
350 * @param $index Int: the array key of the namespace to return
351 * @return mixed, string if the namespace value exists, otherwise false
353 function getNsText( $index ) {
354 $ns = $this->getNamespaces();
355 return isset( $ns[$index] ) ?
$ns[$index] : false;
359 * A convenience function that returns the same thing as
360 * getNsText() except with '_' changed to ' ', useful for
365 function getFormattedNsText( $index ) {
366 $ns = $this->getNsText( $index );
367 return strtr( $ns, '_', ' ' );
371 * Returns gender-dependent namespace alias if available.
372 * @param $index Int: namespace index
373 * @param $gender String: gender key (male, female... )
377 function getGenderNsText( $index, $gender ) {
378 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
379 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
383 * Whether this language makes distinguishes genders for example in
388 function needsGenderDistinction() {
389 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
390 return count( $aliases ) > 0;
394 * Get a namespace key by value, case insensitive.
395 * Only matches namespace names for the current language, not the
396 * canonical ones defined in Namespace.php.
398 * @param $text String
399 * @return mixed An integer if $text is a valid value otherwise false
401 function getLocalNsIndex( $text ) {
402 $lctext = $this->lc( $text );
403 $ids = $this->getNamespaceIds();
404 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
407 function getNamespaceAliases() {
408 if ( is_null( $this->namespaceAliases
) ) {
409 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
413 foreach ( $aliases as $name => $index ) {
414 if ( $index === NS_PROJECT_TALK
) {
415 unset( $aliases[$name] );
416 $name = $this->fixVariableInNamespace( $name );
417 $aliases[$name] = $index;
422 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
423 foreach ( $genders as $index => $forms ) {
424 foreach ( $forms as $alias ) {
425 $aliases[$alias] = $index;
429 $this->namespaceAliases
= $aliases;
431 return $this->namespaceAliases
;
434 function getNamespaceIds() {
435 if ( is_null( $this->mNamespaceIds
) ) {
436 global $wgNamespaceAliases;
437 # Put namespace names and aliases into a hashtable.
438 # If this is too slow, then we should arrange it so that it is done
439 # before caching. The catch is that at pre-cache time, the above
440 # class-specific fixup hasn't been done.
441 $this->mNamespaceIds
= array();
442 foreach ( $this->getNamespaces() as $index => $name ) {
443 $this->mNamespaceIds
[$this->lc( $name )] = $index;
445 foreach ( $this->getNamespaceAliases() as $name => $index ) {
446 $this->mNamespaceIds
[$this->lc( $name )] = $index;
448 if ( $wgNamespaceAliases ) {
449 foreach ( $wgNamespaceAliases as $name => $index ) {
450 $this->mNamespaceIds
[$this->lc( $name )] = $index;
454 return $this->mNamespaceIds
;
459 * Get a namespace key by value, case insensitive. Canonical namespace
460 * names override custom ones defined for the current language.
462 * @param $text String
463 * @return mixed An integer if $text is a valid value otherwise false
465 function getNsIndex( $text ) {
466 $lctext = $this->lc( $text );
467 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
470 $ids = $this->getNamespaceIds();
471 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
475 * short names for language variants used for language conversion links.
477 * @param $code String
480 function getVariantname( $code ) {
481 return $this->getMessageFromDB( "variantname-$code" );
484 function specialPage( $name ) {
485 $aliases = $this->getSpecialPageAliases();
486 if ( isset( $aliases[$name][0] ) ) {
487 $name = $aliases[$name][0];
489 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
492 function getQuickbarSettings() {
494 $this->getMessage( 'qbsettings-none' ),
495 $this->getMessage( 'qbsettings-fixedleft' ),
496 $this->getMessage( 'qbsettings-fixedright' ),
497 $this->getMessage( 'qbsettings-floatingleft' ),
498 $this->getMessage( 'qbsettings-floatingright' )
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 getMonthNamesArray() {
612 $monthNames = array( '' );
613 for ( $i=1; $i < 13; $i++
) {
614 $monthNames[] = $this->getMonthName( $i );
619 function getMonthNameGen( $key ) {
620 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
623 function getMonthAbbreviation( $key ) {
624 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
627 function getMonthAbbreviationsArray() {
628 $monthNames = array('');
629 for ( $i=1; $i < 13; $i++
) {
630 $monthNames[] = $this->getMonthAbbreviation( $i );
635 function getWeekdayName( $key ) {
636 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
639 function getWeekdayAbbreviation( $key ) {
640 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
643 function getIranianCalendarMonthName( $key ) {
644 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
647 function getHebrewCalendarMonthName( $key ) {
648 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
651 function getHebrewCalendarMonthNameGen( $key ) {
652 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
655 function getHijriCalendarMonthName( $key ) {
656 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
660 * Used by date() and time() to adjust the time output.
662 * @param $ts Int the time in date('YmdHis') format
663 * @param $tz Mixed: adjust the time by this amount (default false, mean we
664 * get user timecorrection setting)
667 function userAdjust( $ts, $tz = false ) {
668 global $wgUser, $wgLocalTZoffset;
670 if ( $tz === false ) {
671 $tz = $wgUser->getOption( 'timecorrection' );
674 $data = explode( '|', $tz, 3 );
676 if ( $data[0] == 'ZoneInfo' ) {
677 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
678 $date = date_create( $ts, timezone_open( 'UTC' ) );
679 date_timezone_set( $date, timezone_open( $data[2] ) );
680 $date = date_format( $date, 'YmdHis' );
683 # Unrecognized timezone, default to 'Offset' with the stored offset.
688 if ( $data[0] == 'System' ||
$tz == '' ) {
689 # Global offset in minutes.
690 if ( isset( $wgLocalTZoffset ) ) {
691 $minDiff = $wgLocalTZoffset;
693 } else if ( $data[0] == 'Offset' ) {
694 $minDiff = intval( $data[1] );
696 $data = explode( ':', $tz );
697 if ( count( $data ) == 2 ) {
698 $data[0] = intval( $data[0] );
699 $data[1] = intval( $data[1] );
700 $minDiff = abs( $data[0] ) * 60 +
$data[1];
701 if ( $data[0] < 0 ) {
702 $minDiff = -$minDiff;
705 $minDiff = intval( $data[0] ) * 60;
709 # No difference ? Return time unchanged
710 if ( 0 == $minDiff ) {
714 wfSuppressWarnings(); // E_STRICT system time bitching
715 # Generate an adjusted date; take advantage of the fact that mktime
716 # will normalize out-of-range values so we don't have to split $minDiff
717 # into hours and minutes.
719 (int)substr( $ts, 8, 2 ) ), # Hours
720 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
721 (int)substr( $ts, 12, 2 ), # Seconds
722 (int)substr( $ts, 4, 2 ), # Month
723 (int)substr( $ts, 6, 2 ), # Day
724 (int)substr( $ts, 0, 4 ) ); # Year
726 $date = date( 'YmdHis', $t );
733 * This is a workalike of PHP's date() function, but with better
734 * internationalisation, a reduced set of format characters, and a better
737 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
738 * PHP manual for definitions. There are a number of extensions, which
741 * xn Do not translate digits of the next numeric format character
742 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
743 * xr Use roman numerals for the next numeric format character
744 * xh Use hebrew numerals for the next numeric format character
746 * xg Genitive month name
748 * xij j (day number) in Iranian calendar
749 * xiF F (month name) in Iranian calendar
750 * xin n (month number) in Iranian calendar
751 * xiY Y (full year) in Iranian calendar
753 * xjj j (day number) in Hebrew calendar
754 * xjF F (month name) in Hebrew calendar
755 * xjt t (days in month) in Hebrew calendar
756 * xjx xg (genitive month name) in Hebrew calendar
757 * xjn n (month number) in Hebrew calendar
758 * xjY Y (full year) in Hebrew calendar
760 * xmj j (day number) in Hijri calendar
761 * xmF F (month name) in Hijri calendar
762 * xmn n (month number) in Hijri calendar
763 * xmY Y (full year) in Hijri calendar
765 * xkY Y (full year) in Thai solar calendar. Months and days are
766 * identical to the Gregorian calendar
767 * xoY Y (full year) in Minguo calendar or Juche year.
768 * Months and days are identical to the
770 * xtY Y (full year) in Japanese nengo. Months and days are
771 * identical to the Gregorian calendar
773 * Characters enclosed in double quotes will be considered literal (with
774 * the quotes themselves removed). Unmatched quotes will be considered
775 * literal quotes. Example:
777 * "The month is" F => The month is January
780 * Backslash escaping is also supported.
782 * Input timestamp is assumed to be pre-normalized to the desired local
785 * @param $format String
786 * @param $ts String: 14-character timestamp
789 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
791 function sprintfDate( $format, $ts ) {
804 for ( $p = 0; $p < strlen( $format ); $p++
) {
807 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
808 $code .= $format[++
$p];
811 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
812 $code .= $format[++
$p];
823 $rawToggle = !$rawToggle;
832 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
835 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
836 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
839 $num = substr( $ts, 6, 2 );
842 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
843 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
846 $num = intval( substr( $ts, 6, 2 ) );
850 $iranian = self
::tsToIranian( $ts );
856 $hijri = self
::tsToHijri( $ts );
862 $hebrew = self
::tsToHebrew( $ts );
868 $unix = wfTimestamp( TS_UNIX
, $ts );
870 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
874 $unix = wfTimestamp( TS_UNIX
, $ts );
876 $w = gmdate( 'w', $unix );
881 $unix = wfTimestamp( TS_UNIX
, $ts );
883 $num = gmdate( 'w', $unix );
887 $unix = wfTimestamp( TS_UNIX
, $ts );
889 $num = gmdate( 'z', $unix );
893 $unix = wfTimestamp( TS_UNIX
, $ts );
895 $num = gmdate( 'W', $unix );
898 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
902 $iranian = self
::tsToIranian( $ts );
904 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
908 $hijri = self
::tsToHijri( $ts );
910 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
914 $hebrew = self
::tsToHebrew( $ts );
916 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
919 $num = substr( $ts, 4, 2 );
922 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
925 $num = intval( substr( $ts, 4, 2 ) );
929 $iranian = self
::tsToIranian( $ts );
935 $hijri = self
::tsToHijri ( $ts );
941 $hebrew = self
::tsToHebrew( $ts );
947 $unix = wfTimestamp( TS_UNIX
, $ts );
949 $num = gmdate( 't', $unix );
953 $hebrew = self
::tsToHebrew( $ts );
959 $unix = wfTimestamp( TS_UNIX
, $ts );
961 $num = gmdate( 'L', $unix );
965 $unix = wfTimestamp( TS_UNIX
, $ts );
967 $num = date( 'o', $unix );
970 $num = substr( $ts, 0, 4 );
974 $iranian = self
::tsToIranian( $ts );
980 $hijri = self
::tsToHijri( $ts );
986 $hebrew = self
::tsToHebrew( $ts );
992 $thai = self
::tsToYear( $ts, 'thai' );
998 $minguo = self
::tsToYear( $ts, 'minguo' );
1004 $tenno = self
::tsToYear( $ts, 'tenno' );
1009 $num = substr( $ts, 2, 2 );
1012 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1015 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1018 $h = substr( $ts, 8, 2 );
1019 $num = $h %
12 ?
$h %
12 : 12;
1022 $num = intval( substr( $ts, 8, 2 ) );
1025 $h = substr( $ts, 8, 2 );
1026 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1029 $num = substr( $ts, 8, 2 );
1032 $num = substr( $ts, 10, 2 );
1035 $num = substr( $ts, 12, 2 );
1039 $unix = wfTimestamp( TS_UNIX
, $ts );
1041 $s .= gmdate( 'c', $unix );
1045 $unix = wfTimestamp( TS_UNIX
, $ts );
1047 $s .= gmdate( 'r', $unix );
1051 $unix = wfTimestamp( TS_UNIX
, $ts );
1056 # Backslash escaping
1057 if ( $p < strlen( $format ) - 1 ) {
1058 $s .= $format[++
$p];
1065 if ( $p < strlen( $format ) - 1 ) {
1066 $endQuote = strpos( $format, '"', $p +
1 );
1067 if ( $endQuote === false ) {
1068 # No terminating quote, assume literal "
1071 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1075 # Quote at end of string, assume literal "
1082 if ( $num !== false ) {
1083 if ( $rawToggle ||
$raw ) {
1086 } elseif ( $roman ) {
1087 $s .= self
::romanNumeral( $num );
1089 } elseif ( $hebrewNum ) {
1090 $s .= self
::hebrewNumeral( $num );
1093 $s .= $this->formatNum( $num, true );
1100 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1101 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1103 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1104 * Gregorian dates to Iranian dates. Originally written in C, it
1105 * is released under the terms of GNU Lesser General Public
1106 * License. Conversion to PHP was performed by Niklas Laxström.
1108 * Link: http://www.farsiweb.info/jalali/jalali.c
1110 private static function tsToIranian( $ts ) {
1111 $gy = substr( $ts, 0, 4 ) -1600;
1112 $gm = substr( $ts, 4, 2 ) -1;
1113 $gd = (int)substr( $ts, 6, 2 ) -1;
1115 # Days passed from the beginning (including leap years)
1117 +
floor( ( $gy +
3 ) / 4 )
1118 - floor( ( $gy +
99 ) / 100 )
1119 +
floor( ( $gy +
399 ) / 400 );
1122 // Add days of the past months of this year
1123 for ( $i = 0; $i < $gm; $i++
) {
1124 $gDayNo +
= self
::$GREG_DAYS[$i];
1128 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1132 // Days passed in current month
1135 $jDayNo = $gDayNo - 79;
1137 $jNp = floor( $jDayNo / 12053 );
1140 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1143 if ( $jDayNo >= 366 ) {
1144 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1145 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1148 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1149 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1155 return array( $jy, $jm, $jd );
1159 * Converting Gregorian dates to Hijri dates.
1161 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1163 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1165 private static function tsToHijri( $ts ) {
1166 $year = substr( $ts, 0, 4 );
1167 $month = substr( $ts, 4, 2 );
1168 $day = substr( $ts, 6, 2 );
1176 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1177 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1180 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1181 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1182 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1185 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1186 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1189 $zl = $zjd -1948440 +
10632;
1190 $zn = (int)( ( $zl - 1 ) / 10631 );
1191 $zl = $zl - 10631 * $zn +
354;
1192 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1193 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1194 $zm = (int)( ( 24 * $zl ) / 709 );
1195 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1196 $zy = 30 * $zn +
$zj - 30;
1198 return array( $zy, $zm, $zd );
1202 * Converting Gregorian dates to Hebrew dates.
1204 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1205 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1206 * to translate the relevant functions into PHP and release them under
1209 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1210 * and Adar II is 14. In a non-leap year, Adar is 6.
1212 private static function tsToHebrew( $ts ) {
1214 $year = substr( $ts, 0, 4 );
1215 $month = substr( $ts, 4, 2 );
1216 $day = substr( $ts, 6, 2 );
1218 # Calculate Hebrew year
1219 $hebrewYear = $year +
3760;
1221 # Month number when September = 1, August = 12
1223 if ( $month > 12 ) {
1230 # Calculate day of year from 1 September
1232 for ( $i = 1; $i < $month; $i++
) {
1236 # Check if the year is leap
1237 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1240 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1247 # Calculate the start of the Hebrew year
1248 $start = self
::hebrewYearStart( $hebrewYear );
1250 # Calculate next year's start
1251 if ( $dayOfYear <= $start ) {
1252 # Day is before the start of the year - it is the previous year
1254 $nextStart = $start;
1258 # Add days since previous year's 1 September
1260 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1264 # Start of the new (previous) year
1265 $start = self
::hebrewYearStart( $hebrewYear );
1268 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1271 # Calculate Hebrew day of year
1272 $hebrewDayOfYear = $dayOfYear - $start;
1274 # Difference between year's days
1275 $diff = $nextStart - $start;
1276 # Add 12 (or 13 for leap years) days to ignore the difference between
1277 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1278 # difference is only about the year type
1279 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1285 # Check the year pattern, and is leap year
1286 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1287 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1288 # and non-leap years
1289 $yearPattern = $diff %
30;
1290 # Check if leap year
1291 $isLeap = $diff >= 30;
1293 # Calculate day in the month from number of day in the Hebrew year
1294 # Don't check Adar - if the day is not in Adar, we will stop before;
1295 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1296 $hebrewDay = $hebrewDayOfYear;
1299 while ( $hebrewMonth <= 12 ) {
1300 # Calculate days in this month
1301 if ( $isLeap && $hebrewMonth == 6 ) {
1302 # Adar in a leap year
1304 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1306 if ( $hebrewDay <= $days ) {
1310 # Subtract the days of Adar I
1311 $hebrewDay -= $days;
1314 if ( $hebrewDay <= $days ) {
1320 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1321 # Cheshvan in a complete year (otherwise as the rule below)
1323 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1324 # Kislev in an incomplete year (otherwise as the rule below)
1327 # Odd months have 30 days, even have 29
1328 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1330 if ( $hebrewDay <= $days ) {
1331 # In the current month
1334 # Subtract the days of the current month
1335 $hebrewDay -= $days;
1336 # Try in the next month
1341 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1345 * This calculates the Hebrew year start, as days since 1 September.
1346 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1347 * Used for Hebrew date.
1349 private static function hebrewYearStart( $year ) {
1350 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1351 $b = intval( ( $year - 1 ) %
4 );
1352 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1356 $Mar = intval( $m );
1362 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1363 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1365 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1367 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1371 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1376 * Algorithm to convert Gregorian dates to Thai solar dates,
1377 * Minguo dates or Minguo dates.
1379 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1380 * http://en.wikipedia.org/wiki/Minguo_calendar
1381 * http://en.wikipedia.org/wiki/Japanese_era_name
1383 * @param $ts String: 14-character timestamp
1384 * @param $cName String: calender name
1385 * @return Array: converted year, month, day
1387 private static function tsToYear( $ts, $cName ) {
1388 $gy = substr( $ts, 0, 4 );
1389 $gm = substr( $ts, 4, 2 );
1390 $gd = substr( $ts, 6, 2 );
1392 if ( !strcmp( $cName, 'thai' ) ) {
1394 # Add 543 years to the Gregorian calendar
1395 # Months and days are identical
1396 $gy_offset = $gy +
543;
1397 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1399 # Deduct 1911 years from the Gregorian calendar
1400 # Months and days are identical
1401 $gy_offset = $gy - 1911;
1402 } else if ( !strcmp( $cName, 'tenno' ) ) {
1403 # Nengō dates up to Meiji period
1404 # Deduct years from the Gregorian calendar
1405 # depending on the nengo periods
1406 # Months and days are identical
1407 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1409 $gy_gannen = $gy - 1868 +
1;
1410 $gy_offset = $gy_gannen;
1411 if ( $gy_gannen == 1 ) {
1414 $gy_offset = '明治' . $gy_offset;
1416 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1417 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1418 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1419 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1420 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1424 $gy_gannen = $gy - 1912 +
1;
1425 $gy_offset = $gy_gannen;
1426 if ( $gy_gannen == 1 ) {
1429 $gy_offset = '大正' . $gy_offset;
1431 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1432 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1433 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1437 $gy_gannen = $gy - 1926 +
1;
1438 $gy_offset = $gy_gannen;
1439 if ( $gy_gannen == 1 ) {
1442 $gy_offset = '昭和' . $gy_offset;
1445 $gy_gannen = $gy - 1989 +
1;
1446 $gy_offset = $gy_gannen;
1447 if ( $gy_gannen == 1 ) {
1450 $gy_offset = '平成' . $gy_offset;
1456 return array( $gy_offset, $gm, $gd );
1460 * Roman number formatting up to 3000
1462 static function romanNumeral( $num ) {
1463 static $table = array(
1464 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1465 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1466 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1467 array( '', 'M', 'MM', 'MMM' )
1470 $num = intval( $num );
1471 if ( $num > 3000 ||
$num <= 0 ) {
1476 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1477 if ( $num >= $pow10 ) {
1478 $s .= $table[$i][floor( $num / $pow10 )];
1480 $num = $num %
$pow10;
1486 * Hebrew Gematria number formatting up to 9999
1488 static function hebrewNumeral( $num ) {
1489 static $table = array(
1490 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1491 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1492 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1493 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1496 $num = intval( $num );
1497 if ( $num > 9999 ||
$num <= 0 ) {
1502 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1503 if ( $num >= $pow10 ) {
1504 if ( $num == 15 ||
$num == 16 ) {
1505 $s .= $table[0][9] . $table[0][$num - 9];
1508 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1509 if ( $pow10 == 1000 ) {
1514 $num = $num %
$pow10;
1516 if ( strlen( $s ) == 2 ) {
1519 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1520 $str .= substr( $s, strlen( $s ) - 2, 2 );
1522 $start = substr( $str, 0, strlen( $str ) - 2 );
1523 $end = substr( $str, strlen( $str ) - 2 );
1526 $str = $start . 'ך';
1529 $str = $start . 'ם';
1532 $str = $start . 'ן';
1535 $str = $start . 'ף';
1538 $str = $start . 'ץ';
1545 * This is meant to be used by time(), date(), and timeanddate() to get
1546 * the date preference they're supposed to use, it should be used in
1550 * function timeanddate([...], $format = true) {
1551 * $datePreference = $this->dateFormat($format);
1556 * @param $usePrefs Mixed: if true, the user's preference is used
1557 * if false, the site/language default is used
1558 * if int/string, assumed to be a format.
1561 function dateFormat( $usePrefs = true ) {
1564 if ( is_bool( $usePrefs ) ) {
1566 $datePreference = $wgUser->getDatePreference();
1568 $datePreference = (string)User
::getDefaultOption( 'date' );
1571 $datePreference = (string)$usePrefs;
1575 if ( $datePreference == '' ) {
1579 return $datePreference;
1583 * Get a format string for a given type and preference
1584 * @param $type May be date, time or both
1585 * @param $pref The format name as it appears in Messages*.php
1587 function getDateFormatString( $type, $pref ) {
1588 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1589 if ( $pref == 'default' ) {
1590 $pref = $this->getDefaultDateFormat();
1591 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1593 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1594 if ( is_null( $df ) ) {
1595 $pref = $this->getDefaultDateFormat();
1596 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1599 $this->dateFormatStrings
[$type][$pref] = $df;
1601 return $this->dateFormatStrings
[$type][$pref];
1605 * @param $ts Mixed: the time format which needs to be turned into a
1606 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1607 * @param $adj Bool: whether to adjust the time output according to the
1608 * user configured offset ($timecorrection)
1609 * @param $format Mixed: true to use user's date format preference
1610 * @param $timecorrection String: the time offset as returned by
1611 * validateTimeZone() in Special:Preferences
1614 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1615 $ts = wfTimestamp( TS_MW
, $ts );
1617 $ts = $this->userAdjust( $ts, $timecorrection );
1619 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1620 return $this->sprintfDate( $df, $ts );
1624 * @param $ts Mixed: the time format which needs to be turned into a
1625 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1626 * @param $adj Bool: whether to adjust the time output according to the
1627 * user configured offset ($timecorrection)
1628 * @param $format Mixed: true to use user's date format preference
1629 * @param $timecorrection String: the time offset as returned by
1630 * validateTimeZone() in Special:Preferences
1633 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1634 $ts = wfTimestamp( TS_MW
, $ts );
1636 $ts = $this->userAdjust( $ts, $timecorrection );
1638 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1639 return $this->sprintfDate( $df, $ts );
1643 * @param $ts Mixed: the time format which needs to be turned into a
1644 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1645 * @param $adj Bool: whether to adjust the time output according to the
1646 * user configured offset ($timecorrection)
1647 * @param $format Mixed: what format to return, if it's false output the
1648 * default one (default true)
1649 * @param $timecorrection String: the time offset as returned by
1650 * validateTimeZone() in Special:Preferences
1653 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1654 $ts = wfTimestamp( TS_MW
, $ts );
1656 $ts = $this->userAdjust( $ts, $timecorrection );
1658 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1659 return $this->sprintfDate( $df, $ts );
1662 function getMessage( $key ) {
1663 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1666 function getAllMessages() {
1667 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1670 function iconv( $in, $out, $string ) {
1671 # This is a wrapper for iconv in all languages except esperanto,
1672 # which does some nasty x-conversions beforehand
1674 # Even with //IGNORE iconv can whine about illegal characters in
1675 # *input* string. We just ignore those too.
1676 # REF: http://bugs.php.net/bug.php?id=37166
1677 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1678 wfSuppressWarnings();
1679 $text = iconv( $in, $out . '//IGNORE', $string );
1680 wfRestoreWarnings();
1684 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1685 function ucwordbreaksCallbackAscii( $matches ) {
1686 return $this->ucfirst( $matches[1] );
1689 function ucwordbreaksCallbackMB( $matches ) {
1690 return mb_strtoupper( $matches[0] );
1693 function ucCallback( $matches ) {
1694 list( $wikiUpperChars ) = self
::getCaseMaps();
1695 return strtr( $matches[1], $wikiUpperChars );
1698 function lcCallback( $matches ) {
1699 list( , $wikiLowerChars ) = self
::getCaseMaps();
1700 return strtr( $matches[1], $wikiLowerChars );
1703 function ucwordsCallbackMB( $matches ) {
1704 return mb_strtoupper( $matches[0] );
1707 function ucwordsCallbackWiki( $matches ) {
1708 list( $wikiUpperChars ) = self
::getCaseMaps();
1709 return strtr( $matches[0], $wikiUpperChars );
1713 * Make a string's first character uppercase
1715 function ucfirst( $str ) {
1717 if ( $o < 96 ) { // if already uppercase...
1719 } elseif ( $o < 128 ) {
1720 return ucfirst( $str ); // use PHP's ucfirst()
1722 // fall back to more complex logic in case of multibyte strings
1723 return $this->uc( $str, true );
1728 * Convert a string to uppercase
1730 function uc( $str, $first = false ) {
1731 if ( function_exists( 'mb_strtoupper' ) ) {
1733 if ( $this->isMultibyte( $str ) ) {
1734 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1736 return ucfirst( $str );
1739 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1742 if ( $this->isMultibyte( $str ) ) {
1743 $x = $first ?
'^' : '';
1744 return preg_replace_callback(
1745 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1746 array( $this, 'ucCallback' ),
1750 return $first ?
ucfirst( $str ) : strtoupper( $str );
1755 function lcfirst( $str ) {
1758 return strval( $str );
1759 } elseif ( $o >= 128 ) {
1760 return $this->lc( $str, true );
1761 } elseif ( $o > 96 ) {
1764 $str[0] = strtolower( $str[0] );
1769 function lc( $str, $first = false ) {
1770 if ( function_exists( 'mb_strtolower' ) ) {
1772 if ( $this->isMultibyte( $str ) ) {
1773 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1775 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1778 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1781 if ( $this->isMultibyte( $str ) ) {
1782 $x = $first ?
'^' : '';
1783 return preg_replace_callback(
1784 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1785 array( $this, 'lcCallback' ),
1789 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1794 function isMultibyte( $str ) {
1795 return (bool)preg_match( '/[\x80-\xff]/', $str );
1798 function ucwords( $str ) {
1799 if ( $this->isMultibyte( $str ) ) {
1800 $str = $this->lc( $str );
1802 // regexp to find first letter in each word (i.e. after each space)
1803 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1805 // function to use to capitalize a single char
1806 if ( function_exists( 'mb_strtoupper' ) ) {
1807 return preg_replace_callback(
1809 array( $this, 'ucwordsCallbackMB' ),
1813 return preg_replace_callback(
1815 array( $this, 'ucwordsCallbackWiki' ),
1820 return ucwords( strtolower( $str ) );
1824 # capitalize words at word breaks
1825 function ucwordbreaks( $str ) {
1826 if ( $this->isMultibyte( $str ) ) {
1827 $str = $this->lc( $str );
1829 // since \b doesn't work for UTF-8, we explicitely define word break chars
1830 $breaks = "[ \-\(\)\}\{\.,\?!]";
1832 // find first letter after word break
1833 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1835 if ( function_exists( 'mb_strtoupper' ) ) {
1836 return preg_replace_callback(
1838 array( $this, 'ucwordbreaksCallbackMB' ),
1842 return preg_replace_callback(
1844 array( $this, 'ucwordsCallbackWiki' ),
1849 return preg_replace_callback(
1850 '/\b([\w\x80-\xff]+)\b/',
1851 array( $this, 'ucwordbreaksCallbackAscii' ),
1858 * Return a case-folded representation of $s
1860 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1861 * and $s2 are the same except for the case of their characters. It is not
1862 * necessary for the value returned to make sense when displayed.
1864 * Do *not* perform any other normalisation in this function. If a caller
1865 * uses this function when it should be using a more general normalisation
1866 * function, then fix the caller.
1868 function caseFold( $s ) {
1869 return $this->uc( $s );
1872 function checkTitleEncoding( $s ) {
1873 if ( is_array( $s ) ) {
1874 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1876 # Check for non-UTF-8 URLs
1877 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1882 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1883 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1888 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1891 function fallback8bitEncoding() {
1892 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1896 * Most writing systems use whitespace to break up words.
1897 * Some languages such as Chinese don't conventionally do this,
1898 * which requires special handling when breaking up words for
1901 function hasWordBreaks() {
1906 * Some languages such as Chinese require word segmentation,
1907 * Specify such segmentation when overridden in derived class.
1909 * @param $string String
1912 function segmentByWord( $string ) {
1917 * Some languages have special punctuation need to be normalized.
1918 * Make such changes here.
1920 * @param $string String
1923 function normalizeForSearch( $string ) {
1924 return self
::convertDoubleWidth( $string );
1928 * convert double-width roman characters to single-width.
1929 * range: ff00-ff5f ~= 0020-007f
1931 protected static function convertDoubleWidth( $string ) {
1932 static $full = null;
1933 static $half = null;
1935 if ( $full === null ) {
1936 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1937 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1938 $full = str_split( $fullWidth, 3 );
1939 $half = str_split( $halfWidth );
1942 $string = str_replace( $full, $half, $string );
1946 protected static function insertSpace( $string, $pattern ) {
1947 $string = preg_replace( $pattern, " $1 ", $string );
1948 $string = preg_replace( '/ +/', ' ', $string );
1952 function convertForSearchResult( $termsArray ) {
1953 # some languages, e.g. Chinese, need to do a conversion
1954 # in order for search results to be displayed correctly
1959 * Get the first character of a string.
1964 function firstChar( $s ) {
1967 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1968 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1973 if ( isset( $matches[1] ) ) {
1974 if ( strlen( $matches[1] ) != 3 ) {
1978 // Break down Hangul syllables to grab the first jamo
1979 $code = utf8ToCodepoint( $matches[1] );
1980 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1982 } elseif ( $code < 0xb098 ) {
1983 return "\xe3\x84\xb1";
1984 } elseif ( $code < 0xb2e4 ) {
1985 return "\xe3\x84\xb4";
1986 } elseif ( $code < 0xb77c ) {
1987 return "\xe3\x84\xb7";
1988 } elseif ( $code < 0xb9c8 ) {
1989 return "\xe3\x84\xb9";
1990 } elseif ( $code < 0xbc14 ) {
1991 return "\xe3\x85\x81";
1992 } elseif ( $code < 0xc0ac ) {
1993 return "\xe3\x85\x82";
1994 } elseif ( $code < 0xc544 ) {
1995 return "\xe3\x85\x85";
1996 } elseif ( $code < 0xc790 ) {
1997 return "\xe3\x85\x87";
1998 } elseif ( $code < 0xcc28 ) {
1999 return "\xe3\x85\x88";
2000 } elseif ( $code < 0xce74 ) {
2001 return "\xe3\x85\x8a";
2002 } elseif ( $code < 0xd0c0 ) {
2003 return "\xe3\x85\x8b";
2004 } elseif ( $code < 0xd30c ) {
2005 return "\xe3\x85\x8c";
2006 } elseif ( $code < 0xd558 ) {
2007 return "\xe3\x85\x8d";
2009 return "\xe3\x85\x8e";
2016 function initEncoding() {
2017 # Some languages may have an alternate char encoding option
2018 # (Esperanto X-coding, Japanese furigana conversion, etc)
2019 # If this language is used as the primary content language,
2020 # an override to the defaults can be set here on startup.
2023 function recodeForEdit( $s ) {
2024 # For some languages we'll want to explicitly specify
2025 # which characters make it into the edit box raw
2026 # or are converted in some way or another.
2027 # Note that if wgOutputEncoding is different from
2028 # wgInputEncoding, this text will be further converted
2029 # to wgOutputEncoding.
2030 global $wgEditEncoding;
2031 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2034 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2038 function recodeInput( $s ) {
2039 # Take the previous into account.
2040 global $wgEditEncoding;
2041 if ( $wgEditEncoding != '' ) {
2042 $enc = $wgEditEncoding;
2046 if ( $enc == 'UTF-8' ) {
2049 return $this->iconv( $enc, 'UTF-8', $s );
2054 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2055 * also cleans up certain backwards-compatible sequences, converting them
2056 * to the modern Unicode equivalent.
2058 * This is language-specific for performance reasons only.
2060 function normalize( $s ) {
2061 global $wgAllUnicodeFixes;
2062 $s = UtfNormal
::cleanUp( $s );
2063 if ( $wgAllUnicodeFixes ) {
2064 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2065 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2072 * Transform a string using serialized data stored in the given file (which
2073 * must be in the serialized subdirectory of $IP). The file contains pairs
2074 * mapping source characters to destination characters.
2076 * The data is cached in process memory. This will go faster if you have the
2077 * FastStringSearch extension.
2079 function transformUsingPairFile( $file, $string ) {
2080 if ( !isset( $this->transformData
[$file] ) ) {
2081 $data = wfGetPrecompiledData( $file );
2082 if ( $data === false ) {
2083 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2085 $this->transformData
[$file] = new ReplacementArray( $data );
2087 return $this->transformData
[$file]->replace( $string );
2091 * For right-to-left language support
2096 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2100 * Return the correct HTML 'dir' attribute value for this language.
2104 return $this->isRTL() ?
'rtl' : 'ltr';
2108 * Return 'left' or 'right' as appropriate alignment for line-start
2109 * for this language's text direction.
2111 * Should be equivalent to CSS3 'start' text-align value....
2115 function alignStart() {
2116 return $this->isRTL() ?
'right' : 'left';
2120 * Return 'right' or 'left' as appropriate alignment for line-end
2121 * for this language's text direction.
2123 * Should be equivalent to CSS3 'end' text-align value....
2127 function alignEnd() {
2128 return $this->isRTL() ?
'left' : 'right';
2132 * A hidden direction mark (LRM or RLM), depending on the language direction
2136 function getDirMark() {
2137 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2140 function capitalizeAllNouns() {
2141 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2145 * An arrow, depending on the language direction
2149 function getArrow() {
2150 return $this->isRTL() ?
'←' : '→';
2154 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2158 function linkPrefixExtension() {
2159 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2162 function getMagicWords() {
2163 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2166 protected function doMagicHook() {
2167 if ( $this->mMagicHookDone
) {
2170 $this->mMagicHookDone
= true;
2171 wfProfileIn( 'LanguageGetMagic' );
2172 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2173 wfProfileOut( 'LanguageGetMagic' );
2176 # Fill a MagicWord object with data from here
2177 function getMagic( $mw ) {
2178 $this->doMagicHook();
2180 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2181 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2183 $magicWords = $this->getMagicWords();
2184 if ( isset( $magicWords[$mw->mId
] ) ) {
2185 $rawEntry = $magicWords[$mw->mId
];
2191 if ( !is_array( $rawEntry ) ) {
2192 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2194 $mw->mCaseSensitive
= $rawEntry[0];
2195 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2200 * Add magic words to the extension array
2202 function addMagicWordsByLang( $newWords ) {
2203 $code = $this->getCode();
2204 $fallbackChain = array();
2205 while ( $code && !in_array( $code, $fallbackChain ) ) {
2206 $fallbackChain[] = $code;
2207 $code = self
::getFallbackFor( $code );
2209 if ( !in_array( 'en', $fallbackChain ) ) {
2210 $fallbackChain[] = 'en';
2212 $fallbackChain = array_reverse( $fallbackChain );
2213 foreach ( $fallbackChain as $code ) {
2214 if ( isset( $newWords[$code] ) ) {
2215 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2221 * Get special page names, as an associative array
2222 * case folded alias => real name
2224 function getSpecialPageAliases() {
2225 // Cache aliases because it may be slow to load them
2226 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2228 $this->mExtendedSpecialPageAliases
=
2229 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2230 wfRunHooks( 'LanguageGetSpecialPageAliases',
2231 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2234 return $this->mExtendedSpecialPageAliases
;
2238 * Italic is unsuitable for some languages
2240 * @param $text String: the text to be emphasized.
2243 function emphasize( $text ) {
2244 return "<em>$text</em>";
2248 * Normally we output all numbers in plain en_US style, that is
2249 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2250 * point twohundredthirtyfive. However this is not sutable for all
2251 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2252 * Icelandic just want to use commas instead of dots, and dots instead
2253 * of commas like "293.291,235".
2255 * An example of this function being called:
2257 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2260 * See LanguageGu.php for the Gujarati implementation and
2261 * $separatorTransformTable on MessageIs.php for
2262 * the , => . and . => , implementation.
2264 * @todo check if it's viable to use localeconv() for the decimal
2266 * @param $number Mixed: the string to be formatted, should be an integer
2267 * or a floating point number.
2268 * @param $nocommafy Bool: set to true for special numbers like dates
2271 function formatNum( $number, $nocommafy = false ) {
2272 global $wgTranslateNumerals;
2273 if ( !$nocommafy ) {
2274 $number = $this->commafy( $number );
2275 $s = $this->separatorTransformTable();
2277 $number = strtr( $number, $s );
2281 if ( $wgTranslateNumerals ) {
2282 $s = $this->digitTransformTable();
2284 $number = strtr( $number, $s );
2291 function parseFormattedNumber( $number ) {
2292 $s = $this->digitTransformTable();
2294 $number = strtr( $number, array_flip( $s ) );
2297 $s = $this->separatorTransformTable();
2299 $number = strtr( $number, array_flip( $s ) );
2302 $number = strtr( $number, array( ',' => '' ) );
2307 * Adds commas to a given number
2312 function commafy( $_ ) {
2313 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2316 function digitTransformTable() {
2317 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2320 function separatorTransformTable() {
2321 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2325 * Take a list of strings and build a locale-friendly comma-separated
2326 * list, using the local comma-separator message.
2327 * The last two strings are chained with an "and".
2332 function listToText( $l ) {
2334 $m = count( $l ) - 1;
2336 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2338 for ( $i = $m; $i >= 0; $i-- ) {
2341 } else if ( $i == $m - 1 ) {
2342 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2344 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2352 * Take a list of strings and build a locale-friendly comma-separated
2353 * list, using the local comma-separator message.
2354 * @param $list array of strings to put in a comma list
2357 function commaList( $list ) {
2362 array( 'parsemag', 'escapenoentities', 'language' => $this )
2368 * Take a list of strings and build a locale-friendly semicolon-separated
2369 * list, using the local semicolon-separator message.
2370 * @param $list array of strings to put in a semicolon list
2373 function semicolonList( $list ) {
2377 'semicolon-separator',
2378 array( 'parsemag', 'escapenoentities', 'language' => $this )
2384 * Same as commaList, but separate it with the pipe instead.
2385 * @param $list array of strings to put in a pipe list
2388 function pipeList( $list ) {
2393 array( 'escapenoentities', 'language' => $this )
2399 * Truncate a string to a specified length in bytes, appending an optional
2400 * string (e.g. for ellipses)
2402 * The database offers limited byte lengths for some columns in the database;
2403 * multi-byte character sets mean we need to ensure that only whole characters
2404 * are included, otherwise broken characters can be passed to the user
2406 * If $length is negative, the string will be truncated from the beginning
2408 * @param $string String to truncate
2409 * @param $length Int: maximum length (including ellipses)
2410 * @param $ellipsis String to append to the truncated text
2411 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2412 * $adjustLength was introduced in 1.18, before that behaved as if false.
2415 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2416 # Use the localized ellipsis character
2417 if ( $ellipsis == '...' ) {
2418 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2420 # Check if there is no need to truncate
2421 if ( $length == 0 ) {
2422 return $ellipsis; // convention
2423 } elseif ( strlen( $string ) <= abs( $length ) ) {
2424 return $string; // no need to truncate
2426 $stringOriginal = $string;
2427 # If ellipsis length is >= $length then we can't apply $adjustLength
2428 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2429 $string = $ellipsis; // this can be slightly unexpected
2430 # Otherwise, truncate and add ellipsis...
2432 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2433 if ( $length > 0 ) {
2434 $length -= $eLength;
2435 $string = substr( $string, 0, $length ); // xyz...
2436 $string = $this->removeBadCharLast( $string );
2437 $string = $string . $ellipsis;
2439 $length +
= $eLength;
2440 $string = substr( $string, $length ); // ...xyz
2441 $string = $this->removeBadCharFirst( $string );
2442 $string = $ellipsis . $string;
2445 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2446 # This check is *not* redundant if $adjustLength, due to the single case where
2447 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2448 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2451 return $stringOriginal;
2456 * Remove bytes that represent an incomplete Unicode character
2457 * at the end of string (e.g. bytes of the char are missing)
2459 * @param $string String
2462 protected function removeBadCharLast( $string ) {
2463 if ( $string != '' ) {
2464 $char = ord( $string[strlen( $string ) - 1] );
2466 if ( $char >= 0xc0 ) {
2467 # We got the first byte only of a multibyte char; remove it.
2468 $string = substr( $string, 0, -1 );
2469 } elseif ( $char >= 0x80 &&
2470 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2471 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2473 # We chopped in the middle of a character; remove it
2481 * Remove bytes that represent an incomplete Unicode character
2482 * at the start of string (e.g. bytes of the char are missing)
2484 * @param $string String
2487 protected function removeBadCharFirst( $string ) {
2488 if ( $string != '' ) {
2489 $char = ord( $string[0] );
2490 if ( $char >= 0x80 && $char < 0xc0 ) {
2491 # We chopped in the middle of a character; remove the whole thing
2492 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2499 * Truncate a string of valid HTML to a specified length in bytes,
2500 * appending an optional string (e.g. for ellipses), and return valid HTML
2502 * This is only intended for styled/linked text, such as HTML with
2503 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2504 * Also, this will not detect things like "display:none" CSS.
2506 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2508 * @param string $text HTML string to truncate
2509 * @param int $length (zero/positive) Maximum length (including ellipses)
2510 * @param string $ellipsis String to append to the truncated text
2513 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2514 # Use the localized ellipsis character
2515 if ( $ellipsis == '...' ) {
2516 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2518 # Check if there is clearly no need to truncate
2519 if ( $length <= 0 ) {
2520 return $ellipsis; // no text shown, nothing to format (convention)
2521 } elseif ( strlen( $text ) <= $length ) {
2522 return $text; // string short enough even *with* HTML (short-circuit)
2525 $displayLen = 0; // innerHTML legth so far
2526 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2527 $tagType = 0; // 0-open, 1-close
2528 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2529 $entityState = 0; // 0-not entity, 1-entity
2530 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2531 $openTags = array(); // open tag stack
2532 $pOpenTags = array();
2534 $textLen = strlen( $text );
2535 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2536 for ( $pos = 0; true; ++
$pos ) {
2537 # Consider truncation once the display length has reached the maximim.
2538 # Check that we're not in the middle of a bracket/entity...
2539 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2540 if ( !$testingEllipsis ) {
2541 $testingEllipsis = true;
2542 # Save where we are; we will truncate here unless there turn out to
2543 # be so few remaining characters that truncation is not necessary.
2544 $pOpenTags = $openTags; // save state
2545 $pRet = $ret; // save state
2546 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2547 # String in fact does need truncation, the truncation point was OK.
2548 $openTags = $pOpenTags; // reload state
2549 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2550 $ret .= $ellipsis; // add ellipsis
2554 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2556 # Read the next char...
2558 $lastCh = $pos ?
$text[$pos - 1] : '';
2559 $ret .= $ch; // add to result string
2561 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2562 $entityState = 0; // for bad HTML
2563 $bracketState = 1; // tag started (checking for backslash)
2564 } elseif ( $ch == '>' ) {
2565 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2566 $entityState = 0; // for bad HTML
2567 $bracketState = 0; // out of brackets
2568 } elseif ( $bracketState == 1 ) {
2570 $tagType = 1; // close tag (e.g. "</span>")
2572 $tagType = 0; // open tag (e.g. "<span>")
2575 $bracketState = 2; // building tag name
2576 } elseif ( $bracketState == 2 ) {
2580 // Name found (e.g. "<a href=..."), add on tag attributes...
2581 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2583 } elseif ( $bracketState == 0 ) {
2584 if ( $entityState ) {
2587 $displayLen++
; // entity is one displayed char
2591 $entityState = 1; // entity found, (e.g. " ")
2593 $displayLen++
; // this char is displayed
2594 // Add the next $max display text chars after this in one swoop...
2595 $max = ( $testingEllipsis ?
$length : $neLength ) - $displayLen;
2596 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2597 $displayLen +
= $skipped;
2603 if ( $displayLen == 0 ) {
2604 return ''; // no text shown, nothing to format
2606 // Close the last tag if left unclosed by bad HTML
2607 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2608 while ( count( $openTags ) > 0 ) {
2609 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2614 // truncateHtml() helper function
2615 // like strcspn() but adds the skipped chars to $ret
2616 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2617 if ( $len === null ) {
2618 $len = -1; // -1 means "no limit" for strcspn
2619 } elseif ( $len < 0 ) {
2623 if ( $start < strlen( $text ) ) {
2624 $skipCount = strcspn( $text, $search, $start, $len );
2625 $ret .= substr( $text, $start, $skipCount );
2631 * truncateHtml() helper function
2632 * (a) push or pop $tag from $openTags as needed
2633 * (b) clear $tag value
2634 * @param String &$tag Current HTML tag name we are looking at
2635 * @param int $tagType (0-open tag, 1-close tag)
2636 * @param char $lastCh Character before the '>' that ended this tag
2637 * @param array &$openTags Open tag stack (not accounting for $tag)
2639 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2640 $tag = ltrim( $tag );
2642 if ( $tagType == 0 && $lastCh != '/' ) {
2643 $openTags[] = $tag; // tag opened (didn't close itself)
2644 } else if ( $tagType == 1 ) {
2645 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2646 array_pop( $openTags ); // tag closed
2654 * Grammatical transformations, needed for inflected languages
2655 * Invoked by putting {{grammar:case|word}} in a message
2657 * @param $word string
2658 * @param $case string
2661 function convertGrammar( $word, $case ) {
2662 global $wgGrammarForms;
2663 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2664 return $wgGrammarForms[$this->getCode()][$case][$word];
2670 * Provides an alternative text depending on specified gender.
2671 * Usage {{gender:username|masculine|feminine|neutral}}.
2672 * username is optional, in which case the gender of current user is used,
2673 * but only in (some) interface messages; otherwise default gender is used.
2674 * If second or third parameter are not specified, masculine is used.
2675 * These details may be overriden per language.
2677 function gender( $gender, $forms ) {
2678 if ( !count( $forms ) ) {
2681 $forms = $this->preConvertPlural( $forms, 2 );
2682 if ( $gender === 'male' ) {
2685 if ( $gender === 'female' ) {
2688 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2692 * Plural form transformations, needed for some languages.
2693 * For example, there are 3 form of plural in Russian and Polish,
2694 * depending on "count mod 10". See [[w:Plural]]
2695 * For English it is pretty simple.
2697 * Invoked by putting {{plural:count|wordform1|wordform2}}
2698 * or {{plural:count|wordform1|wordform2|wordform3}}
2700 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2702 * @param $count Integer: non-localized number
2703 * @param $forms Array: different plural forms
2704 * @return string Correct form of plural for $count in this language
2706 function convertPlural( $count, $forms ) {
2707 if ( !count( $forms ) ) {
2710 $forms = $this->preConvertPlural( $forms, 2 );
2712 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2716 * Checks that convertPlural was given an array and pads it to requested
2717 * amount of forms by copying the last one.
2719 * @param $count Integer: How many forms should there be at least
2720 * @param $forms Array of forms given to convertPlural
2721 * @return array Padded array of forms or an exception if not an array
2723 protected function preConvertPlural( /* Array */ $forms, $count ) {
2724 while ( count( $forms ) < $count ) {
2725 $forms[] = $forms[count( $forms ) - 1];
2731 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2732 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2733 * (which is an absolute timestamp).
2734 * @param $str String: the validated block duration in English
2735 * @return Somehow translated block duration
2736 * @see LanguageFi.php for example implementation
2738 function translateBlockExpiry( $str ) {
2739 foreach( SpecialBlock
::getSuggestedDurations( $this ) as $show => $value ){
2740 if ( strcmp( $str, $value ) == 0 ) {
2741 return htmlspecialchars( trim( $show ) );
2748 * languages like Chinese need to be segmented in order for the diff
2751 * @param $text String
2754 function segmentForDiff( $text ) {
2759 * and unsegment to show the result
2761 * @param $text String
2764 function unsegmentForDiff( $text ) {
2768 # convert text to all supported variants
2769 function autoConvertToAllVariants( $text ) {
2770 return $this->mConverter
->autoConvertToAllVariants( $text );
2773 # convert text to different variants of a language.
2774 function convert( $text ) {
2775 return $this->mConverter
->convert( $text );
2778 # Convert a Title object to a string in the preferred variant
2779 function convertTitle( $title ) {
2780 return $this->mConverter
->convertTitle( $title );
2783 # Check if this is a language with variants
2784 function hasVariants() {
2785 return sizeof( $this->getVariants() ) > 1;
2788 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2789 function armourMath( $text ) {
2790 return $this->mConverter
->armourMath( $text );
2794 * Perform output conversion on a string, and encode for safe HTML output.
2795 * @param $text String text to be converted
2796 * @param $isTitle Bool whether this conversion is for the article title
2798 * @todo this should get integrated somewhere sane
2800 function convertHtml( $text, $isTitle = false ) {
2801 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2804 function convertCategoryKey( $key ) {
2805 return $this->mConverter
->convertCategoryKey( $key );
2809 * Get the list of variants supported by this language
2810 * see sample implementation in LanguageZh.php
2812 * @return array an array of language codes
2814 function getVariants() {
2815 return $this->mConverter
->getVariants();
2818 function getPreferredVariant() {
2819 return $this->mConverter
->getPreferredVariant();
2822 function getDefaultVariant() {
2823 return $this->mConverter
->getDefaultVariant();
2826 function getURLVariant() {
2827 return $this->mConverter
->getURLVariant();
2831 * If a language supports multiple variants, it is
2832 * possible that non-existing link in one variant
2833 * actually exists in another variant. this function
2834 * tries to find it. See e.g. LanguageZh.php
2836 * @param $link String: the name of the link
2837 * @param $nt Mixed: the title object of the link
2838 * @param $ignoreOtherCond Boolean: to disable other conditions when
2839 * we need to transclude a template or update a category's link
2840 * @return null the input parameters may be modified upon return
2842 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2843 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2847 * If a language supports multiple variants, converts text
2848 * into an array of all possible variants of the text:
2849 * 'variant' => text in that variant
2851 * @deprecated Use autoConvertToAllVariants()
2853 function convertLinkToAllVariants( $text ) {
2854 return $this->mConverter
->convertLinkToAllVariants( $text );
2858 * returns language specific options used by User::getPageRenderHash()
2859 * for example, the preferred language variant
2863 function getExtraHashOptions() {
2864 return $this->mConverter
->getExtraHashOptions();
2868 * For languages that support multiple variants, the title of an
2869 * article may be displayed differently in different variants. this
2870 * function returns the apporiate title defined in the body of the article.
2874 function getParsedTitle() {
2875 return $this->mConverter
->getParsedTitle();
2879 * Enclose a string with the "no conversion" tag. This is used by
2880 * various functions in the Parser
2882 * @param $text String: text to be tagged for no conversion
2884 * @return string the tagged text
2886 function markNoConversion( $text, $noParse = false ) {
2887 return $this->mConverter
->markNoConversion( $text, $noParse );
2891 * A regular expression to match legal word-trailing characters
2892 * which should be merged onto a link of the form [[foo]]bar.
2896 function linkTrail() {
2897 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2900 function getLangObj() {
2905 * Get the RFC 3066 code for this language object
2907 function getCode() {
2908 return $this->mCode
;
2911 function setCode( $code ) {
2912 $this->mCode
= $code;
2916 * Get the name of a file for a certain language code
2917 * @param $prefix string Prepend this to the filename
2918 * @param $code string Language code
2919 * @param $suffix string Append this to the filename
2920 * @return string $prefix . $mangledCode . $suffix
2922 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2923 // Protect against path traversal
2924 if ( !Language
::isValidCode( $code )
2925 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2927 throw new MWException( "Invalid language code \"$code\"" );
2930 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2934 * Get the language code from a file name. Inverse of getFileName()
2935 * @param $filename string $prefix . $languageCode . $suffix
2936 * @param $prefix string Prefix before the language code
2937 * @param $suffix string Suffix after the language code
2938 * @return Language code, or false if $prefix or $suffix isn't found
2940 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2942 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2943 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2944 if ( !count( $m ) ) {
2947 return str_replace( '_', '-', strtolower( $m[1] ) );
2950 static function getMessagesFileName( $code ) {
2952 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2955 static function getClassFileName( $code ) {
2957 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2961 * Get the fallback for a given language
2963 static function getFallbackFor( $code ) {
2964 if ( $code === 'en' ) {
2968 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2973 * Get all messages for a given language
2974 * WARNING: this may take a long time
2976 static function getMessagesFor( $code ) {
2977 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2981 * Get a message for a given language
2983 static function getMessageFor( $key, $code ) {
2984 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2987 function fixVariableInNamespace( $talk ) {
2988 if ( strpos( $talk, '$1' ) === false ) {
2992 global $wgMetaNamespace;
2993 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2995 # Allow grammar transformations
2996 # Allowing full message-style parsing would make simple requests
2997 # such as action=raw much more expensive than they need to be.
2998 # This will hopefully cover most cases.
2999 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3000 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3001 return str_replace( ' ', '_', $talk );
3004 function replaceGrammarInNamespace( $m ) {
3005 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3008 static function getCaseMaps() {
3009 static $wikiUpperChars, $wikiLowerChars;
3010 if ( isset( $wikiUpperChars ) ) {
3011 return array( $wikiUpperChars, $wikiLowerChars );
3014 wfProfileIn( __METHOD__
);
3015 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3016 if ( $arr === false ) {
3017 throw new MWException(
3018 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3020 $wikiUpperChars = $arr['wikiUpperChars'];
3021 $wikiLowerChars = $arr['wikiLowerChars'];
3022 wfProfileOut( __METHOD__
);
3023 return array( $wikiUpperChars, $wikiLowerChars );
3027 * Decode an expiry (block, protection, etc) which has come from the DB
3029 * @param $expiry String: Database expiry String
3030 * @param $format Bool|Int true to process using language functions, or TS_ constant
3031 * to return the expiry in a given timestamp
3034 public function formatExpiry( $expiry, $format = true ) {
3035 static $infinity, $infinityMsg;
3036 if( $infinity === null ){
3037 $infinityMsg = wfMessage( 'infiniteblock' );
3038 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3041 if ( $expiry == '' ||
$expiry == $infinity ) {
3042 return $format === true
3046 return $format === true
3047 ?
$this->timeanddate( $expiry )
3048 : wfTimestamp( $format, $expiry );
3054 * @param $seconds String
3057 function formatTimePeriod( $seconds ) {
3058 if ( round( $seconds * 10 ) < 100 ) {
3059 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3060 } elseif ( round( $seconds ) < 60 ) {
3061 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3062 } elseif ( round( $seconds ) < 3600 ) {
3063 $minutes = floor( $seconds / 60 );
3064 $secondsPart = round( fmod( $seconds, 60 ) );
3065 if ( $secondsPart == 60 ) {
3069 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3070 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3072 $hours = floor( $seconds / 3600 );
3073 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3074 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3075 if ( $secondsPart == 60 ) {
3079 if ( $minutes == 60 ) {
3083 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3084 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3085 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3089 function formatBitrate( $bps ) {
3090 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3092 return $this->formatNum( $bps ) . $units[0];
3094 $unitIndex = floor( log10( $bps ) / 3 );
3095 $mantissa = $bps / pow( 1000, $unitIndex );
3096 if ( $mantissa < 10 ) {
3097 $mantissa = round( $mantissa, 1 );
3099 $mantissa = round( $mantissa );
3101 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3105 * Format a size in bytes for output, using an appropriate
3106 * unit (B, KB, MB or GB) according to the magnitude in question
3108 * @param $size Size to format
3109 * @return string Plain text (not HTML)
3111 function formatSize( $size ) {
3112 // For small sizes no decimal places necessary
3114 if ( $size > 1024 ) {
3115 $size = $size / 1024;
3116 if ( $size > 1024 ) {
3117 $size = $size / 1024;
3118 // For MB and bigger two decimal places are smarter
3120 if ( $size > 1024 ) {
3121 $size = $size / 1024;
3122 $msg = 'size-gigabytes';
3124 $msg = 'size-megabytes';
3127 $msg = 'size-kilobytes';
3130 $msg = 'size-bytes';
3132 $size = round( $size, $round );
3133 $text = $this->getMessageFromDB( $msg );
3134 return str_replace( '$1', $this->formatNum( $size ), $text );
3138 * Get the conversion rule title, if any.
3140 function getConvRuleTitle() {
3141 return $this->mConverter
->getConvRuleTitle();