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 ( $code == 'en' ) {
168 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
169 // Preload base classes to work around APC/PHP5 bug
170 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
171 include_once( "$IP/languages/classes/$class.deps.php" );
173 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
174 include_once( "$IP/languages/classes/$class.php" );
178 if ( $recursionLevel > 5 ) {
179 throw new MWException( "Language fallback loop detected when creating class $class\n" );
182 if ( !class_exists( $class ) ) {
183 $fallback = Language
::getFallbackFor( $code );
185 $lang = Language
::newFromCode( $fallback );
187 $lang->setCode( $code );
195 * Returns true if a language code string is of a valid form, whether or
198 public static function isValidCode( $code ) {
199 return (bool)preg_match( '/^[a-z-]+$/', $code );
203 * Get the LocalisationCache instance
205 public static function getLocalisationCache() {
206 if ( is_null( self
::$dataCache ) ) {
207 global $wgLocalisationCacheConf;
208 $class = $wgLocalisationCacheConf['class'];
209 self
::$dataCache = new $class( $wgLocalisationCacheConf );
211 return self
::$dataCache;
214 function __construct() {
215 $this->mConverter
= new FakeConverter( $this );
216 // Set the code to the name of the descendant
217 if ( get_class( $this ) == 'Language' ) {
220 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
222 self
::getLocalisationCache();
226 * Reduce memory usage
228 function __destruct() {
229 foreach ( $this as $name => $value ) {
230 unset( $this->$name );
235 * Hook which will be called if this is the content language.
236 * Descendants can use this to register hook functions or modify globals
238 function initContLang() { }
241 * @deprecated Use User::getDefaultOptions()
244 function getDefaultUserOptions() {
245 wfDeprecated( __METHOD__
);
246 return User
::getDefaultOptions();
249 function getFallbackLanguageCode() {
250 if ( $this->mCode
=== 'en' ) {
253 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
258 * Exports $wgBookstoreListEn
261 function getBookstoreList() {
262 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
268 function getNamespaces() {
269 if ( is_null( $this->namespaceNames
) ) {
270 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
272 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
273 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
275 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
277 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
278 if ( $wgMetaNamespaceTalk ) {
279 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
281 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
282 $this->namespaceNames
[NS_PROJECT_TALK
] =
283 $this->fixVariableInNamespace( $talk );
286 # Sometimes a language will be localised but not actually exist on this wiki.
287 foreach( $this->namespaceNames
as $key => $text ) {
288 if ( !isset( $validNamespaces[$key] ) ) {
289 unset( $this->namespaceNames
[$key] );
293 # The above mixing may leave namespaces out of canonical order.
294 # Re-order by namespace ID number...
295 ksort( $this->namespaceNames
);
297 return $this->namespaceNames
;
301 * A convenience function that returns the same thing as
302 * getNamespaces() except with the array values changed to ' '
303 * where it found '_', useful for producing output to be displayed
304 * e.g. in <select> forms.
308 function getFormattedNamespaces() {
309 $ns = $this->getNamespaces();
310 foreach ( $ns as $k => $v ) {
311 $ns[$k] = strtr( $v, '_', ' ' );
317 * Get a namespace value by key
319 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
320 * echo $mw_ns; // prints 'MediaWiki'
323 * @param $index Int: the array key of the namespace to return
324 * @return mixed, string if the namespace value exists, otherwise false
326 function getNsText( $index ) {
327 $ns = $this->getNamespaces();
328 return isset( $ns[$index] ) ?
$ns[$index] : false;
332 * A convenience function that returns the same thing as
333 * getNsText() except with '_' changed to ' ', useful for
338 function getFormattedNsText( $index ) {
339 $ns = $this->getNsText( $index );
340 return strtr( $ns, '_', ' ' );
344 * Get a namespace key by value, case insensitive.
345 * Only matches namespace names for the current language, not the
346 * canonical ones defined in Namespace.php.
348 * @param $text String
349 * @return mixed An integer if $text is a valid value otherwise false
351 function getLocalNsIndex( $text ) {
352 $lctext = $this->lc( $text );
353 $ids = $this->getNamespaceIds();
354 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
357 function getNamespaceAliases() {
358 if ( is_null( $this->namespaceAliases
) ) {
359 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
363 foreach ( $aliases as $name => $index ) {
364 if ( $index === NS_PROJECT_TALK
) {
365 unset( $aliases[$name] );
366 $name = $this->fixVariableInNamespace( $name );
367 $aliases[$name] = $index;
371 $this->namespaceAliases
= $aliases;
373 return $this->namespaceAliases
;
376 function getNamespaceIds() {
377 if ( is_null( $this->mNamespaceIds
) ) {
378 global $wgNamespaceAliases;
379 # Put namespace names and aliases into a hashtable.
380 # If this is too slow, then we should arrange it so that it is done
381 # before caching. The catch is that at pre-cache time, the above
382 # class-specific fixup hasn't been done.
383 $this->mNamespaceIds
= array();
384 foreach ( $this->getNamespaces() as $index => $name ) {
385 $this->mNamespaceIds
[$this->lc( $name )] = $index;
387 foreach ( $this->getNamespaceAliases() as $name => $index ) {
388 $this->mNamespaceIds
[$this->lc( $name )] = $index;
390 if ( $wgNamespaceAliases ) {
391 foreach ( $wgNamespaceAliases as $name => $index ) {
392 $this->mNamespaceIds
[$this->lc( $name )] = $index;
396 return $this->mNamespaceIds
;
401 * Get a namespace key by value, case insensitive. Canonical namespace
402 * names override custom ones defined for the current language.
404 * @param $text String
405 * @return mixed An integer if $text is a valid value otherwise false
407 function getNsIndex( $text ) {
408 $lctext = $this->lc( $text );
409 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
412 $ids = $this->getNamespaceIds();
413 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
417 * short names for language variants used for language conversion links.
419 * @param $code String
422 function getVariantname( $code ) {
423 return $this->getMessageFromDB( "variantname-$code" );
426 function specialPage( $name ) {
427 $aliases = $this->getSpecialPageAliases();
428 if ( isset( $aliases[$name][0] ) ) {
429 $name = $aliases[$name][0];
431 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
434 function getQuickbarSettings() {
436 $this->getMessage( 'qbsettings-none' ),
437 $this->getMessage( 'qbsettings-fixedleft' ),
438 $this->getMessage( 'qbsettings-fixedright' ),
439 $this->getMessage( 'qbsettings-floatingleft' ),
440 $this->getMessage( 'qbsettings-floatingright' )
444 function getMathNames() {
445 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
448 function getDatePreferences() {
449 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
452 function getDateFormats() {
453 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
456 function getDefaultDateFormat() {
457 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
458 if ( $df === 'dmy or mdy' ) {
459 global $wgAmericanDates;
460 return $wgAmericanDates ?
'mdy' : 'dmy';
466 function getDatePreferenceMigrationMap() {
467 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
470 function getImageFile( $image ) {
471 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
474 function getDefaultUserOptionOverrides() {
475 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
478 function getExtraUserToggles() {
479 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
482 function getUserToggle( $tog ) {
483 return $this->getMessageFromDB( "tog-$tog" );
487 * Get language names, indexed by code.
488 * If $customisedOnly is true, only returns codes with a messages file
490 public static function getLanguageNames( $customisedOnly = false ) {
491 global $wgLanguageNames, $wgExtraLanguageNames;
492 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
493 if ( !$customisedOnly ) {
499 $dir = opendir( "$IP/languages/messages" );
500 while ( false !== ( $file = readdir( $dir ) ) ) {
501 $code = self
::getCodeFromFileName( $file, 'Messages' );
502 if ( $code && isset( $allNames[$code] ) ) {
503 $names[$code] = $allNames[$code];
511 * Get translated language names. This is done on best effort and
512 * by default this is exactly the same as Language::getLanguageNames.
513 * The CLDR extension provides translated names.
514 * @param $code String Language code.
515 * @return Array language code => language name
518 public static function getTranslatedLanguageNames( $code ) {
520 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
522 foreach ( self
::getLanguageNames() as $code => $name ) {
523 if ( !isset( $names[$code] ) ) $names[$code] = $name;
530 * Get a message from the MediaWiki namespace.
532 * @param $msg String: message name
535 function getMessageFromDB( $msg ) {
536 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
539 function getLanguageName( $code ) {
540 $names = self
::getLanguageNames();
541 if ( !array_key_exists( $code, $names ) ) {
544 return $names[$code];
547 function getMonthName( $key ) {
548 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
551 function getMonthNameGen( $key ) {
552 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
555 function getMonthAbbreviation( $key ) {
556 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
559 function getWeekdayName( $key ) {
560 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
563 function getWeekdayAbbreviation( $key ) {
564 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
567 function getIranianCalendarMonthName( $key ) {
568 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
571 function getHebrewCalendarMonthName( $key ) {
572 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
575 function getHebrewCalendarMonthNameGen( $key ) {
576 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
579 function getHijriCalendarMonthName( $key ) {
580 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
584 * Used by date() and time() to adjust the time output.
586 * @param $ts Int the time in date('YmdHis') format
587 * @param $tz Mixed: adjust the time by this amount (default false, mean we
588 * get user timecorrection setting)
591 function userAdjust( $ts, $tz = false ) {
592 global $wgUser, $wgLocalTZoffset;
594 if ( $tz === false ) {
595 $tz = $wgUser->getOption( 'timecorrection' );
598 $data = explode( '|', $tz, 3 );
600 if ( $data[0] == 'ZoneInfo' ) {
601 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
602 $date = date_create( $ts, timezone_open( 'UTC' ) );
603 date_timezone_set( $date, timezone_open( $data[2] ) );
604 $date = date_format( $date, 'YmdHis' );
607 # Unrecognized timezone, default to 'Offset' with the stored offset.
612 if ( $data[0] == 'System' ||
$tz == '' ) {
613 # Global offset in minutes.
614 if ( isset( $wgLocalTZoffset ) ) {
615 $minDiff = $wgLocalTZoffset;
617 } else if ( $data[0] == 'Offset' ) {
618 $minDiff = intval( $data[1] );
620 $data = explode( ':', $tz );
621 if ( count( $data ) == 2 ) {
622 $data[0] = intval( $data[0] );
623 $data[1] = intval( $data[1] );
624 $minDiff = abs( $data[0] ) * 60 +
$data[1];
625 if ( $data[0] < 0 ) {
626 $minDiff = -$minDiff;
629 $minDiff = intval( $data[0] ) * 60;
633 # No difference ? Return time unchanged
634 if ( 0 == $minDiff ) {
638 wfSuppressWarnings(); // E_STRICT system time bitching
639 # Generate an adjusted date; take advantage of the fact that mktime
640 # will normalize out-of-range values so we don't have to split $minDiff
641 # into hours and minutes.
643 (int)substr( $ts, 8, 2 ) ), # Hours
644 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
645 (int)substr( $ts, 12, 2 ), # Seconds
646 (int)substr( $ts, 4, 2 ), # Month
647 (int)substr( $ts, 6, 2 ), # Day
648 (int)substr( $ts, 0, 4 ) ); # Year
650 $date = date( 'YmdHis', $t );
657 * This is a workalike of PHP's date() function, but with better
658 * internationalisation, a reduced set of format characters, and a better
661 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
662 * PHP manual for definitions. There are a number of extensions, which
665 * xn Do not translate digits of the next numeric format character
666 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
667 * xr Use roman numerals for the next numeric format character
668 * xh Use hebrew numerals for the next numeric format character
670 * xg Genitive month name
672 * xij j (day number) in Iranian calendar
673 * xiF F (month name) in Iranian calendar
674 * xin n (month number) in Iranian calendar
675 * xiY Y (full year) in Iranian calendar
677 * xjj j (day number) in Hebrew calendar
678 * xjF F (month name) in Hebrew calendar
679 * xjt t (days in month) in Hebrew calendar
680 * xjx xg (genitive month name) in Hebrew calendar
681 * xjn n (month number) in Hebrew calendar
682 * xjY Y (full year) in Hebrew calendar
684 * xmj j (day number) in Hijri calendar
685 * xmF F (month name) in Hijri calendar
686 * xmn n (month number) in Hijri calendar
687 * xmY Y (full year) in Hijri calendar
689 * xkY Y (full year) in Thai solar calendar. Months and days are
690 * identical to the Gregorian calendar
691 * xoY Y (full year) in Minguo calendar or Juche year.
692 * Months and days are identical to the
694 * xtY Y (full year) in Japanese nengo. Months and days are
695 * identical to the Gregorian calendar
697 * Characters enclosed in double quotes will be considered literal (with
698 * the quotes themselves removed). Unmatched quotes will be considered
699 * literal quotes. Example:
701 * "The month is" F => The month is January
704 * Backslash escaping is also supported.
706 * Input timestamp is assumed to be pre-normalized to the desired local
709 * @param $format String
710 * @param $ts String: 14-character timestamp
713 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
715 function sprintfDate( $format, $ts ) {
728 for ( $p = 0; $p < strlen( $format ); $p++
) {
731 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
732 $code .= $format[++
$p];
735 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
736 $code .= $format[++
$p];
747 $rawToggle = !$rawToggle;
756 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
759 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
760 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
763 $num = substr( $ts, 6, 2 );
766 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
767 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
770 $num = intval( substr( $ts, 6, 2 ) );
774 $iranian = self
::tsToIranian( $ts );
780 $hijri = self
::tsToHijri( $ts );
786 $hebrew = self
::tsToHebrew( $ts );
792 $unix = wfTimestamp( TS_UNIX
, $ts );
794 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
798 $unix = wfTimestamp( TS_UNIX
, $ts );
800 $w = gmdate( 'w', $unix );
805 $unix = wfTimestamp( TS_UNIX
, $ts );
807 $num = gmdate( 'w', $unix );
811 $unix = wfTimestamp( TS_UNIX
, $ts );
813 $num = gmdate( 'z', $unix );
817 $unix = wfTimestamp( TS_UNIX
, $ts );
819 $num = gmdate( 'W', $unix );
822 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
826 $iranian = self
::tsToIranian( $ts );
828 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
832 $hijri = self
::tsToHijri( $ts );
834 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
838 $hebrew = self
::tsToHebrew( $ts );
840 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
843 $num = substr( $ts, 4, 2 );
846 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
849 $num = intval( substr( $ts, 4, 2 ) );
853 $iranian = self
::tsToIranian( $ts );
859 $hijri = self
::tsToHijri ( $ts );
865 $hebrew = self
::tsToHebrew( $ts );
871 $unix = wfTimestamp( TS_UNIX
, $ts );
873 $num = gmdate( 't', $unix );
877 $hebrew = self
::tsToHebrew( $ts );
883 $unix = wfTimestamp( TS_UNIX
, $ts );
885 $num = gmdate( 'L', $unix );
889 $unix = wfTimestamp( TS_UNIX
, $ts );
891 $num = date( 'o', $unix );
894 $num = substr( $ts, 0, 4 );
898 $iranian = self
::tsToIranian( $ts );
904 $hijri = self
::tsToHijri( $ts );
910 $hebrew = self
::tsToHebrew( $ts );
916 $thai = self
::tsToYear( $ts, 'thai' );
922 $minguo = self
::tsToYear( $ts, 'minguo' );
928 $tenno = self
::tsToYear( $ts, 'tenno' );
933 $num = substr( $ts, 2, 2 );
936 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
939 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
942 $h = substr( $ts, 8, 2 );
943 $num = $h %
12 ?
$h %
12 : 12;
946 $num = intval( substr( $ts, 8, 2 ) );
949 $h = substr( $ts, 8, 2 );
950 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
953 $num = substr( $ts, 8, 2 );
956 $num = substr( $ts, 10, 2 );
959 $num = substr( $ts, 12, 2 );
963 $unix = wfTimestamp( TS_UNIX
, $ts );
965 $s .= gmdate( 'c', $unix );
969 $unix = wfTimestamp( TS_UNIX
, $ts );
971 $s .= gmdate( 'r', $unix );
975 $unix = wfTimestamp( TS_UNIX
, $ts );
981 if ( $p < strlen( $format ) - 1 ) {
989 if ( $p < strlen( $format ) - 1 ) {
990 $endQuote = strpos( $format, '"', $p +
1 );
991 if ( $endQuote === false ) {
992 # No terminating quote, assume literal "
995 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
999 # Quote at end of string, assume literal "
1006 if ( $num !== false ) {
1007 if ( $rawToggle ||
$raw ) {
1010 } elseif ( $roman ) {
1011 $s .= self
::romanNumeral( $num );
1013 } elseif ( $hebrewNum ) {
1014 $s .= self
::hebrewNumeral( $num );
1017 $s .= $this->formatNum( $num, true );
1024 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1025 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1027 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1028 * Gregorian dates to Iranian dates. Originally written in C, it
1029 * is released under the terms of GNU Lesser General Public
1030 * License. Conversion to PHP was performed by Niklas Laxström.
1032 * Link: http://www.farsiweb.info/jalali/jalali.c
1034 private static function tsToIranian( $ts ) {
1035 $gy = substr( $ts, 0, 4 ) -1600;
1036 $gm = substr( $ts, 4, 2 ) -1;
1037 $gd = substr( $ts, 6, 2 ) -1;
1039 # Days passed from the beginning (including leap years)
1041 +
floor( ( $gy +
3 ) / 4 )
1042 - floor( ( $gy +
99 ) / 100 )
1043 +
floor( ( $gy +
399 ) / 400 );
1046 // Add days of the past months of this year
1047 for ( $i = 0; $i < $gm; $i++
) {
1048 $gDayNo +
= self
::$GREG_DAYS[$i];
1052 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1056 // Days passed in current month
1059 $jDayNo = $gDayNo - 79;
1061 $jNp = floor( $jDayNo / 12053 );
1064 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1067 if ( $jDayNo >= 366 ) {
1068 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1069 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1072 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1073 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1079 return array( $jy, $jm, $jd );
1083 * Converting Gregorian dates to Hijri dates.
1085 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1087 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1089 private static function tsToHijri( $ts ) {
1090 $year = substr( $ts, 0, 4 );
1091 $month = substr( $ts, 4, 2 );
1092 $day = substr( $ts, 6, 2 );
1100 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1101 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1104 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1105 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1106 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1109 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1110 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1113 $zl = $zjd -1948440 +
10632;
1114 $zn = (int)( ( $zl - 1 ) / 10631 );
1115 $zl = $zl - 10631 * $zn +
354;
1116 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1117 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1118 $zm = (int)( ( 24 * $zl ) / 709 );
1119 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1120 $zy = 30 * $zn +
$zj - 30;
1122 return array( $zy, $zm, $zd );
1126 * Converting Gregorian dates to Hebrew dates.
1128 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1129 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1130 * to translate the relevant functions into PHP and release them under
1133 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1134 * and Adar II is 14. In a non-leap year, Adar is 6.
1136 private static function tsToHebrew( $ts ) {
1138 $year = substr( $ts, 0, 4 );
1139 $month = substr( $ts, 4, 2 );
1140 $day = substr( $ts, 6, 2 );
1142 # Calculate Hebrew year
1143 $hebrewYear = $year +
3760;
1145 # Month number when September = 1, August = 12
1147 if ( $month > 12 ) {
1154 # Calculate day of year from 1 September
1156 for ( $i = 1; $i < $month; $i++
) {
1160 # Check if the year is leap
1161 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1164 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1171 # Calculate the start of the Hebrew year
1172 $start = self
::hebrewYearStart( $hebrewYear );
1174 # Calculate next year's start
1175 if ( $dayOfYear <= $start ) {
1176 # Day is before the start of the year - it is the previous year
1178 $nextStart = $start;
1182 # Add days since previous year's 1 September
1184 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1188 # Start of the new (previous) year
1189 $start = self
::hebrewYearStart( $hebrewYear );
1192 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1195 # Calculate Hebrew day of year
1196 $hebrewDayOfYear = $dayOfYear - $start;
1198 # Difference between year's days
1199 $diff = $nextStart - $start;
1200 # Add 12 (or 13 for leap years) days to ignore the difference between
1201 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1202 # difference is only about the year type
1203 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1209 # Check the year pattern, and is leap year
1210 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1211 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1212 # and non-leap years
1213 $yearPattern = $diff %
30;
1214 # Check if leap year
1215 $isLeap = $diff >= 30;
1217 # Calculate day in the month from number of day in the Hebrew year
1218 # Don't check Adar - if the day is not in Adar, we will stop before;
1219 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1220 $hebrewDay = $hebrewDayOfYear;
1223 while ( $hebrewMonth <= 12 ) {
1224 # Calculate days in this month
1225 if ( $isLeap && $hebrewMonth == 6 ) {
1226 # Adar in a leap year
1228 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1230 if ( $hebrewDay <= $days ) {
1234 # Subtract the days of Adar I
1235 $hebrewDay -= $days;
1238 if ( $hebrewDay <= $days ) {
1244 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1245 # Cheshvan in a complete year (otherwise as the rule below)
1247 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1248 # Kislev in an incomplete year (otherwise as the rule below)
1251 # Odd months have 30 days, even have 29
1252 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1254 if ( $hebrewDay <= $days ) {
1255 # In the current month
1258 # Subtract the days of the current month
1259 $hebrewDay -= $days;
1260 # Try in the next month
1265 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1269 * This calculates the Hebrew year start, as days since 1 September.
1270 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1271 * Used for Hebrew date.
1273 private static function hebrewYearStart( $year ) {
1274 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1275 $b = intval( ( $year - 1 ) %
4 );
1276 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1280 $Mar = intval( $m );
1286 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1287 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1289 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1291 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1295 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1300 * Algorithm to convert Gregorian dates to Thai solar dates,
1301 * Minguo dates or Minguo dates.
1303 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1304 * http://en.wikipedia.org/wiki/Minguo_calendar
1305 * http://en.wikipedia.org/wiki/Japanese_era_name
1307 * @param $ts String: 14-character timestamp
1308 * @param $cName String: calender name
1309 * @return Array: converted year, month, day
1311 private static function tsToYear( $ts, $cName ) {
1312 $gy = substr( $ts, 0, 4 );
1313 $gm = substr( $ts, 4, 2 );
1314 $gd = substr( $ts, 6, 2 );
1316 if ( !strcmp( $cName, 'thai' ) ) {
1318 # Add 543 years to the Gregorian calendar
1319 # Months and days are identical
1320 $gy_offset = $gy +
543;
1321 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1323 # Deduct 1911 years from the Gregorian calendar
1324 # Months and days are identical
1325 $gy_offset = $gy - 1911;
1326 } else if ( !strcmp( $cName, 'tenno' ) ) {
1327 # Nengō dates up to Meiji period
1328 # Deduct years from the Gregorian calendar
1329 # depending on the nengo periods
1330 # Months and days are identical
1331 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1333 $gy_gannen = $gy - 1868 +
1;
1334 $gy_offset = $gy_gannen;
1335 if ( $gy_gannen == 1 ) {
1338 $gy_offset = '明治' . $gy_offset;
1340 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1341 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1342 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1343 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1344 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1348 $gy_gannen = $gy - 1912 +
1;
1349 $gy_offset = $gy_gannen;
1350 if ( $gy_gannen == 1 ) {
1353 $gy_offset = '大正' . $gy_offset;
1355 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1356 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1357 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1361 $gy_gannen = $gy - 1926 +
1;
1362 $gy_offset = $gy_gannen;
1363 if ( $gy_gannen == 1 ) {
1366 $gy_offset = '昭和' . $gy_offset;
1369 $gy_gannen = $gy - 1989 +
1;
1370 $gy_offset = $gy_gannen;
1371 if ( $gy_gannen == 1 ) {
1374 $gy_offset = '平成' . $gy_offset;
1380 return array( $gy_offset, $gm, $gd );
1384 * Roman number formatting up to 3000
1386 static function romanNumeral( $num ) {
1387 static $table = array(
1388 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1389 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1390 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1391 array( '', 'M', 'MM', 'MMM' )
1394 $num = intval( $num );
1395 if ( $num > 3000 ||
$num <= 0 ) {
1400 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1401 if ( $num >= $pow10 ) {
1402 $s .= $table[$i][floor( $num / $pow10 )];
1404 $num = $num %
$pow10;
1410 * Hebrew Gematria number formatting up to 9999
1412 static function hebrewNumeral( $num ) {
1413 static $table = array(
1414 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1415 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1416 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1417 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1420 $num = intval( $num );
1421 if ( $num > 9999 ||
$num <= 0 ) {
1426 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1427 if ( $num >= $pow10 ) {
1428 if ( $num == 15 ||
$num == 16 ) {
1429 $s .= $table[0][9] . $table[0][$num - 9];
1432 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1433 if ( $pow10 == 1000 ) {
1438 $num = $num %
$pow10;
1440 if ( strlen( $s ) == 2 ) {
1443 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1444 $str .= substr( $s, strlen( $s ) - 2, 2 );
1446 $start = substr( $str, 0, strlen( $str ) - 2 );
1447 $end = substr( $str, strlen( $str ) - 2 );
1450 $str = $start . 'ך';
1453 $str = $start . 'ם';
1456 $str = $start . 'ן';
1459 $str = $start . 'ף';
1462 $str = $start . 'ץ';
1469 * This is meant to be used by time(), date(), and timeanddate() to get
1470 * the date preference they're supposed to use, it should be used in
1474 * function timeanddate([...], $format = true) {
1475 * $datePreference = $this->dateFormat($format);
1480 * @param $usePrefs Mixed: if true, the user's preference is used
1481 * if false, the site/language default is used
1482 * if int/string, assumed to be a format.
1485 function dateFormat( $usePrefs = true ) {
1488 if ( is_bool( $usePrefs ) ) {
1490 $datePreference = $wgUser->getDatePreference();
1492 $datePreference = (string)User
::getDefaultOption( 'date' );
1495 $datePreference = (string)$usePrefs;
1499 if ( $datePreference == '' ) {
1503 return $datePreference;
1507 * Get a format string for a given type and preference
1508 * @param $type May be date, time or both
1509 * @param $pref The format name as it appears in Messages*.php
1511 function getDateFormatString( $type, $pref ) {
1512 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1513 if ( $pref == 'default' ) {
1514 $pref = $this->getDefaultDateFormat();
1515 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1517 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1518 if ( is_null( $df ) ) {
1519 $pref = $this->getDefaultDateFormat();
1520 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1523 $this->dateFormatStrings
[$type][$pref] = $df;
1525 return $this->dateFormatStrings
[$type][$pref];
1529 * @param $ts Mixed: the time format which needs to be turned into a
1530 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1531 * @param $adj Bool: whether to adjust the time output according to the
1532 * user configured offset ($timecorrection)
1533 * @param $format Mixed: true to use user's date format preference
1534 * @param $timecorrection String: the time offset as returned by
1535 * validateTimeZone() in Special:Preferences
1538 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1539 $ts = wfTimestamp( TS_MW
, $ts );
1541 $ts = $this->userAdjust( $ts, $timecorrection );
1543 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1544 return $this->sprintfDate( $df, $ts );
1548 * @param $ts Mixed: the time format which needs to be turned into a
1549 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1550 * @param $adj Bool: whether to adjust the time output according to the
1551 * user configured offset ($timecorrection)
1552 * @param $format Mixed: true to use user's date format preference
1553 * @param $timecorrection String: the time offset as returned by
1554 * validateTimeZone() in Special:Preferences
1557 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1558 $ts = wfTimestamp( TS_MW
, $ts );
1560 $ts = $this->userAdjust( $ts, $timecorrection );
1562 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1563 return $this->sprintfDate( $df, $ts );
1567 * @param $ts Mixed: the time format which needs to be turned into a
1568 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1569 * @param $adj Bool: whether to adjust the time output according to the
1570 * user configured offset ($timecorrection)
1571 * @param $format Mixed: what format to return, if it's false output the
1572 * default one (default true)
1573 * @param $timecorrection String: the time offset as returned by
1574 * validateTimeZone() in Special:Preferences
1577 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1578 $ts = wfTimestamp( TS_MW
, $ts );
1580 $ts = $this->userAdjust( $ts, $timecorrection );
1582 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1583 return $this->sprintfDate( $df, $ts );
1586 function getMessage( $key ) {
1587 // Don't change getPreferredVariant() to getCode() / mCode, because:
1589 // 1. Some language like Chinese has multiple variant languages. Only
1590 // getPreferredVariant() (in LanguageConverter) could return a
1591 // sub-language which would be more suitable for the user.
1592 // 2. To languages without multiple variants, getPreferredVariant()
1593 // (in FakeConverter) functions exactly same as getCode() / mCode,
1594 // it won't break anything.
1597 return self
::$dataCache->getSubitem( $this->getPreferredVariant(), 'messages', $key );
1600 function getAllMessages() {
1601 return self
::$dataCache->getItem( $this->getPreferredVariant(), 'messages' );
1604 function iconv( $in, $out, $string ) {
1605 # This is a wrapper for iconv in all languages except esperanto,
1606 # which does some nasty x-conversions beforehand
1608 # Even with //IGNORE iconv can whine about illegal characters in
1609 # *input* string. We just ignore those too.
1610 # REF: http://bugs.php.net/bug.php?id=37166
1611 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1612 wfSuppressWarnings();
1613 $text = iconv( $in, $out . '//IGNORE', $string );
1614 wfRestoreWarnings();
1618 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1619 function ucwordbreaksCallbackAscii( $matches ) {
1620 return $this->ucfirst( $matches[1] );
1623 function ucwordbreaksCallbackMB( $matches ) {
1624 return mb_strtoupper( $matches[0] );
1627 function ucCallback( $matches ) {
1628 list( $wikiUpperChars ) = self
::getCaseMaps();
1629 return strtr( $matches[1], $wikiUpperChars );
1632 function lcCallback( $matches ) {
1633 list( , $wikiLowerChars ) = self
::getCaseMaps();
1634 return strtr( $matches[1], $wikiLowerChars );
1637 function ucwordsCallbackMB( $matches ) {
1638 return mb_strtoupper( $matches[0] );
1641 function ucwordsCallbackWiki( $matches ) {
1642 list( $wikiUpperChars ) = self
::getCaseMaps();
1643 return strtr( $matches[0], $wikiUpperChars );
1647 * Make a string's first character uppercase
1649 function ucfirst( $str ) {
1651 if ( $o < 96 ) { // if already uppercase...
1653 } elseif ( $o < 128 ) {
1654 return ucfirst( $str ); // use PHP's ucfirst()
1656 // fall back to more complex logic in case of multibyte strings
1657 return $this->uc( $str, true );
1662 * Convert a string to uppercase
1664 function uc( $str, $first = false ) {
1665 if ( function_exists( 'mb_strtoupper' ) ) {
1667 if ( $this->isMultibyte( $str ) ) {
1668 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1670 return ucfirst( $str );
1673 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1676 if ( $this->isMultibyte( $str ) ) {
1677 $x = $first ?
'^' : '';
1678 return preg_replace_callback(
1679 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1680 array( $this, 'ucCallback' ),
1684 return $first ?
ucfirst( $str ) : strtoupper( $str );
1689 function lcfirst( $str ) {
1692 return strval( $str );
1693 } elseif ( $o >= 128 ) {
1694 return $this->lc( $str, true );
1695 } elseif ( $o > 96 ) {
1698 $str[0] = strtolower( $str[0] );
1703 function lc( $str, $first = false ) {
1704 if ( function_exists( 'mb_strtolower' ) ) {
1706 if ( $this->isMultibyte( $str ) ) {
1707 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1709 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1712 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1715 if ( $this->isMultibyte( $str ) ) {
1716 $x = $first ?
'^' : '';
1717 return preg_replace_callback(
1718 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1719 array( $this, 'lcCallback' ),
1723 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1728 function isMultibyte( $str ) {
1729 return (bool)preg_match( '/[\x80-\xff]/', $str );
1732 function ucwords( $str ) {
1733 if ( $this->isMultibyte( $str ) ) {
1734 $str = $this->lc( $str );
1736 // regexp to find first letter in each word (i.e. after each space)
1737 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1739 // function to use to capitalize a single char
1740 if ( function_exists( 'mb_strtoupper' ) ) {
1741 return preg_replace_callback(
1743 array( $this, 'ucwordsCallbackMB' ),
1747 return preg_replace_callback(
1749 array( $this, 'ucwordsCallbackWiki' ),
1754 return ucwords( strtolower( $str ) );
1758 # capitalize words at word breaks
1759 function ucwordbreaks( $str ) {
1760 if ( $this->isMultibyte( $str ) ) {
1761 $str = $this->lc( $str );
1763 // since \b doesn't work for UTF-8, we explicitely define word break chars
1764 $breaks = "[ \-\(\)\}\{\.,\?!]";
1766 // find first letter after word break
1767 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1769 if ( function_exists( 'mb_strtoupper' ) ) {
1770 return preg_replace_callback(
1772 array( $this, 'ucwordbreaksCallbackMB' ),
1776 return preg_replace_callback(
1778 array( $this, 'ucwordsCallbackWiki' ),
1783 return preg_replace_callback(
1784 '/\b([\w\x80-\xff]+)\b/',
1785 array( $this, 'ucwordbreaksCallbackAscii' ),
1792 * Return a case-folded representation of $s
1794 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1795 * and $s2 are the same except for the case of their characters. It is not
1796 * necessary for the value returned to make sense when displayed.
1798 * Do *not* perform any other normalisation in this function. If a caller
1799 * uses this function when it should be using a more general normalisation
1800 * function, then fix the caller.
1802 function caseFold( $s ) {
1803 return $this->uc( $s );
1806 function checkTitleEncoding( $s ) {
1807 if ( is_array( $s ) ) {
1808 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1810 # Check for non-UTF-8 URLs
1811 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1816 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1817 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1822 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1825 function fallback8bitEncoding() {
1826 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1830 * Most writing systems use whitespace to break up words.
1831 * Some languages such as Chinese don't conventionally do this,
1832 * which requires special handling when breaking up words for
1835 function hasWordBreaks() {
1840 * Some languages such as Chinese require word segmentation,
1841 * Specify such segmentation when overridden in derived class.
1843 * @param $string String
1846 function segmentByWord( $string ) {
1851 * Some languages have special punctuation need to be normalized.
1852 * Make such changes here.
1854 * @param $string String
1857 function normalizeForSearch( $string ) {
1858 return self
::convertDoubleWidth( $string );
1862 * convert double-width roman characters to single-width.
1863 * range: ff00-ff5f ~= 0020-007f
1865 protected static function convertDoubleWidth( $string ) {
1866 static $full = null;
1867 static $half = null;
1869 if ( $full === null ) {
1870 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1871 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1872 $full = str_split( $fullWidth, 3 );
1873 $half = str_split( $halfWidth );
1876 $string = str_replace( $full, $half, $string );
1880 protected static function insertSpace( $string, $pattern ) {
1881 $string = preg_replace( $pattern, " $1 ", $string );
1882 $string = preg_replace( '/ +/', ' ', $string );
1886 function convertForSearchResult( $termsArray ) {
1887 # some languages, e.g. Chinese, need to do a conversion
1888 # in order for search results to be displayed correctly
1893 * Get the first character of a string.
1898 function firstChar( $s ) {
1901 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1902 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1907 if ( isset( $matches[1] ) ) {
1908 if ( strlen( $matches[1] ) != 3 ) {
1912 // Break down Hangul syllables to grab the first jamo
1913 $code = utf8ToCodepoint( $matches[1] );
1914 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1916 } elseif ( $code < 0xb098 ) {
1917 return "\xe3\x84\xb1";
1918 } elseif ( $code < 0xb2e4 ) {
1919 return "\xe3\x84\xb4";
1920 } elseif ( $code < 0xb77c ) {
1921 return "\xe3\x84\xb7";
1922 } elseif ( $code < 0xb9c8 ) {
1923 return "\xe3\x84\xb9";
1924 } elseif ( $code < 0xbc14 ) {
1925 return "\xe3\x85\x81";
1926 } elseif ( $code < 0xc0ac ) {
1927 return "\xe3\x85\x82";
1928 } elseif ( $code < 0xc544 ) {
1929 return "\xe3\x85\x85";
1930 } elseif ( $code < 0xc790 ) {
1931 return "\xe3\x85\x87";
1932 } elseif ( $code < 0xcc28 ) {
1933 return "\xe3\x85\x88";
1934 } elseif ( $code < 0xce74 ) {
1935 return "\xe3\x85\x8a";
1936 } elseif ( $code < 0xd0c0 ) {
1937 return "\xe3\x85\x8b";
1938 } elseif ( $code < 0xd30c ) {
1939 return "\xe3\x85\x8c";
1940 } elseif ( $code < 0xd558 ) {
1941 return "\xe3\x85\x8d";
1943 return "\xe3\x85\x8e";
1950 function initEncoding() {
1951 # Some languages may have an alternate char encoding option
1952 # (Esperanto X-coding, Japanese furigana conversion, etc)
1953 # If this language is used as the primary content language,
1954 # an override to the defaults can be set here on startup.
1957 function recodeForEdit( $s ) {
1958 # For some languages we'll want to explicitly specify
1959 # which characters make it into the edit box raw
1960 # or are converted in some way or another.
1961 # Note that if wgOutputEncoding is different from
1962 # wgInputEncoding, this text will be further converted
1963 # to wgOutputEncoding.
1964 global $wgEditEncoding;
1965 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1968 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1972 function recodeInput( $s ) {
1973 # Take the previous into account.
1974 global $wgEditEncoding;
1975 if ( $wgEditEncoding != '' ) {
1976 $enc = $wgEditEncoding;
1980 if ( $enc == 'UTF-8' ) {
1983 return $this->iconv( $enc, 'UTF-8', $s );
1988 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1989 * also cleans up certain backwards-compatible sequences, converting them
1990 * to the modern Unicode equivalent.
1992 * This is language-specific for performance reasons only.
1994 function normalize( $s ) {
1995 global $wgAllUnicodeFixes;
1996 $s = UtfNormal
::cleanUp( $s );
1997 if ( $wgAllUnicodeFixes ) {
1998 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1999 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2006 * Transform a string using serialized data stored in the given file (which
2007 * must be in the serialized subdirectory of $IP). The file contains pairs
2008 * mapping source characters to destination characters.
2010 * The data is cached in process memory. This will go faster if you have the
2011 * FastStringSearch extension.
2013 function transformUsingPairFile( $file, $string ) {
2014 if ( !isset( $this->transformData
[$file] ) ) {
2015 $data = wfGetPrecompiledData( $file );
2016 if ( $data === false ) {
2017 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2019 $this->transformData
[$file] = new ReplacementArray( $data );
2021 return $this->transformData
[$file]->replace( $string );
2025 * For right-to-left language support
2030 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2034 * Return the correct HTML 'dir' attribute value for this language.
2038 return $this->isRTL() ?
'rtl' : 'ltr';
2042 * Return 'left' or 'right' as appropriate alignment for line-start
2043 * for this language's text direction.
2045 * Should be equivalent to CSS3 'start' text-align value....
2049 function alignStart() {
2050 return $this->isRTL() ?
'right' : 'left';
2054 * Return 'right' or 'left' as appropriate alignment for line-end
2055 * for this language's text direction.
2057 * Should be equivalent to CSS3 'end' text-align value....
2061 function alignEnd() {
2062 return $this->isRTL() ?
'left' : 'right';
2066 * A hidden direction mark (LRM or RLM), depending on the language direction
2070 function getDirMark() {
2071 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2074 function capitalizeAllNouns() {
2075 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2079 * An arrow, depending on the language direction
2083 function getArrow() {
2084 return $this->isRTL() ?
'←' : '→';
2088 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2092 function linkPrefixExtension() {
2093 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2096 function getMagicWords() {
2097 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2100 # Fill a MagicWord object with data from here
2101 function getMagic( $mw ) {
2102 if ( !$this->mMagicHookDone
) {
2103 $this->mMagicHookDone
= true;
2104 wfProfileIn( 'LanguageGetMagic' );
2105 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2106 wfProfileOut( 'LanguageGetMagic' );
2108 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2109 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2111 $magicWords = $this->getMagicWords();
2112 if ( isset( $magicWords[$mw->mId
] ) ) {
2113 $rawEntry = $magicWords[$mw->mId
];
2119 if ( !is_array( $rawEntry ) ) {
2120 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2122 $mw->mCaseSensitive
= $rawEntry[0];
2123 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2128 * Add magic words to the extension array
2130 function addMagicWordsByLang( $newWords ) {
2131 $code = $this->getCode();
2132 $fallbackChain = array();
2133 while ( $code && !in_array( $code, $fallbackChain ) ) {
2134 $fallbackChain[] = $code;
2135 $code = self
::getFallbackFor( $code );
2137 if ( !in_array( 'en', $fallbackChain ) ) {
2138 $fallbackChain[] = 'en';
2140 $fallbackChain = array_reverse( $fallbackChain );
2141 foreach ( $fallbackChain as $code ) {
2142 if ( isset( $newWords[$code] ) ) {
2143 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2149 * Get special page names, as an associative array
2150 * case folded alias => real name
2152 function getSpecialPageAliases() {
2153 // Cache aliases because it may be slow to load them
2154 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2156 $this->mExtendedSpecialPageAliases
=
2157 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2158 wfRunHooks( 'LanguageGetSpecialPageAliases',
2159 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2162 return $this->mExtendedSpecialPageAliases
;
2166 * Italic is unsuitable for some languages
2168 * @param $text String: the text to be emphasized.
2171 function emphasize( $text ) {
2172 return "<em>$text</em>";
2176 * Normally we output all numbers in plain en_US style, that is
2177 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2178 * point twohundredthirtyfive. However this is not sutable for all
2179 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2180 * Icelandic just want to use commas instead of dots, and dots instead
2181 * of commas like "293.291,235".
2183 * An example of this function being called:
2185 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2188 * See LanguageGu.php for the Gujarati implementation and
2189 * $separatorTransformTable on MessageIs.php for
2190 * the , => . and . => , implementation.
2192 * @todo check if it's viable to use localeconv() for the decimal
2194 * @param $number Mixed: the string to be formatted, should be an integer
2195 * or a floating point number.
2196 * @param $nocommafy Bool: set to true for special numbers like dates
2199 function formatNum( $number, $nocommafy = false ) {
2200 global $wgTranslateNumerals;
2201 if ( !$nocommafy ) {
2202 $number = $this->commafy( $number );
2203 $s = $this->separatorTransformTable();
2205 $number = strtr( $number, $s );
2209 if ( $wgTranslateNumerals ) {
2210 $s = $this->digitTransformTable();
2212 $number = strtr( $number, $s );
2219 function parseFormattedNumber( $number ) {
2220 $s = $this->digitTransformTable();
2222 $number = strtr( $number, array_flip( $s ) );
2225 $s = $this->separatorTransformTable();
2227 $number = strtr( $number, array_flip( $s ) );
2230 $number = strtr( $number, array( ',' => '' ) );
2235 * Adds commas to a given number
2240 function commafy( $_ ) {
2241 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2244 function digitTransformTable() {
2245 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2248 function separatorTransformTable() {
2249 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2253 * Take a list of strings and build a locale-friendly comma-separated
2254 * list, using the local comma-separator message.
2255 * The last two strings are chained with an "and".
2260 function listToText( $l ) {
2262 $m = count( $l ) - 1;
2264 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2266 for ( $i = $m; $i >= 0; $i-- ) {
2269 } else if ( $i == $m - 1 ) {
2270 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2272 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2280 * Take a list of strings and build a locale-friendly comma-separated
2281 * list, using the local comma-separator message.
2282 * @param $list array of strings to put in a comma list
2285 function commaList( $list ) {
2290 array( 'parsemag', 'escapenoentities', 'language' => $this )
2296 * Take a list of strings and build a locale-friendly semicolon-separated
2297 * list, using the local semicolon-separator message.
2298 * @param $list array of strings to put in a semicolon list
2301 function semicolonList( $list ) {
2305 'semicolon-separator',
2306 array( 'parsemag', 'escapenoentities', 'language' => $this )
2312 * Same as commaList, but separate it with the pipe instead.
2313 * @param $list array of strings to put in a pipe list
2316 function pipeList( $list ) {
2321 array( 'escapenoentities', 'language' => $this )
2327 * Truncate a string to a specified length in bytes, appending an optional
2328 * string (e.g. for ellipses)
2330 * The database offers limited byte lengths for some columns in the database;
2331 * multi-byte character sets mean we need to ensure that only whole characters
2332 * are included, otherwise broken characters can be passed to the user
2334 * If $length is negative, the string will be truncated from the beginning
2336 * @param $string String to truncate
2337 * @param $length Int: maximum length (excluding ellipses)
2338 * @param $ellipsis String to append to the truncated text
2341 function truncate( $string, $length, $ellipsis = '...' ) {
2342 # Use the localized ellipsis character
2343 if ( $ellipsis == '...' ) {
2344 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2346 # Check if there is no need to truncate
2347 if ( $length == 0 ) {
2349 } elseif ( strlen( $string ) <= abs( $length ) ) {
2352 $stringOriginal = $string;
2353 if ( $length > 0 ) {
2354 $string = substr( $string, 0, $length ); // xyz...
2355 $string = $this->removeBadCharLast( $string );
2356 $string = $string . $ellipsis;
2358 $string = substr( $string, $length ); // ...xyz
2359 $string = $this->removeBadCharFirst( $string );
2360 $string = $ellipsis . $string;
2362 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2363 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2366 return $stringOriginal;
2371 * Remove bytes that represent an incomplete Unicode character
2372 * at the end of string (e.g. bytes of the char are missing)
2374 * @param $string String
2377 protected function removeBadCharLast( $string ) {
2378 $char = ord( $string[strlen( $string ) - 1] );
2380 if ( $char >= 0xc0 ) {
2381 # We got the first byte only of a multibyte char; remove it.
2382 $string = substr( $string, 0, -1 );
2383 } elseif ( $char >= 0x80 &&
2384 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2385 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2387 # We chopped in the middle of a character; remove it
2394 * Remove bytes that represent an incomplete Unicode character
2395 * at the start of string (e.g. bytes of the char are missing)
2397 * @param $string String
2400 protected function removeBadCharFirst( $string ) {
2401 $char = ord( $string[0] );
2402 if ( $char >= 0x80 && $char < 0xc0 ) {
2403 # We chopped in the middle of a character; remove the whole thing
2404 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2410 * Truncate a string of valid HTML to a specified length in bytes,
2411 * appending an optional string (e.g. for ellipses), and return valid HTML
2413 * This is only intended for styled/linked text, such as HTML with
2414 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2416 * Note: tries to fix broken HTML with MWTidy
2418 * @param string $text HTML string to truncate
2419 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2420 * @param string $ellipsis String to append to the truncated text
2423 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2424 # Use the localized ellipsis character
2425 if ( $ellipsis == '...' ) {
2426 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2428 # Check if there is no need to truncate
2429 if ( $length <= 0 ) {
2430 return $ellipsis; // no text shown, nothing to format
2431 } elseif ( strlen( $text ) <= $length ) {
2432 return $text; // string short enough even *with* HTML
2434 $text = MWTidy
::tidy( $text ); // fix tags
2435 $displayLen = 0; // innerHTML legth so far
2436 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2437 $tagType = 0; // 0-open, 1-close
2438 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2439 $entityState = 0; // 0-not entity, 1-entity
2441 $openTags = array(); // open tag stack
2442 $textLen = strlen( $text );
2443 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2445 $lastCh = $pos ?
$text[$pos - 1] : '';
2446 $ret .= $ch; // add to result string
2448 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2449 $entityState = 0; // for bad HTML
2450 $bracketState = 1; // tag started (checking for backslash)
2451 } elseif ( $ch == '>' ) {
2452 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2453 $entityState = 0; // for bad HTML
2454 $bracketState = 0; // out of brackets
2455 } elseif ( $bracketState == 1 ) {
2457 $tagType = 1; // close tag (e.g. "</span>")
2459 $tagType = 0; // open tag (e.g. "<span>")
2462 $bracketState = 2; // building tag name
2463 } elseif ( $bracketState == 2 ) {
2467 // Name found (e.g. "<a href=..."), add on tag attributes...
2468 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2470 } elseif ( $bracketState == 0 ) {
2471 if ( $entityState ) {
2474 $displayLen++
; // entity is one displayed char
2478 $entityState = 1; // entity found, (e.g. " ")
2480 $displayLen++
; // this char is displayed
2481 // Add on the other display text after this...
2482 $skipped = $this->truncate_skip(
2483 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2484 $displayLen +
= $skipped;
2489 # Consider truncation once the display length has reached the maximim.
2490 # Double-check that we're not in the middle of a bracket/entity...
2491 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2492 if ( !$testingEllipsis ) {
2493 $testingEllipsis = true;
2494 # Save where we are; we will truncate here unless
2495 # the ellipsis actually makes the string longer.
2496 $pOpenTags = $openTags; // save state
2497 $pRet = $ret; // save state
2498 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2499 # Ellipsis won't make string longer/equal, the truncation point was OK.
2500 $openTags = $pOpenTags; // reload state
2501 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2502 $ret .= $ellipsis; // add ellipsis
2507 if ( $displayLen == 0 ) {
2508 return ''; // no text shown, nothing to format
2510 // Close the last tag if left unclosed by bad HTML
2511 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2512 while ( count( $openTags ) > 0 ) {
2513 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2518 // truncateHtml() helper function
2519 // like strcspn() but adds the skipped chars to $ret
2520 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2522 if ( $start < strlen( $text ) ) {
2523 $skipCount = strcspn( $text, $search, $start, $len );
2524 $ret .= substr( $text, $start, $skipCount );
2530 * truncateHtml() helper function
2531 * (a) push or pop $tag from $openTags as needed
2532 * (b) clear $tag value
2533 * @param String &$tag Current HTML tag name we are looking at
2534 * @param int $tagType (0-open tag, 1-close tag)
2535 * @param char $lastCh Character before the '>' that ended this tag
2536 * @param array &$openTags Open tag stack (not accounting for $tag)
2538 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2539 $tag = ltrim( $tag );
2541 if ( $tagType == 0 && $lastCh != '/' ) {
2542 $openTags[] = $tag; // tag opened (didn't close itself)
2543 } else if ( $tagType == 1 ) {
2544 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2545 array_pop( $openTags ); // tag closed
2553 * Grammatical transformations, needed for inflected languages
2554 * Invoked by putting {{grammar:case|word}} in a message
2556 * @param $word string
2557 * @param $case string
2560 function convertGrammar( $word, $case ) {
2561 global $wgGrammarForms;
2562 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2563 return $wgGrammarForms[$this->getCode()][$case][$word];
2569 * Provides an alternative text depending on specified gender.
2570 * Usage {{gender:username|masculine|feminine|neutral}}.
2571 * username is optional, in which case the gender of current user is used,
2572 * but only in (some) interface messages; otherwise default gender is used.
2573 * If second or third parameter are not specified, masculine is used.
2574 * These details may be overriden per language.
2576 function gender( $gender, $forms ) {
2577 if ( !count( $forms ) ) {
2580 $forms = $this->preConvertPlural( $forms, 2 );
2581 if ( $gender === 'male' ) {
2584 if ( $gender === 'female' ) {
2587 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2591 * Plural form transformations, needed for some languages.
2592 * For example, there are 3 form of plural in Russian and Polish,
2593 * depending on "count mod 10". See [[w:Plural]]
2594 * For English it is pretty simple.
2596 * Invoked by putting {{plural:count|wordform1|wordform2}}
2597 * or {{plural:count|wordform1|wordform2|wordform3}}
2599 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2601 * @param $count Integer: non-localized number
2602 * @param $forms Array: different plural forms
2603 * @return string Correct form of plural for $count in this language
2605 function convertPlural( $count, $forms ) {
2606 if ( !count( $forms ) ) {
2609 $forms = $this->preConvertPlural( $forms, 2 );
2611 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2615 * Checks that convertPlural was given an array and pads it to requested
2616 * amound of forms by copying the last one.
2618 * @param $count Integer: How many forms should there be at least
2619 * @param $forms Array of forms given to convertPlural
2620 * @return array Padded array of forms or an exception if not an array
2622 protected function preConvertPlural( /* Array */ $forms, $count ) {
2623 while ( count( $forms ) < $count ) {
2624 $forms[] = $forms[count( $forms ) - 1];
2630 * For translating of expiry times
2631 * @param $str String: the validated block time in English
2632 * @return Somehow translated block time
2633 * @see LanguageFi.php for example implementation
2635 function translateBlockExpiry( $str ) {
2636 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2638 if ( $scBlockExpiryOptions == '-' ) {
2642 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2643 if ( strpos( $option, ':' ) === false ) {
2646 list( $show, $value ) = explode( ':', $option );
2647 if ( strcmp( $str, $value ) == 0 ) {
2648 return htmlspecialchars( trim( $show ) );
2656 * languages like Chinese need to be segmented in order for the diff
2659 * @param $text String
2662 function segmentForDiff( $text ) {
2667 * and unsegment to show the result
2669 * @param $text String
2672 function unsegmentForDiff( $text ) {
2676 # convert text to all supported variants
2677 function autoConvertToAllVariants( $text ) {
2678 return $this->mConverter
->autoConvertToAllVariants( $text );
2681 # convert text to different variants of a language.
2682 function convert( $text ) {
2683 return $this->mConverter
->convert( $text );
2686 # Convert a Title object to a string in the preferred variant
2687 function convertTitle( $title ) {
2688 return $this->mConverter
->convertTitle( $title );
2691 # Check if this is a language with variants
2692 function hasVariants() {
2693 return sizeof( $this->getVariants() ) > 1;
2696 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2697 function armourMath( $text ) {
2698 return $this->mConverter
->armourMath( $text );
2702 * Perform output conversion on a string, and encode for safe HTML output.
2703 * @param $text String text to be converted
2704 * @param $isTitle Bool whether this conversion is for the article title
2706 * @todo this should get integrated somewhere sane
2708 function convertHtml( $text, $isTitle = false ) {
2709 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2712 function convertCategoryKey( $key ) {
2713 return $this->mConverter
->convertCategoryKey( $key );
2717 * Get the list of variants supported by this language
2718 * see sample implementation in LanguageZh.php
2720 * @return array an array of language codes
2722 function getVariants() {
2723 return $this->mConverter
->getVariants();
2726 function getPreferredVariant() {
2727 return $this->mConverter
->getPreferredVariant();
2730 function getDefaultVariant() {
2731 return $this->mConverter
->getDefaultVariant();
2734 function getURLVariant() {
2735 return $this->mConverter
->getURLVariant();
2739 * If a language supports multiple variants, it is
2740 * possible that non-existing link in one variant
2741 * actually exists in another variant. this function
2742 * tries to find it. See e.g. LanguageZh.php
2744 * @param $link String: the name of the link
2745 * @param $nt Mixed: the title object of the link
2746 * @param $ignoreOtherCond Boolean: to disable other conditions when
2747 * we need to transclude a template or update a category's link
2748 * @return null the input parameters may be modified upon return
2750 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2751 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2755 * If a language supports multiple variants, converts text
2756 * into an array of all possible variants of the text:
2757 * 'variant' => text in that variant
2759 * @deprecated Use autoConvertToAllVariants()
2761 function convertLinkToAllVariants( $text ) {
2762 return $this->mConverter
->convertLinkToAllVariants( $text );
2766 * returns language specific options used by User::getPageRenderHash()
2767 * for example, the preferred language variant
2771 function getExtraHashOptions() {
2772 return $this->mConverter
->getExtraHashOptions();
2776 * For languages that support multiple variants, the title of an
2777 * article may be displayed differently in different variants. this
2778 * function returns the apporiate title defined in the body of the article.
2782 function getParsedTitle() {
2783 return $this->mConverter
->getParsedTitle();
2787 * Enclose a string with the "no conversion" tag. This is used by
2788 * various functions in the Parser
2790 * @param $text String: text to be tagged for no conversion
2792 * @return string the tagged text
2794 function markNoConversion( $text, $noParse = false ) {
2795 return $this->mConverter
->markNoConversion( $text, $noParse );
2799 * A regular expression to match legal word-trailing characters
2800 * which should be merged onto a link of the form [[foo]]bar.
2804 function linkTrail() {
2805 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2808 function getLangObj() {
2813 * Get the RFC 3066 code for this language object
2815 function getCode() {
2816 return $this->mCode
;
2819 function setCode( $code ) {
2820 $this->mCode
= $code;
2824 * Get the name of a file for a certain language code
2825 * @param $prefix string Prepend this to the filename
2826 * @param $code string Language code
2827 * @param $suffix string Append this to the filename
2828 * @return string $prefix . $mangledCode . $suffix
2830 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2831 // Protect against path traversal
2832 if ( !Language
::isValidCode( $code )
2833 ||
strcspn( $code, "/\\\000" ) !== strlen( $code ) )
2835 throw new MWException( "Invalid language code \"$code\"" );
2838 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2842 * Get the language code from a file name. Inverse of getFileName()
2843 * @param $filename string $prefix . $languageCode . $suffix
2844 * @param $prefix string Prefix before the language code
2845 * @param $suffix string Suffix after the language code
2846 * @return Language code, or false if $prefix or $suffix isn't found
2848 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2850 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2851 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2852 if ( !count( $m ) ) {
2855 return str_replace( '_', '-', strtolower( $m[1] ) );
2858 static function getMessagesFileName( $code ) {
2860 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2863 static function getClassFileName( $code ) {
2865 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2869 * Get the fallback for a given language
2871 static function getFallbackFor( $code ) {
2872 if ( $code === 'en' ) {
2876 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2881 * Get all messages for a given language
2882 * WARNING: this may take a long time
2884 static function getMessagesFor( $code ) {
2885 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2889 * Get a message for a given language
2891 static function getMessageFor( $key, $code ) {
2892 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2895 function fixVariableInNamespace( $talk ) {
2896 if ( strpos( $talk, '$1' ) === false ) {
2900 global $wgMetaNamespace;
2901 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2903 # Allow grammar transformations
2904 # Allowing full message-style parsing would make simple requests
2905 # such as action=raw much more expensive than they need to be.
2906 # This will hopefully cover most cases.
2907 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2908 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2909 return str_replace( ' ', '_', $talk );
2912 function replaceGrammarInNamespace( $m ) {
2913 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2916 static function getCaseMaps() {
2917 static $wikiUpperChars, $wikiLowerChars;
2918 if ( isset( $wikiUpperChars ) ) {
2919 return array( $wikiUpperChars, $wikiLowerChars );
2922 wfProfileIn( __METHOD__
);
2923 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2924 if ( $arr === false ) {
2925 throw new MWException(
2926 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2928 $wikiUpperChars = $arr['wikiUpperChars'];
2929 $wikiLowerChars = $arr['wikiLowerChars'];
2930 wfProfileOut( __METHOD__
);
2931 return array( $wikiUpperChars, $wikiLowerChars );
2934 function formatTimePeriod( $seconds ) {
2935 if ( round( $seconds * 10 ) < 100 ) {
2936 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2937 } elseif ( round( $seconds ) < 60 ) {
2938 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2939 } elseif ( round( $seconds ) < 3600 ) {
2940 $minutes = floor( $seconds / 60 );
2941 $secondsPart = round( fmod( $seconds, 60 ) );
2942 if ( $secondsPart == 60 ) {
2946 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2947 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2949 $hours = floor( $seconds / 3600 );
2950 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2951 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2952 if ( $secondsPart == 60 ) {
2956 if ( $minutes == 60 ) {
2960 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2961 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2962 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2966 function formatBitrate( $bps ) {
2967 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2969 return $this->formatNum( $bps ) . $units[0];
2971 $unitIndex = floor( log10( $bps ) / 3 );
2972 $mantissa = $bps / pow( 1000, $unitIndex );
2973 if ( $mantissa < 10 ) {
2974 $mantissa = round( $mantissa, 1 );
2976 $mantissa = round( $mantissa );
2978 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2982 * Format a size in bytes for output, using an appropriate
2983 * unit (B, KB, MB or GB) according to the magnitude in question
2985 * @param $size Size to format
2986 * @return string Plain text (not HTML)
2988 function formatSize( $size ) {
2989 // For small sizes no decimal places necessary
2991 if ( $size > 1024 ) {
2992 $size = $size / 1024;
2993 if ( $size > 1024 ) {
2994 $size = $size / 1024;
2995 // For MB and bigger two decimal places are smarter
2997 if ( $size > 1024 ) {
2998 $size = $size / 1024;
2999 $msg = 'size-gigabytes';
3001 $msg = 'size-megabytes';
3004 $msg = 'size-kilobytes';
3007 $msg = 'size-bytes';
3009 $size = round( $size, $round );
3010 $text = $this->getMessageFromDB( $msg );
3011 return str_replace( '$1', $this->formatNum( $size ), $text );
3015 * Get the conversion rule title, if any.
3017 function getConvRuleTitle() {
3018 return $this->mConverter
->getConvRuleTitle();