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 // Preload base classes to work around APC/PHP5 bug
178 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
179 include_once( "$IP/languages/classes/$class.deps.php" );
181 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
182 include_once( "$IP/languages/classes/$class.php" );
186 if ( $recursionLevel > 5 ) {
187 throw new MWException( "Language fallback loop detected when creating class $class\n" );
190 if ( !class_exists( $class ) ) {
191 $fallback = Language
::getFallbackFor( $code );
193 $lang = Language
::newFromCode( $fallback );
195 $lang->setCode( $code );
203 * Returns true if a language code string is of a valid form, whether or
204 * not it exists. This includes codes which are used solely for
205 * customisation via the MediaWiki namespace.
207 public static function isValidCode( $code ) {
209 strcspn( $code, ":/\\\000" ) === strlen( $code )
210 && !preg_match( Title
::getTitleInvalidRegex(), $code );
214 * Returns true if a language code is of a valid form for the purposes of
215 * internal customisation of MediaWiki, via Messages*.php.
217 public static function isValidBuiltInCode( $code ) {
218 return preg_match( '/^[a-z0-9-]*$/', $code );
222 * Get the LocalisationCache instance
224 * @return LocalisationCache
226 public static function getLocalisationCache() {
227 if ( is_null( self
::$dataCache ) ) {
228 global $wgLocalisationCacheConf;
229 $class = $wgLocalisationCacheConf['class'];
230 self
::$dataCache = new $class( $wgLocalisationCacheConf );
232 return self
::$dataCache;
235 function __construct() {
236 $this->mConverter
= new FakeConverter( $this );
237 // Set the code to the name of the descendant
238 if ( get_class( $this ) == 'Language' ) {
241 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
243 self
::getLocalisationCache();
247 * Reduce memory usage
249 function __destruct() {
250 foreach ( $this as $name => $value ) {
251 unset( $this->$name );
256 * Hook which will be called if this is the content language.
257 * Descendants can use this to register hook functions or modify globals
259 function initContLang() { }
262 * @deprecated Use User::getDefaultOptions()
265 function getDefaultUserOptions() {
266 wfDeprecated( __METHOD__
);
267 return User
::getDefaultOptions();
270 function getFallbackLanguageCode() {
271 if ( $this->mCode
=== 'en' ) {
274 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
279 * Exports $wgBookstoreListEn
282 function getBookstoreList() {
283 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
289 function getNamespaces() {
290 if ( is_null( $this->namespaceNames
) ) {
291 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
293 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
294 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
296 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
298 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
299 if ( $wgMetaNamespaceTalk ) {
300 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
302 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
303 $this->namespaceNames
[NS_PROJECT_TALK
] =
304 $this->fixVariableInNamespace( $talk );
307 # Sometimes a language will be localised but not actually exist on this wiki.
308 foreach( $this->namespaceNames
as $key => $text ) {
309 if ( !isset( $validNamespaces[$key] ) ) {
310 unset( $this->namespaceNames
[$key] );
314 # The above mixing may leave namespaces out of canonical order.
315 # Re-order by namespace ID number...
316 ksort( $this->namespaceNames
);
318 return $this->namespaceNames
;
322 * A convenience function that returns the same thing as
323 * getNamespaces() except with the array values changed to ' '
324 * where it found '_', useful for producing output to be displayed
325 * e.g. in <select> forms.
329 function getFormattedNamespaces() {
330 $ns = $this->getNamespaces();
331 foreach ( $ns as $k => $v ) {
332 $ns[$k] = strtr( $v, '_', ' ' );
338 * Get a namespace value by key
340 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
341 * echo $mw_ns; // prints 'MediaWiki'
344 * @param $index Int: the array key of the namespace to return
345 * @return mixed, string if the namespace value exists, otherwise false
347 function getNsText( $index ) {
348 $ns = $this->getNamespaces();
349 return isset( $ns[$index] ) ?
$ns[$index] : false;
353 * A convenience function that returns the same thing as
354 * getNsText() except with '_' changed to ' ', useful for
359 function getFormattedNsText( $index ) {
360 $ns = $this->getNsText( $index );
361 return strtr( $ns, '_', ' ' );
365 * Returns gender-dependent namespace alias if available.
366 * @param $index Int: namespace index
367 * @param $gender String: gender key (male, female... )
371 function getGenderNsText( $index, $gender ) {
372 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
373 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
377 * Whether this language makes distinguishes genders for example in
382 function needsGenderDistinction() {
383 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
384 return count( $aliases ) > 0;
388 * Get a namespace key by value, case insensitive.
389 * Only matches namespace names for the current language, not the
390 * canonical ones defined in Namespace.php.
392 * @param $text String
393 * @return mixed An integer if $text is a valid value otherwise false
395 function getLocalNsIndex( $text ) {
396 $lctext = $this->lc( $text );
397 $ids = $this->getNamespaceIds();
398 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
401 function getNamespaceAliases() {
402 if ( is_null( $this->namespaceAliases
) ) {
403 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
407 foreach ( $aliases as $name => $index ) {
408 if ( $index === NS_PROJECT_TALK
) {
409 unset( $aliases[$name] );
410 $name = $this->fixVariableInNamespace( $name );
411 $aliases[$name] = $index;
416 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
417 foreach ( $genders as $index => $forms ) {
418 foreach ( $forms as $alias ) {
419 $aliases[$alias] = $index;
423 $this->namespaceAliases
= $aliases;
425 return $this->namespaceAliases
;
428 function getNamespaceIds() {
429 if ( is_null( $this->mNamespaceIds
) ) {
430 global $wgNamespaceAliases;
431 # Put namespace names and aliases into a hashtable.
432 # If this is too slow, then we should arrange it so that it is done
433 # before caching. The catch is that at pre-cache time, the above
434 # class-specific fixup hasn't been done.
435 $this->mNamespaceIds
= array();
436 foreach ( $this->getNamespaces() as $index => $name ) {
437 $this->mNamespaceIds
[$this->lc( $name )] = $index;
439 foreach ( $this->getNamespaceAliases() as $name => $index ) {
440 $this->mNamespaceIds
[$this->lc( $name )] = $index;
442 if ( $wgNamespaceAliases ) {
443 foreach ( $wgNamespaceAliases as $name => $index ) {
444 $this->mNamespaceIds
[$this->lc( $name )] = $index;
448 return $this->mNamespaceIds
;
453 * Get a namespace key by value, case insensitive. Canonical namespace
454 * names override custom ones defined for the current language.
456 * @param $text String
457 * @return mixed An integer if $text is a valid value otherwise false
459 function getNsIndex( $text ) {
460 $lctext = $this->lc( $text );
461 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
464 $ids = $this->getNamespaceIds();
465 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
469 * short names for language variants used for language conversion links.
471 * @param $code String
474 function getVariantname( $code ) {
475 return $this->getMessageFromDB( "variantname-$code" );
478 function specialPage( $name ) {
479 $aliases = $this->getSpecialPageAliases();
480 if ( isset( $aliases[$name][0] ) ) {
481 $name = $aliases[$name][0];
483 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
486 function getQuickbarSettings() {
488 $this->getMessage( 'qbsettings-none' ),
489 $this->getMessage( 'qbsettings-fixedleft' ),
490 $this->getMessage( 'qbsettings-fixedright' ),
491 $this->getMessage( 'qbsettings-floatingleft' ),
492 $this->getMessage( 'qbsettings-floatingright' )
496 function getMathNames() {
497 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
500 function getDatePreferences() {
501 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
504 function getDateFormats() {
505 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
508 function getDefaultDateFormat() {
509 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
510 if ( $df === 'dmy or mdy' ) {
511 global $wgAmericanDates;
512 return $wgAmericanDates ?
'mdy' : 'dmy';
518 function getDatePreferenceMigrationMap() {
519 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
522 function getImageFile( $image ) {
523 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
526 function getDefaultUserOptionOverrides() {
527 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
530 function getExtraUserToggles() {
531 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
534 function getUserToggle( $tog ) {
535 return $this->getMessageFromDB( "tog-$tog" );
539 * Get language names, indexed by code.
540 * If $customisedOnly is true, only returns codes with a messages file
542 public static function getLanguageNames( $customisedOnly = false ) {
543 global $wgLanguageNames, $wgExtraLanguageNames;
544 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
545 if ( !$customisedOnly ) {
551 $dir = opendir( "$IP/languages/messages" );
552 while ( false !== ( $file = readdir( $dir ) ) ) {
553 $code = self
::getCodeFromFileName( $file, 'Messages' );
554 if ( $code && isset( $allNames[$code] ) ) {
555 $names[$code] = $allNames[$code];
563 * Get translated language names. This is done on best effort and
564 * by default this is exactly the same as Language::getLanguageNames.
565 * The CLDR extension provides translated names.
566 * @param $code String Language code.
567 * @return Array language code => language name
570 public static function getTranslatedLanguageNames( $code ) {
572 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
574 foreach ( self
::getLanguageNames() as $code => $name ) {
575 if ( !isset( $names[$code] ) ) $names[$code] = $name;
582 * Get a message from the MediaWiki namespace.
584 * @param $msg String: message name
587 function getMessageFromDB( $msg ) {
588 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
591 function getLanguageName( $code ) {
592 $names = self
::getLanguageNames();
593 if ( !array_key_exists( $code, $names ) ) {
596 return $names[$code];
599 function getMonthName( $key ) {
600 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
603 function getMonthNameGen( $key ) {
604 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
607 function getMonthAbbreviation( $key ) {
608 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
611 function getWeekdayName( $key ) {
612 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
615 function getWeekdayAbbreviation( $key ) {
616 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
619 function getIranianCalendarMonthName( $key ) {
620 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
623 function getHebrewCalendarMonthName( $key ) {
624 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
627 function getHebrewCalendarMonthNameGen( $key ) {
628 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
631 function getHijriCalendarMonthName( $key ) {
632 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
636 * Used by date() and time() to adjust the time output.
638 * @param $ts Int the time in date('YmdHis') format
639 * @param $tz Mixed: adjust the time by this amount (default false, mean we
640 * get user timecorrection setting)
643 function userAdjust( $ts, $tz = false ) {
644 global $wgUser, $wgLocalTZoffset;
646 if ( $tz === false ) {
647 $tz = $wgUser->getOption( 'timecorrection' );
650 $data = explode( '|', $tz, 3 );
652 if ( $data[0] == 'ZoneInfo' ) {
653 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
654 $date = date_create( $ts, timezone_open( 'UTC' ) );
655 date_timezone_set( $date, timezone_open( $data[2] ) );
656 $date = date_format( $date, 'YmdHis' );
659 # Unrecognized timezone, default to 'Offset' with the stored offset.
664 if ( $data[0] == 'System' ||
$tz == '' ) {
665 # Global offset in minutes.
666 if ( isset( $wgLocalTZoffset ) ) {
667 $minDiff = $wgLocalTZoffset;
669 } else if ( $data[0] == 'Offset' ) {
670 $minDiff = intval( $data[1] );
672 $data = explode( ':', $tz );
673 if ( count( $data ) == 2 ) {
674 $data[0] = intval( $data[0] );
675 $data[1] = intval( $data[1] );
676 $minDiff = abs( $data[0] ) * 60 +
$data[1];
677 if ( $data[0] < 0 ) {
678 $minDiff = -$minDiff;
681 $minDiff = intval( $data[0] ) * 60;
685 # No difference ? Return time unchanged
686 if ( 0 == $minDiff ) {
690 wfSuppressWarnings(); // E_STRICT system time bitching
691 # Generate an adjusted date; take advantage of the fact that mktime
692 # will normalize out-of-range values so we don't have to split $minDiff
693 # into hours and minutes.
695 (int)substr( $ts, 8, 2 ) ), # Hours
696 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
697 (int)substr( $ts, 12, 2 ), # Seconds
698 (int)substr( $ts, 4, 2 ), # Month
699 (int)substr( $ts, 6, 2 ), # Day
700 (int)substr( $ts, 0, 4 ) ); # Year
702 $date = date( 'YmdHis', $t );
709 * This is a workalike of PHP's date() function, but with better
710 * internationalisation, a reduced set of format characters, and a better
713 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
714 * PHP manual for definitions. There are a number of extensions, which
717 * xn Do not translate digits of the next numeric format character
718 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
719 * xr Use roman numerals for the next numeric format character
720 * xh Use hebrew numerals for the next numeric format character
722 * xg Genitive month name
724 * xij j (day number) in Iranian calendar
725 * xiF F (month name) in Iranian calendar
726 * xin n (month number) in Iranian calendar
727 * xiY Y (full year) in Iranian calendar
729 * xjj j (day number) in Hebrew calendar
730 * xjF F (month name) in Hebrew calendar
731 * xjt t (days in month) in Hebrew calendar
732 * xjx xg (genitive month name) in Hebrew calendar
733 * xjn n (month number) in Hebrew calendar
734 * xjY Y (full year) in Hebrew calendar
736 * xmj j (day number) in Hijri calendar
737 * xmF F (month name) in Hijri calendar
738 * xmn n (month number) in Hijri calendar
739 * xmY Y (full year) in Hijri calendar
741 * xkY Y (full year) in Thai solar calendar. Months and days are
742 * identical to the Gregorian calendar
743 * xoY Y (full year) in Minguo calendar or Juche year.
744 * Months and days are identical to the
746 * xtY Y (full year) in Japanese nengo. Months and days are
747 * identical to the Gregorian calendar
749 * Characters enclosed in double quotes will be considered literal (with
750 * the quotes themselves removed). Unmatched quotes will be considered
751 * literal quotes. Example:
753 * "The month is" F => The month is January
756 * Backslash escaping is also supported.
758 * Input timestamp is assumed to be pre-normalized to the desired local
761 * @param $format String
762 * @param $ts String: 14-character timestamp
765 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
767 function sprintfDate( $format, $ts ) {
780 for ( $p = 0; $p < strlen( $format ); $p++
) {
783 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
784 $code .= $format[++
$p];
787 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
788 $code .= $format[++
$p];
799 $rawToggle = !$rawToggle;
808 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
811 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
812 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
815 $num = substr( $ts, 6, 2 );
818 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
819 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
822 $num = intval( substr( $ts, 6, 2 ) );
826 $iranian = self
::tsToIranian( $ts );
832 $hijri = self
::tsToHijri( $ts );
838 $hebrew = self
::tsToHebrew( $ts );
844 $unix = wfTimestamp( TS_UNIX
, $ts );
846 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
850 $unix = wfTimestamp( TS_UNIX
, $ts );
852 $w = gmdate( 'w', $unix );
857 $unix = wfTimestamp( TS_UNIX
, $ts );
859 $num = gmdate( 'w', $unix );
863 $unix = wfTimestamp( TS_UNIX
, $ts );
865 $num = gmdate( 'z', $unix );
869 $unix = wfTimestamp( TS_UNIX
, $ts );
871 $num = gmdate( 'W', $unix );
874 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
878 $iranian = self
::tsToIranian( $ts );
880 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
884 $hijri = self
::tsToHijri( $ts );
886 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
890 $hebrew = self
::tsToHebrew( $ts );
892 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
895 $num = substr( $ts, 4, 2 );
898 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
901 $num = intval( substr( $ts, 4, 2 ) );
905 $iranian = self
::tsToIranian( $ts );
911 $hijri = self
::tsToHijri ( $ts );
917 $hebrew = self
::tsToHebrew( $ts );
923 $unix = wfTimestamp( TS_UNIX
, $ts );
925 $num = gmdate( 't', $unix );
929 $hebrew = self
::tsToHebrew( $ts );
935 $unix = wfTimestamp( TS_UNIX
, $ts );
937 $num = gmdate( 'L', $unix );
941 $unix = wfTimestamp( TS_UNIX
, $ts );
943 $num = date( 'o', $unix );
946 $num = substr( $ts, 0, 4 );
950 $iranian = self
::tsToIranian( $ts );
956 $hijri = self
::tsToHijri( $ts );
962 $hebrew = self
::tsToHebrew( $ts );
968 $thai = self
::tsToYear( $ts, 'thai' );
974 $minguo = self
::tsToYear( $ts, 'minguo' );
980 $tenno = self
::tsToYear( $ts, 'tenno' );
985 $num = substr( $ts, 2, 2 );
988 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
991 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
994 $h = substr( $ts, 8, 2 );
995 $num = $h %
12 ?
$h %
12 : 12;
998 $num = intval( substr( $ts, 8, 2 ) );
1001 $h = substr( $ts, 8, 2 );
1002 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1005 $num = substr( $ts, 8, 2 );
1008 $num = substr( $ts, 10, 2 );
1011 $num = substr( $ts, 12, 2 );
1015 $unix = wfTimestamp( TS_UNIX
, $ts );
1017 $s .= gmdate( 'c', $unix );
1021 $unix = wfTimestamp( TS_UNIX
, $ts );
1023 $s .= gmdate( 'r', $unix );
1027 $unix = wfTimestamp( TS_UNIX
, $ts );
1032 # Backslash escaping
1033 if ( $p < strlen( $format ) - 1 ) {
1034 $s .= $format[++
$p];
1041 if ( $p < strlen( $format ) - 1 ) {
1042 $endQuote = strpos( $format, '"', $p +
1 );
1043 if ( $endQuote === false ) {
1044 # No terminating quote, assume literal "
1047 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1051 # Quote at end of string, assume literal "
1058 if ( $num !== false ) {
1059 if ( $rawToggle ||
$raw ) {
1062 } elseif ( $roman ) {
1063 $s .= self
::romanNumeral( $num );
1065 } elseif ( $hebrewNum ) {
1066 $s .= self
::hebrewNumeral( $num );
1069 $s .= $this->formatNum( $num, true );
1076 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1077 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1079 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1080 * Gregorian dates to Iranian dates. Originally written in C, it
1081 * is released under the terms of GNU Lesser General Public
1082 * License. Conversion to PHP was performed by Niklas Laxström.
1084 * Link: http://www.farsiweb.info/jalali/jalali.c
1086 private static function tsToIranian( $ts ) {
1087 $gy = substr( $ts, 0, 4 ) -1600;
1088 $gm = substr( $ts, 4, 2 ) -1;
1089 $gd = substr( $ts, 6, 2 ) -1;
1091 # Days passed from the beginning (including leap years)
1093 +
floor( ( $gy +
3 ) / 4 )
1094 - floor( ( $gy +
99 ) / 100 )
1095 +
floor( ( $gy +
399 ) / 400 );
1098 // Add days of the past months of this year
1099 for ( $i = 0; $i < $gm; $i++
) {
1100 $gDayNo +
= self
::$GREG_DAYS[$i];
1104 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1108 // Days passed in current month
1111 $jDayNo = $gDayNo - 79;
1113 $jNp = floor( $jDayNo / 12053 );
1116 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1119 if ( $jDayNo >= 366 ) {
1120 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1121 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1124 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1125 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1131 return array( $jy, $jm, $jd );
1135 * Converting Gregorian dates to Hijri dates.
1137 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1139 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1141 private static function tsToHijri( $ts ) {
1142 $year = substr( $ts, 0, 4 );
1143 $month = substr( $ts, 4, 2 );
1144 $day = substr( $ts, 6, 2 );
1152 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1153 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1156 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1157 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1158 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1161 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1162 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1165 $zl = $zjd -1948440 +
10632;
1166 $zn = (int)( ( $zl - 1 ) / 10631 );
1167 $zl = $zl - 10631 * $zn +
354;
1168 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1169 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1170 $zm = (int)( ( 24 * $zl ) / 709 );
1171 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1172 $zy = 30 * $zn +
$zj - 30;
1174 return array( $zy, $zm, $zd );
1178 * Converting Gregorian dates to Hebrew dates.
1180 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1181 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1182 * to translate the relevant functions into PHP and release them under
1185 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1186 * and Adar II is 14. In a non-leap year, Adar is 6.
1188 private static function tsToHebrew( $ts ) {
1190 $year = substr( $ts, 0, 4 );
1191 $month = substr( $ts, 4, 2 );
1192 $day = substr( $ts, 6, 2 );
1194 # Calculate Hebrew year
1195 $hebrewYear = $year +
3760;
1197 # Month number when September = 1, August = 12
1199 if ( $month > 12 ) {
1206 # Calculate day of year from 1 September
1208 for ( $i = 1; $i < $month; $i++
) {
1212 # Check if the year is leap
1213 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1216 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1223 # Calculate the start of the Hebrew year
1224 $start = self
::hebrewYearStart( $hebrewYear );
1226 # Calculate next year's start
1227 if ( $dayOfYear <= $start ) {
1228 # Day is before the start of the year - it is the previous year
1230 $nextStart = $start;
1234 # Add days since previous year's 1 September
1236 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1240 # Start of the new (previous) year
1241 $start = self
::hebrewYearStart( $hebrewYear );
1244 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1247 # Calculate Hebrew day of year
1248 $hebrewDayOfYear = $dayOfYear - $start;
1250 # Difference between year's days
1251 $diff = $nextStart - $start;
1252 # Add 12 (or 13 for leap years) days to ignore the difference between
1253 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1254 # difference is only about the year type
1255 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1261 # Check the year pattern, and is leap year
1262 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1263 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1264 # and non-leap years
1265 $yearPattern = $diff %
30;
1266 # Check if leap year
1267 $isLeap = $diff >= 30;
1269 # Calculate day in the month from number of day in the Hebrew year
1270 # Don't check Adar - if the day is not in Adar, we will stop before;
1271 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1272 $hebrewDay = $hebrewDayOfYear;
1275 while ( $hebrewMonth <= 12 ) {
1276 # Calculate days in this month
1277 if ( $isLeap && $hebrewMonth == 6 ) {
1278 # Adar in a leap year
1280 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1282 if ( $hebrewDay <= $days ) {
1286 # Subtract the days of Adar I
1287 $hebrewDay -= $days;
1290 if ( $hebrewDay <= $days ) {
1296 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1297 # Cheshvan in a complete year (otherwise as the rule below)
1299 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1300 # Kislev in an incomplete year (otherwise as the rule below)
1303 # Odd months have 30 days, even have 29
1304 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1306 if ( $hebrewDay <= $days ) {
1307 # In the current month
1310 # Subtract the days of the current month
1311 $hebrewDay -= $days;
1312 # Try in the next month
1317 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1321 * This calculates the Hebrew year start, as days since 1 September.
1322 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1323 * Used for Hebrew date.
1325 private static function hebrewYearStart( $year ) {
1326 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1327 $b = intval( ( $year - 1 ) %
4 );
1328 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1332 $Mar = intval( $m );
1338 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1339 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1341 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1343 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1347 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1352 * Algorithm to convert Gregorian dates to Thai solar dates,
1353 * Minguo dates or Minguo dates.
1355 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1356 * http://en.wikipedia.org/wiki/Minguo_calendar
1357 * http://en.wikipedia.org/wiki/Japanese_era_name
1359 * @param $ts String: 14-character timestamp
1360 * @param $cName String: calender name
1361 * @return Array: converted year, month, day
1363 private static function tsToYear( $ts, $cName ) {
1364 $gy = substr( $ts, 0, 4 );
1365 $gm = substr( $ts, 4, 2 );
1366 $gd = substr( $ts, 6, 2 );
1368 if ( !strcmp( $cName, 'thai' ) ) {
1370 # Add 543 years to the Gregorian calendar
1371 # Months and days are identical
1372 $gy_offset = $gy +
543;
1373 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1375 # Deduct 1911 years from the Gregorian calendar
1376 # Months and days are identical
1377 $gy_offset = $gy - 1911;
1378 } else if ( !strcmp( $cName, 'tenno' ) ) {
1379 # Nengō dates up to Meiji period
1380 # Deduct years from the Gregorian calendar
1381 # depending on the nengo periods
1382 # Months and days are identical
1383 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1385 $gy_gannen = $gy - 1868 +
1;
1386 $gy_offset = $gy_gannen;
1387 if ( $gy_gannen == 1 ) {
1390 $gy_offset = '明治' . $gy_offset;
1392 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1393 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1394 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1395 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1396 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1400 $gy_gannen = $gy - 1912 +
1;
1401 $gy_offset = $gy_gannen;
1402 if ( $gy_gannen == 1 ) {
1405 $gy_offset = '大正' . $gy_offset;
1407 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1408 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1409 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1413 $gy_gannen = $gy - 1926 +
1;
1414 $gy_offset = $gy_gannen;
1415 if ( $gy_gannen == 1 ) {
1418 $gy_offset = '昭和' . $gy_offset;
1421 $gy_gannen = $gy - 1989 +
1;
1422 $gy_offset = $gy_gannen;
1423 if ( $gy_gannen == 1 ) {
1426 $gy_offset = '平成' . $gy_offset;
1432 return array( $gy_offset, $gm, $gd );
1436 * Roman number formatting up to 3000
1438 static function romanNumeral( $num ) {
1439 static $table = array(
1440 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1441 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1442 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1443 array( '', 'M', 'MM', 'MMM' )
1446 $num = intval( $num );
1447 if ( $num > 3000 ||
$num <= 0 ) {
1452 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1453 if ( $num >= $pow10 ) {
1454 $s .= $table[$i][floor( $num / $pow10 )];
1456 $num = $num %
$pow10;
1462 * Hebrew Gematria number formatting up to 9999
1464 static function hebrewNumeral( $num ) {
1465 static $table = array(
1466 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1467 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1468 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1469 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1472 $num = intval( $num );
1473 if ( $num > 9999 ||
$num <= 0 ) {
1478 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1479 if ( $num >= $pow10 ) {
1480 if ( $num == 15 ||
$num == 16 ) {
1481 $s .= $table[0][9] . $table[0][$num - 9];
1484 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1485 if ( $pow10 == 1000 ) {
1490 $num = $num %
$pow10;
1492 if ( strlen( $s ) == 2 ) {
1495 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1496 $str .= substr( $s, strlen( $s ) - 2, 2 );
1498 $start = substr( $str, 0, strlen( $str ) - 2 );
1499 $end = substr( $str, strlen( $str ) - 2 );
1502 $str = $start . 'ך';
1505 $str = $start . 'ם';
1508 $str = $start . 'ן';
1511 $str = $start . 'ף';
1514 $str = $start . 'ץ';
1521 * This is meant to be used by time(), date(), and timeanddate() to get
1522 * the date preference they're supposed to use, it should be used in
1526 * function timeanddate([...], $format = true) {
1527 * $datePreference = $this->dateFormat($format);
1532 * @param $usePrefs Mixed: if true, the user's preference is used
1533 * if false, the site/language default is used
1534 * if int/string, assumed to be a format.
1537 function dateFormat( $usePrefs = true ) {
1540 if ( is_bool( $usePrefs ) ) {
1542 $datePreference = $wgUser->getDatePreference();
1544 $datePreference = (string)User
::getDefaultOption( 'date' );
1547 $datePreference = (string)$usePrefs;
1551 if ( $datePreference == '' ) {
1555 return $datePreference;
1559 * Get a format string for a given type and preference
1560 * @param $type May be date, time or both
1561 * @param $pref The format name as it appears in Messages*.php
1563 function getDateFormatString( $type, $pref ) {
1564 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1565 if ( $pref == 'default' ) {
1566 $pref = $this->getDefaultDateFormat();
1567 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1569 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1570 if ( is_null( $df ) ) {
1571 $pref = $this->getDefaultDateFormat();
1572 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1575 $this->dateFormatStrings
[$type][$pref] = $df;
1577 return $this->dateFormatStrings
[$type][$pref];
1581 * @param $ts Mixed: the time format which needs to be turned into a
1582 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1583 * @param $adj Bool: whether to adjust the time output according to the
1584 * user configured offset ($timecorrection)
1585 * @param $format Mixed: true to use user's date format preference
1586 * @param $timecorrection String: the time offset as returned by
1587 * validateTimeZone() in Special:Preferences
1590 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1591 $ts = wfTimestamp( TS_MW
, $ts );
1593 $ts = $this->userAdjust( $ts, $timecorrection );
1595 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1596 return $this->sprintfDate( $df, $ts );
1600 * @param $ts Mixed: the time format which needs to be turned into a
1601 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1602 * @param $adj Bool: whether to adjust the time output according to the
1603 * user configured offset ($timecorrection)
1604 * @param $format Mixed: true to use user's date format preference
1605 * @param $timecorrection String: the time offset as returned by
1606 * validateTimeZone() in Special:Preferences
1609 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1610 $ts = wfTimestamp( TS_MW
, $ts );
1612 $ts = $this->userAdjust( $ts, $timecorrection );
1614 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1615 return $this->sprintfDate( $df, $ts );
1619 * @param $ts Mixed: the time format which needs to be turned into a
1620 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1621 * @param $adj Bool: whether to adjust the time output according to the
1622 * user configured offset ($timecorrection)
1623 * @param $format Mixed: what format to return, if it's false output the
1624 * default one (default true)
1625 * @param $timecorrection String: the time offset as returned by
1626 * validateTimeZone() in Special:Preferences
1629 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1630 $ts = wfTimestamp( TS_MW
, $ts );
1632 $ts = $this->userAdjust( $ts, $timecorrection );
1634 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1635 return $this->sprintfDate( $df, $ts );
1638 function getMessage( $key ) {
1639 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1642 function getAllMessages() {
1643 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1646 function iconv( $in, $out, $string ) {
1647 # This is a wrapper for iconv in all languages except esperanto,
1648 # which does some nasty x-conversions beforehand
1650 # Even with //IGNORE iconv can whine about illegal characters in
1651 # *input* string. We just ignore those too.
1652 # REF: http://bugs.php.net/bug.php?id=37166
1653 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1654 wfSuppressWarnings();
1655 $text = iconv( $in, $out . '//IGNORE', $string );
1656 wfRestoreWarnings();
1660 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1661 function ucwordbreaksCallbackAscii( $matches ) {
1662 return $this->ucfirst( $matches[1] );
1665 function ucwordbreaksCallbackMB( $matches ) {
1666 return mb_strtoupper( $matches[0] );
1669 function ucCallback( $matches ) {
1670 list( $wikiUpperChars ) = self
::getCaseMaps();
1671 return strtr( $matches[1], $wikiUpperChars );
1674 function lcCallback( $matches ) {
1675 list( , $wikiLowerChars ) = self
::getCaseMaps();
1676 return strtr( $matches[1], $wikiLowerChars );
1679 function ucwordsCallbackMB( $matches ) {
1680 return mb_strtoupper( $matches[0] );
1683 function ucwordsCallbackWiki( $matches ) {
1684 list( $wikiUpperChars ) = self
::getCaseMaps();
1685 return strtr( $matches[0], $wikiUpperChars );
1689 * Make a string's first character uppercase
1691 function ucfirst( $str ) {
1693 if ( $o < 96 ) { // if already uppercase...
1695 } elseif ( $o < 128 ) {
1696 return ucfirst( $str ); // use PHP's ucfirst()
1698 // fall back to more complex logic in case of multibyte strings
1699 return $this->uc( $str, true );
1704 * Convert a string to uppercase
1706 function uc( $str, $first = false ) {
1707 if ( function_exists( 'mb_strtoupper' ) ) {
1709 if ( $this->isMultibyte( $str ) ) {
1710 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1712 return ucfirst( $str );
1715 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1718 if ( $this->isMultibyte( $str ) ) {
1719 $x = $first ?
'^' : '';
1720 return preg_replace_callback(
1721 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1722 array( $this, 'ucCallback' ),
1726 return $first ?
ucfirst( $str ) : strtoupper( $str );
1731 function lcfirst( $str ) {
1734 return strval( $str );
1735 } elseif ( $o >= 128 ) {
1736 return $this->lc( $str, true );
1737 } elseif ( $o > 96 ) {
1740 $str[0] = strtolower( $str[0] );
1745 function lc( $str, $first = false ) {
1746 if ( function_exists( 'mb_strtolower' ) ) {
1748 if ( $this->isMultibyte( $str ) ) {
1749 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1751 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1754 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1757 if ( $this->isMultibyte( $str ) ) {
1758 $x = $first ?
'^' : '';
1759 return preg_replace_callback(
1760 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1761 array( $this, 'lcCallback' ),
1765 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1770 function isMultibyte( $str ) {
1771 return (bool)preg_match( '/[\x80-\xff]/', $str );
1774 function ucwords( $str ) {
1775 if ( $this->isMultibyte( $str ) ) {
1776 $str = $this->lc( $str );
1778 // regexp to find first letter in each word (i.e. after each space)
1779 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1781 // function to use to capitalize a single char
1782 if ( function_exists( 'mb_strtoupper' ) ) {
1783 return preg_replace_callback(
1785 array( $this, 'ucwordsCallbackMB' ),
1789 return preg_replace_callback(
1791 array( $this, 'ucwordsCallbackWiki' ),
1796 return ucwords( strtolower( $str ) );
1800 # capitalize words at word breaks
1801 function ucwordbreaks( $str ) {
1802 if ( $this->isMultibyte( $str ) ) {
1803 $str = $this->lc( $str );
1805 // since \b doesn't work for UTF-8, we explicitely define word break chars
1806 $breaks = "[ \-\(\)\}\{\.,\?!]";
1808 // find first letter after word break
1809 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1811 if ( function_exists( 'mb_strtoupper' ) ) {
1812 return preg_replace_callback(
1814 array( $this, 'ucwordbreaksCallbackMB' ),
1818 return preg_replace_callback(
1820 array( $this, 'ucwordsCallbackWiki' ),
1825 return preg_replace_callback(
1826 '/\b([\w\x80-\xff]+)\b/',
1827 array( $this, 'ucwordbreaksCallbackAscii' ),
1834 * Return a case-folded representation of $s
1836 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1837 * and $s2 are the same except for the case of their characters. It is not
1838 * necessary for the value returned to make sense when displayed.
1840 * Do *not* perform any other normalisation in this function. If a caller
1841 * uses this function when it should be using a more general normalisation
1842 * function, then fix the caller.
1844 function caseFold( $s ) {
1845 return $this->uc( $s );
1848 function checkTitleEncoding( $s ) {
1849 if ( is_array( $s ) ) {
1850 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1852 # Check for non-UTF-8 URLs
1853 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1858 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1859 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1864 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1867 function fallback8bitEncoding() {
1868 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1872 * Most writing systems use whitespace to break up words.
1873 * Some languages such as Chinese don't conventionally do this,
1874 * which requires special handling when breaking up words for
1877 function hasWordBreaks() {
1882 * Some languages such as Chinese require word segmentation,
1883 * Specify such segmentation when overridden in derived class.
1885 * @param $string String
1888 function segmentByWord( $string ) {
1893 * Some languages have special punctuation need to be normalized.
1894 * Make such changes here.
1896 * @param $string String
1899 function normalizeForSearch( $string ) {
1900 return self
::convertDoubleWidth( $string );
1904 * convert double-width roman characters to single-width.
1905 * range: ff00-ff5f ~= 0020-007f
1907 protected static function convertDoubleWidth( $string ) {
1908 static $full = null;
1909 static $half = null;
1911 if ( $full === null ) {
1912 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1913 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1914 $full = str_split( $fullWidth, 3 );
1915 $half = str_split( $halfWidth );
1918 $string = str_replace( $full, $half, $string );
1922 protected static function insertSpace( $string, $pattern ) {
1923 $string = preg_replace( $pattern, " $1 ", $string );
1924 $string = preg_replace( '/ +/', ' ', $string );
1928 function convertForSearchResult( $termsArray ) {
1929 # some languages, e.g. Chinese, need to do a conversion
1930 # in order for search results to be displayed correctly
1935 * Get the first character of a string.
1940 function firstChar( $s ) {
1943 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1944 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1949 if ( isset( $matches[1] ) ) {
1950 if ( strlen( $matches[1] ) != 3 ) {
1954 // Break down Hangul syllables to grab the first jamo
1955 $code = utf8ToCodepoint( $matches[1] );
1956 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1958 } elseif ( $code < 0xb098 ) {
1959 return "\xe3\x84\xb1";
1960 } elseif ( $code < 0xb2e4 ) {
1961 return "\xe3\x84\xb4";
1962 } elseif ( $code < 0xb77c ) {
1963 return "\xe3\x84\xb7";
1964 } elseif ( $code < 0xb9c8 ) {
1965 return "\xe3\x84\xb9";
1966 } elseif ( $code < 0xbc14 ) {
1967 return "\xe3\x85\x81";
1968 } elseif ( $code < 0xc0ac ) {
1969 return "\xe3\x85\x82";
1970 } elseif ( $code < 0xc544 ) {
1971 return "\xe3\x85\x85";
1972 } elseif ( $code < 0xc790 ) {
1973 return "\xe3\x85\x87";
1974 } elseif ( $code < 0xcc28 ) {
1975 return "\xe3\x85\x88";
1976 } elseif ( $code < 0xce74 ) {
1977 return "\xe3\x85\x8a";
1978 } elseif ( $code < 0xd0c0 ) {
1979 return "\xe3\x85\x8b";
1980 } elseif ( $code < 0xd30c ) {
1981 return "\xe3\x85\x8c";
1982 } elseif ( $code < 0xd558 ) {
1983 return "\xe3\x85\x8d";
1985 return "\xe3\x85\x8e";
1992 function initEncoding() {
1993 # Some languages may have an alternate char encoding option
1994 # (Esperanto X-coding, Japanese furigana conversion, etc)
1995 # If this language is used as the primary content language,
1996 # an override to the defaults can be set here on startup.
1999 function recodeForEdit( $s ) {
2000 # For some languages we'll want to explicitly specify
2001 # which characters make it into the edit box raw
2002 # or are converted in some way or another.
2003 # Note that if wgOutputEncoding is different from
2004 # wgInputEncoding, this text will be further converted
2005 # to wgOutputEncoding.
2006 global $wgEditEncoding;
2007 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2010 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2014 function recodeInput( $s ) {
2015 # Take the previous into account.
2016 global $wgEditEncoding;
2017 if ( $wgEditEncoding != '' ) {
2018 $enc = $wgEditEncoding;
2022 if ( $enc == 'UTF-8' ) {
2025 return $this->iconv( $enc, 'UTF-8', $s );
2030 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2031 * also cleans up certain backwards-compatible sequences, converting them
2032 * to the modern Unicode equivalent.
2034 * This is language-specific for performance reasons only.
2036 function normalize( $s ) {
2037 global $wgAllUnicodeFixes;
2038 $s = UtfNormal
::cleanUp( $s );
2039 if ( $wgAllUnicodeFixes ) {
2040 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2041 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2048 * Transform a string using serialized data stored in the given file (which
2049 * must be in the serialized subdirectory of $IP). The file contains pairs
2050 * mapping source characters to destination characters.
2052 * The data is cached in process memory. This will go faster if you have the
2053 * FastStringSearch extension.
2055 function transformUsingPairFile( $file, $string ) {
2056 if ( !isset( $this->transformData
[$file] ) ) {
2057 $data = wfGetPrecompiledData( $file );
2058 if ( $data === false ) {
2059 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2061 $this->transformData
[$file] = new ReplacementArray( $data );
2063 return $this->transformData
[$file]->replace( $string );
2067 * For right-to-left language support
2072 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2076 * Return the correct HTML 'dir' attribute value for this language.
2080 return $this->isRTL() ?
'rtl' : 'ltr';
2084 * Return 'left' or 'right' as appropriate alignment for line-start
2085 * for this language's text direction.
2087 * Should be equivalent to CSS3 'start' text-align value....
2091 function alignStart() {
2092 return $this->isRTL() ?
'right' : 'left';
2096 * Return 'right' or 'left' as appropriate alignment for line-end
2097 * for this language's text direction.
2099 * Should be equivalent to CSS3 'end' text-align value....
2103 function alignEnd() {
2104 return $this->isRTL() ?
'left' : 'right';
2108 * A hidden direction mark (LRM or RLM), depending on the language direction
2112 function getDirMark() {
2113 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2116 function capitalizeAllNouns() {
2117 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2121 * An arrow, depending on the language direction
2125 function getArrow() {
2126 return $this->isRTL() ?
'←' : '→';
2130 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2134 function linkPrefixExtension() {
2135 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2138 function getMagicWords() {
2139 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2142 protected function doMagicHook() {
2143 if ( $this->mMagicHookDone
) {
2146 $this->mMagicHookDone
= true;
2147 wfProfileIn( 'LanguageGetMagic' );
2148 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2149 wfProfileOut( 'LanguageGetMagic' );
2152 # Fill a MagicWord object with data from here
2153 function getMagic( $mw ) {
2154 $this->doMagicHook();
2156 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2157 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2159 $magicWords = $this->getMagicWords();
2160 if ( isset( $magicWords[$mw->mId
] ) ) {
2161 $rawEntry = $magicWords[$mw->mId
];
2167 if ( !is_array( $rawEntry ) ) {
2168 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2170 $mw->mCaseSensitive
= $rawEntry[0];
2171 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2176 * Add magic words to the extension array
2178 function addMagicWordsByLang( $newWords ) {
2179 $code = $this->getCode();
2180 $fallbackChain = array();
2181 while ( $code && !in_array( $code, $fallbackChain ) ) {
2182 $fallbackChain[] = $code;
2183 $code = self
::getFallbackFor( $code );
2185 if ( !in_array( 'en', $fallbackChain ) ) {
2186 $fallbackChain[] = 'en';
2188 $fallbackChain = array_reverse( $fallbackChain );
2189 foreach ( $fallbackChain as $code ) {
2190 if ( isset( $newWords[$code] ) ) {
2191 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2197 * Get special page names, as an associative array
2198 * case folded alias => real name
2200 function getSpecialPageAliases() {
2201 // Cache aliases because it may be slow to load them
2202 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2204 $this->mExtendedSpecialPageAliases
=
2205 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2206 wfRunHooks( 'LanguageGetSpecialPageAliases',
2207 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2210 return $this->mExtendedSpecialPageAliases
;
2214 * Italic is unsuitable for some languages
2216 * @param $text String: the text to be emphasized.
2219 function emphasize( $text ) {
2220 return "<em>$text</em>";
2224 * Normally we output all numbers in plain en_US style, that is
2225 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2226 * point twohundredthirtyfive. However this is not sutable for all
2227 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2228 * Icelandic just want to use commas instead of dots, and dots instead
2229 * of commas like "293.291,235".
2231 * An example of this function being called:
2233 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2236 * See LanguageGu.php for the Gujarati implementation and
2237 * $separatorTransformTable on MessageIs.php for
2238 * the , => . and . => , implementation.
2240 * @todo check if it's viable to use localeconv() for the decimal
2242 * @param $number Mixed: the string to be formatted, should be an integer
2243 * or a floating point number.
2244 * @param $nocommafy Bool: set to true for special numbers like dates
2247 function formatNum( $number, $nocommafy = false ) {
2248 global $wgTranslateNumerals;
2249 if ( !$nocommafy ) {
2250 $number = $this->commafy( $number );
2251 $s = $this->separatorTransformTable();
2253 $number = strtr( $number, $s );
2257 if ( $wgTranslateNumerals ) {
2258 $s = $this->digitTransformTable();
2260 $number = strtr( $number, $s );
2267 function parseFormattedNumber( $number ) {
2268 $s = $this->digitTransformTable();
2270 $number = strtr( $number, array_flip( $s ) );
2273 $s = $this->separatorTransformTable();
2275 $number = strtr( $number, array_flip( $s ) );
2278 $number = strtr( $number, array( ',' => '' ) );
2283 * Adds commas to a given number
2288 function commafy( $_ ) {
2289 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2292 function digitTransformTable() {
2293 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2296 function separatorTransformTable() {
2297 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2301 * Take a list of strings and build a locale-friendly comma-separated
2302 * list, using the local comma-separator message.
2303 * The last two strings are chained with an "and".
2308 function listToText( $l ) {
2310 $m = count( $l ) - 1;
2312 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2314 for ( $i = $m; $i >= 0; $i-- ) {
2317 } else if ( $i == $m - 1 ) {
2318 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2320 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2328 * Take a list of strings and build a locale-friendly comma-separated
2329 * list, using the local comma-separator message.
2330 * @param $list array of strings to put in a comma list
2333 function commaList( $list ) {
2338 array( 'parsemag', 'escapenoentities', 'language' => $this )
2344 * Take a list of strings and build a locale-friendly semicolon-separated
2345 * list, using the local semicolon-separator message.
2346 * @param $list array of strings to put in a semicolon list
2349 function semicolonList( $list ) {
2353 'semicolon-separator',
2354 array( 'parsemag', 'escapenoentities', 'language' => $this )
2360 * Same as commaList, but separate it with the pipe instead.
2361 * @param $list array of strings to put in a pipe list
2364 function pipeList( $list ) {
2369 array( 'escapenoentities', 'language' => $this )
2375 * Truncate a string to a specified length in bytes, appending an optional
2376 * string (e.g. for ellipses)
2378 * The database offers limited byte lengths for some columns in the database;
2379 * multi-byte character sets mean we need to ensure that only whole characters
2380 * are included, otherwise broken characters can be passed to the user
2382 * If $length is negative, the string will be truncated from the beginning
2384 * @param $string String to truncate
2385 * @param $length Int: maximum length (excluding ellipses)
2386 * @param $ellipsis String to append to the truncated text
2389 function truncate( $string, $length, $ellipsis = '...' ) {
2390 # Use the localized ellipsis character
2391 if ( $ellipsis == '...' ) {
2392 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2394 # Check if there is no need to truncate
2395 if ( $length == 0 ) {
2397 } elseif ( strlen( $string ) <= abs( $length ) ) {
2400 $stringOriginal = $string;
2401 if ( $length > 0 ) {
2402 $string = substr( $string, 0, $length ); // xyz...
2403 $string = $this->removeBadCharLast( $string );
2404 $string = $string . $ellipsis;
2406 $string = substr( $string, $length ); // ...xyz
2407 $string = $this->removeBadCharFirst( $string );
2408 $string = $ellipsis . $string;
2410 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2411 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2414 return $stringOriginal;
2419 * Remove bytes that represent an incomplete Unicode character
2420 * at the end of string (e.g. bytes of the char are missing)
2422 * @param $string String
2425 protected function removeBadCharLast( $string ) {
2426 $char = ord( $string[strlen( $string ) - 1] );
2428 if ( $char >= 0xc0 ) {
2429 # We got the first byte only of a multibyte char; remove it.
2430 $string = substr( $string, 0, -1 );
2431 } elseif ( $char >= 0x80 &&
2432 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2433 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2435 # We chopped in the middle of a character; remove it
2442 * Remove bytes that represent an incomplete Unicode character
2443 * at the start of string (e.g. bytes of the char are missing)
2445 * @param $string String
2448 protected function removeBadCharFirst( $string ) {
2449 $char = ord( $string[0] );
2450 if ( $char >= 0x80 && $char < 0xc0 ) {
2451 # We chopped in the middle of a character; remove the whole thing
2452 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2458 * Truncate a string of valid HTML to a specified length in bytes,
2459 * appending an optional string (e.g. for ellipses), and return valid HTML
2461 * This is only intended for styled/linked text, such as HTML with
2462 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2464 * Note: tries to fix broken HTML with MWTidy
2466 * @param string $text HTML string to truncate
2467 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2468 * @param string $ellipsis String to append to the truncated text
2471 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2472 # Use the localized ellipsis character
2473 if ( $ellipsis == '...' ) {
2474 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2476 # Check if there is no need to truncate
2477 if ( $length <= 0 ) {
2478 return $ellipsis; // no text shown, nothing to format
2479 } elseif ( strlen( $text ) <= $length ) {
2480 return $text; // string short enough even *with* HTML
2482 $text = MWTidy
::tidy( $text ); // fix tags
2483 $displayLen = 0; // innerHTML legth so far
2484 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2485 $tagType = 0; // 0-open, 1-close
2486 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2487 $entityState = 0; // 0-not entity, 1-entity
2489 $openTags = array(); // open tag stack
2490 $textLen = strlen( $text );
2491 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2493 $lastCh = $pos ?
$text[$pos - 1] : '';
2494 $ret .= $ch; // add to result string
2496 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2497 $entityState = 0; // for bad HTML
2498 $bracketState = 1; // tag started (checking for backslash)
2499 } elseif ( $ch == '>' ) {
2500 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2501 $entityState = 0; // for bad HTML
2502 $bracketState = 0; // out of brackets
2503 } elseif ( $bracketState == 1 ) {
2505 $tagType = 1; // close tag (e.g. "</span>")
2507 $tagType = 0; // open tag (e.g. "<span>")
2510 $bracketState = 2; // building tag name
2511 } elseif ( $bracketState == 2 ) {
2515 // Name found (e.g. "<a href=..."), add on tag attributes...
2516 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2518 } elseif ( $bracketState == 0 ) {
2519 if ( $entityState ) {
2522 $displayLen++
; // entity is one displayed char
2526 $entityState = 1; // entity found, (e.g. " ")
2528 $displayLen++
; // this char is displayed
2529 // Add on the other display text after this...
2530 $skipped = $this->truncate_skip(
2531 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2532 $displayLen +
= $skipped;
2537 # Consider truncation once the display length has reached the maximim.
2538 # Double-check that we're not in the middle of a bracket/entity...
2539 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2540 if ( !$testingEllipsis ) {
2541 $testingEllipsis = true;
2542 # Save where we are; we will truncate here unless
2543 # the ellipsis actually makes the string longer.
2544 $pOpenTags = $openTags; // save state
2545 $pRet = $ret; // save state
2546 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2547 # Ellipsis won't make string longer/equal, 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
2555 if ( $displayLen == 0 ) {
2556 return ''; // no text shown, nothing to format
2558 // Close the last tag if left unclosed by bad HTML
2559 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2560 while ( count( $openTags ) > 0 ) {
2561 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2566 // truncateHtml() helper function
2567 // like strcspn() but adds the skipped chars to $ret
2568 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2570 if ( $start < strlen( $text ) ) {
2571 $skipCount = strcspn( $text, $search, $start, $len );
2572 $ret .= substr( $text, $start, $skipCount );
2578 * truncateHtml() helper function
2579 * (a) push or pop $tag from $openTags as needed
2580 * (b) clear $tag value
2581 * @param String &$tag Current HTML tag name we are looking at
2582 * @param int $tagType (0-open tag, 1-close tag)
2583 * @param char $lastCh Character before the '>' that ended this tag
2584 * @param array &$openTags Open tag stack (not accounting for $tag)
2586 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2587 $tag = ltrim( $tag );
2589 if ( $tagType == 0 && $lastCh != '/' ) {
2590 $openTags[] = $tag; // tag opened (didn't close itself)
2591 } else if ( $tagType == 1 ) {
2592 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2593 array_pop( $openTags ); // tag closed
2601 * Grammatical transformations, needed for inflected languages
2602 * Invoked by putting {{grammar:case|word}} in a message
2604 * @param $word string
2605 * @param $case string
2608 function convertGrammar( $word, $case ) {
2609 global $wgGrammarForms;
2610 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2611 return $wgGrammarForms[$this->getCode()][$case][$word];
2617 * Provides an alternative text depending on specified gender.
2618 * Usage {{gender:username|masculine|feminine|neutral}}.
2619 * username is optional, in which case the gender of current user is used,
2620 * but only in (some) interface messages; otherwise default gender is used.
2621 * If second or third parameter are not specified, masculine is used.
2622 * These details may be overriden per language.
2624 function gender( $gender, $forms ) {
2625 if ( !count( $forms ) ) {
2628 $forms = $this->preConvertPlural( $forms, 2 );
2629 if ( $gender === 'male' ) {
2632 if ( $gender === 'female' ) {
2635 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2639 * Plural form transformations, needed for some languages.
2640 * For example, there are 3 form of plural in Russian and Polish,
2641 * depending on "count mod 10". See [[w:Plural]]
2642 * For English it is pretty simple.
2644 * Invoked by putting {{plural:count|wordform1|wordform2}}
2645 * or {{plural:count|wordform1|wordform2|wordform3}}
2647 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2649 * @param $count Integer: non-localized number
2650 * @param $forms Array: different plural forms
2651 * @return string Correct form of plural for $count in this language
2653 function convertPlural( $count, $forms ) {
2654 if ( !count( $forms ) ) {
2657 $forms = $this->preConvertPlural( $forms, 2 );
2659 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2663 * Checks that convertPlural was given an array and pads it to requested
2664 * amound of forms by copying the last one.
2666 * @param $count Integer: How many forms should there be at least
2667 * @param $forms Array of forms given to convertPlural
2668 * @return array Padded array of forms or an exception if not an array
2670 protected function preConvertPlural( /* Array */ $forms, $count ) {
2671 while ( count( $forms ) < $count ) {
2672 $forms[] = $forms[count( $forms ) - 1];
2678 * For translating of expiry times
2679 * @param $str String: the validated block time in English
2680 * @return Somehow translated block time
2681 * @see LanguageFi.php for example implementation
2683 function translateBlockExpiry( $str ) {
2684 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2686 if ( $scBlockExpiryOptions == '-' ) {
2690 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2691 if ( strpos( $option, ':' ) === false ) {
2694 list( $show, $value ) = explode( ':', $option );
2695 if ( strcmp( $str, $value ) == 0 ) {
2696 return htmlspecialchars( trim( $show ) );
2704 * languages like Chinese need to be segmented in order for the diff
2707 * @param $text String
2710 function segmentForDiff( $text ) {
2715 * and unsegment to show the result
2717 * @param $text String
2720 function unsegmentForDiff( $text ) {
2724 # convert text to all supported variants
2725 function autoConvertToAllVariants( $text ) {
2726 return $this->mConverter
->autoConvertToAllVariants( $text );
2729 # convert text to different variants of a language.
2730 function convert( $text ) {
2731 return $this->mConverter
->convert( $text );
2734 # Convert a Title object to a string in the preferred variant
2735 function convertTitle( $title ) {
2736 return $this->mConverter
->convertTitle( $title );
2739 # Check if this is a language with variants
2740 function hasVariants() {
2741 return sizeof( $this->getVariants() ) > 1;
2744 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2745 function armourMath( $text ) {
2746 return $this->mConverter
->armourMath( $text );
2750 * Perform output conversion on a string, and encode for safe HTML output.
2751 * @param $text String text to be converted
2752 * @param $isTitle Bool whether this conversion is for the article title
2754 * @todo this should get integrated somewhere sane
2756 function convertHtml( $text, $isTitle = false ) {
2757 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2760 function convertCategoryKey( $key ) {
2761 return $this->mConverter
->convertCategoryKey( $key );
2765 * Get the list of variants supported by this language
2766 * see sample implementation in LanguageZh.php
2768 * @return array an array of language codes
2770 function getVariants() {
2771 return $this->mConverter
->getVariants();
2774 function getPreferredVariant() {
2775 return $this->mConverter
->getPreferredVariant();
2778 function getDefaultVariant() {
2779 return $this->mConverter
->getDefaultVariant();
2782 function getURLVariant() {
2783 return $this->mConverter
->getURLVariant();
2787 * If a language supports multiple variants, it is
2788 * possible that non-existing link in one variant
2789 * actually exists in another variant. this function
2790 * tries to find it. See e.g. LanguageZh.php
2792 * @param $link String: the name of the link
2793 * @param $nt Mixed: the title object of the link
2794 * @param $ignoreOtherCond Boolean: to disable other conditions when
2795 * we need to transclude a template or update a category's link
2796 * @return null the input parameters may be modified upon return
2798 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2799 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2803 * If a language supports multiple variants, converts text
2804 * into an array of all possible variants of the text:
2805 * 'variant' => text in that variant
2807 * @deprecated Use autoConvertToAllVariants()
2809 function convertLinkToAllVariants( $text ) {
2810 return $this->mConverter
->convertLinkToAllVariants( $text );
2814 * returns language specific options used by User::getPageRenderHash()
2815 * for example, the preferred language variant
2819 function getExtraHashOptions() {
2820 return $this->mConverter
->getExtraHashOptions();
2824 * For languages that support multiple variants, the title of an
2825 * article may be displayed differently in different variants. this
2826 * function returns the apporiate title defined in the body of the article.
2830 function getParsedTitle() {
2831 return $this->mConverter
->getParsedTitle();
2835 * Enclose a string with the "no conversion" tag. This is used by
2836 * various functions in the Parser
2838 * @param $text String: text to be tagged for no conversion
2840 * @return string the tagged text
2842 function markNoConversion( $text, $noParse = false ) {
2843 return $this->mConverter
->markNoConversion( $text, $noParse );
2847 * A regular expression to match legal word-trailing characters
2848 * which should be merged onto a link of the form [[foo]]bar.
2852 function linkTrail() {
2853 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2856 function getLangObj() {
2861 * Get the RFC 3066 code for this language object
2863 function getCode() {
2864 return $this->mCode
;
2867 function setCode( $code ) {
2868 $this->mCode
= $code;
2872 * Get the name of a file for a certain language code
2873 * @param $prefix string Prepend this to the filename
2874 * @param $code string Language code
2875 * @param $suffix string Append this to the filename
2876 * @return string $prefix . $mangledCode . $suffix
2878 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2879 // Protect against path traversal
2880 if ( !Language
::isValidCode( $code )
2881 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2883 throw new MWException( "Invalid language code \"$code\"" );
2886 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2890 * Get the language code from a file name. Inverse of getFileName()
2891 * @param $filename string $prefix . $languageCode . $suffix
2892 * @param $prefix string Prefix before the language code
2893 * @param $suffix string Suffix after the language code
2894 * @return Language code, or false if $prefix or $suffix isn't found
2896 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2898 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2899 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2900 if ( !count( $m ) ) {
2903 return str_replace( '_', '-', strtolower( $m[1] ) );
2906 static function getMessagesFileName( $code ) {
2908 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2911 static function getClassFileName( $code ) {
2913 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2917 * Get the fallback for a given language
2919 static function getFallbackFor( $code ) {
2920 if ( $code === 'en' ) {
2924 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2929 * Get all messages for a given language
2930 * WARNING: this may take a long time
2932 static function getMessagesFor( $code ) {
2933 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2937 * Get a message for a given language
2939 static function getMessageFor( $key, $code ) {
2940 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2943 function fixVariableInNamespace( $talk ) {
2944 if ( strpos( $talk, '$1' ) === false ) {
2948 global $wgMetaNamespace;
2949 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2951 # Allow grammar transformations
2952 # Allowing full message-style parsing would make simple requests
2953 # such as action=raw much more expensive than they need to be.
2954 # This will hopefully cover most cases.
2955 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2956 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2957 return str_replace( ' ', '_', $talk );
2960 function replaceGrammarInNamespace( $m ) {
2961 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2964 static function getCaseMaps() {
2965 static $wikiUpperChars, $wikiLowerChars;
2966 if ( isset( $wikiUpperChars ) ) {
2967 return array( $wikiUpperChars, $wikiLowerChars );
2970 wfProfileIn( __METHOD__
);
2971 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2972 if ( $arr === false ) {
2973 throw new MWException(
2974 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2976 $wikiUpperChars = $arr['wikiUpperChars'];
2977 $wikiLowerChars = $arr['wikiLowerChars'];
2978 wfProfileOut( __METHOD__
);
2979 return array( $wikiUpperChars, $wikiLowerChars );
2982 function formatTimePeriod( $seconds ) {
2983 if ( round( $seconds * 10 ) < 100 ) {
2984 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2985 } elseif ( round( $seconds ) < 60 ) {
2986 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2987 } elseif ( round( $seconds ) < 3600 ) {
2988 $minutes = floor( $seconds / 60 );
2989 $secondsPart = round( fmod( $seconds, 60 ) );
2990 if ( $secondsPart == 60 ) {
2994 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2995 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2997 $hours = floor( $seconds / 3600 );
2998 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2999 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3000 if ( $secondsPart == 60 ) {
3004 if ( $minutes == 60 ) {
3008 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3009 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3010 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3014 function formatBitrate( $bps ) {
3015 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3017 return $this->formatNum( $bps ) . $units[0];
3019 $unitIndex = floor( log10( $bps ) / 3 );
3020 $mantissa = $bps / pow( 1000, $unitIndex );
3021 if ( $mantissa < 10 ) {
3022 $mantissa = round( $mantissa, 1 );
3024 $mantissa = round( $mantissa );
3026 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3030 * Format a size in bytes for output, using an appropriate
3031 * unit (B, KB, MB or GB) according to the magnitude in question
3033 * @param $size Size to format
3034 * @return string Plain text (not HTML)
3036 function formatSize( $size ) {
3037 // For small sizes no decimal places necessary
3039 if ( $size > 1024 ) {
3040 $size = $size / 1024;
3041 if ( $size > 1024 ) {
3042 $size = $size / 1024;
3043 // For MB and bigger two decimal places are smarter
3045 if ( $size > 1024 ) {
3046 $size = $size / 1024;
3047 $msg = 'size-gigabytes';
3049 $msg = 'size-megabytes';
3052 $msg = 'size-kilobytes';
3055 $msg = 'size-bytes';
3057 $size = round( $size, $round );
3058 $text = $this->getMessageFromDB( $msg );
3059 return str_replace( '$1', $this->formatNum( $size ), $text );
3063 * Get the conversion rule title, if any.
3065 function getConvRuleTitle() {
3066 return $this->mConverter
->getConvRuleTitle();