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;
157 if ( $code == 'en' ) {
160 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
161 // Preload base classes to work around APC/PHP5 bug
162 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
163 include_once( "$IP/languages/classes/$class.deps.php" );
165 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
166 include_once( "$IP/languages/classes/$class.php" );
170 if ( $recursionLevel > 5 ) {
171 throw new MWException( "Language fallback loop detected when creating class $class\n" );
174 if ( !class_exists( $class ) ) {
175 $fallback = Language
::getFallbackFor( $code );
177 $lang = Language
::newFromCode( $fallback );
179 $lang->setCode( $code );
187 * Get the LocalisationCache instance
189 public static function getLocalisationCache() {
190 if ( is_null( self
::$dataCache ) ) {
191 global $wgLocalisationCacheConf;
192 $class = $wgLocalisationCacheConf['class'];
193 self
::$dataCache = new $class( $wgLocalisationCacheConf );
195 return self
::$dataCache;
198 function __construct() {
199 $this->mConverter
= new FakeConverter( $this );
200 // Set the code to the name of the descendant
201 if ( get_class( $this ) == 'Language' ) {
204 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
206 self
::getLocalisationCache();
210 * Reduce memory usage
212 function __destruct() {
213 foreach ( $this as $name => $value ) {
214 unset( $this->$name );
219 * Hook which will be called if this is the content language.
220 * Descendants can use this to register hook functions or modify globals
222 function initContLang() { }
225 * @deprecated Use User::getDefaultOptions()
228 function getDefaultUserOptions() {
229 wfDeprecated( __METHOD__
);
230 return User
::getDefaultOptions();
233 function getFallbackLanguageCode() {
234 if ( $this->mCode
=== 'en' ) {
237 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
242 * Exports $wgBookstoreListEn
245 function getBookstoreList() {
246 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
252 function getNamespaces() {
253 if ( is_null( $this->namespaceNames
) ) {
254 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
256 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
257 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
259 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
261 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
262 if ( $wgMetaNamespaceTalk ) {
263 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
265 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
266 $this->namespaceNames
[NS_PROJECT_TALK
] =
267 $this->fixVariableInNamespace( $talk );
270 # Sometimes a language will be localised but not actually exist on this wiki.
271 foreach( $this->namespaceNames
as $key => $text ) {
272 if ( !isset( $validNamespaces[$key] ) ) {
273 unset( $this->namespaceNames
[$key] );
277 # The above mixing may leave namespaces out of canonical order.
278 # Re-order by namespace ID number...
279 ksort( $this->namespaceNames
);
281 return $this->namespaceNames
;
285 * A convenience function that returns the same thing as
286 * getNamespaces() except with the array values changed to ' '
287 * where it found '_', useful for producing output to be displayed
288 * e.g. in <select> forms.
292 function getFormattedNamespaces() {
293 $ns = $this->getNamespaces();
294 foreach ( $ns as $k => $v ) {
295 $ns[$k] = strtr( $v, '_', ' ' );
301 * Get a namespace value by key
303 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
304 * echo $mw_ns; // prints 'MediaWiki'
307 * @param $index Int: the array key of the namespace to return
308 * @return mixed, string if the namespace value exists, otherwise false
310 function getNsText( $index ) {
311 $ns = $this->getNamespaces();
312 return isset( $ns[$index] ) ?
$ns[$index] : false;
316 * A convenience function that returns the same thing as
317 * getNsText() except with '_' changed to ' ', useful for
322 function getFormattedNsText( $index ) {
323 $ns = $this->getNsText( $index );
324 return strtr( $ns, '_', ' ' );
328 * Get a namespace key by value, case insensitive.
329 * Only matches namespace names for the current language, not the
330 * canonical ones defined in Namespace.php.
332 * @param $text String
333 * @return mixed An integer if $text is a valid value otherwise false
335 function getLocalNsIndex( $text ) {
336 $lctext = $this->lc( $text );
337 $ids = $this->getNamespaceIds();
338 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
341 function getNamespaceAliases() {
342 if ( is_null( $this->namespaceAliases
) ) {
343 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
347 foreach ( $aliases as $name => $index ) {
348 if ( $index === NS_PROJECT_TALK
) {
349 unset( $aliases[$name] );
350 $name = $this->fixVariableInNamespace( $name );
351 $aliases[$name] = $index;
355 $this->namespaceAliases
= $aliases;
357 return $this->namespaceAliases
;
360 function getNamespaceIds() {
361 if ( is_null( $this->mNamespaceIds
) ) {
362 global $wgNamespaceAliases;
363 # Put namespace names and aliases into a hashtable.
364 # If this is too slow, then we should arrange it so that it is done
365 # before caching. The catch is that at pre-cache time, the above
366 # class-specific fixup hasn't been done.
367 $this->mNamespaceIds
= array();
368 foreach ( $this->getNamespaces() as $index => $name ) {
369 $this->mNamespaceIds
[$this->lc( $name )] = $index;
371 foreach ( $this->getNamespaceAliases() as $name => $index ) {
372 $this->mNamespaceIds
[$this->lc( $name )] = $index;
374 if ( $wgNamespaceAliases ) {
375 foreach ( $wgNamespaceAliases as $name => $index ) {
376 $this->mNamespaceIds
[$this->lc( $name )] = $index;
380 return $this->mNamespaceIds
;
385 * Get a namespace key by value, case insensitive. Canonical namespace
386 * names override custom ones defined for the current language.
388 * @param $text String
389 * @return mixed An integer if $text is a valid value otherwise false
391 function getNsIndex( $text ) {
392 $lctext = $this->lc( $text );
393 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
396 $ids = $this->getNamespaceIds();
397 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
401 * short names for language variants used for language conversion links.
403 * @param $code String
406 function getVariantname( $code ) {
407 return $this->getMessageFromDB( "variantname-$code" );
410 function specialPage( $name ) {
411 $aliases = $this->getSpecialPageAliases();
412 if ( isset( $aliases[$name][0] ) ) {
413 $name = $aliases[$name][0];
415 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
418 function getQuickbarSettings() {
420 $this->getMessage( 'qbsettings-none' ),
421 $this->getMessage( 'qbsettings-fixedleft' ),
422 $this->getMessage( 'qbsettings-fixedright' ),
423 $this->getMessage( 'qbsettings-floatingleft' ),
424 $this->getMessage( 'qbsettings-floatingright' )
428 function getMathNames() {
429 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
432 function getDatePreferences() {
433 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
436 function getDateFormats() {
437 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
440 function getDefaultDateFormat() {
441 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
442 if ( $df === 'dmy or mdy' ) {
443 global $wgAmericanDates;
444 return $wgAmericanDates ?
'mdy' : 'dmy';
450 function getDatePreferenceMigrationMap() {
451 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
454 function getImageFile( $image ) {
455 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
458 function getDefaultUserOptionOverrides() {
459 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
462 function getExtraUserToggles() {
463 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
466 function getUserToggle( $tog ) {
467 return $this->getMessageFromDB( "tog-$tog" );
471 * Get language names, indexed by code.
472 * If $customisedOnly is true, only returns codes with a messages file
474 public static function getLanguageNames( $customisedOnly = false ) {
475 global $wgLanguageNames, $wgExtraLanguageNames;
476 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
477 if ( !$customisedOnly ) {
483 $dir = opendir( "$IP/languages/messages" );
484 while ( false !== ( $file = readdir( $dir ) ) ) {
485 $code = self
::getCodeFromFileName( $file, 'Messages' );
486 if ( $code && isset( $allNames[$code] ) ) {
487 $names[$code] = $allNames[$code];
495 * Get translated language names. This is done on best effort and
496 * by default this is exactly the same as Language::getLanguageNames.
497 * The CLDR extension provides translated names.
498 * @param $code String Language code.
499 * @return Array language code => language name
502 public static function getTranslatedLanguageNames( $code ) {
504 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
506 foreach ( self
::getLanguageNames() as $code => $name ) {
507 if ( !isset( $names[$code] ) ) $names[$code] = $name;
514 * Get a message from the MediaWiki namespace.
516 * @param $msg String: message name
519 function getMessageFromDB( $msg ) {
520 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
523 function getLanguageName( $code ) {
524 $names = self
::getLanguageNames();
525 if ( !array_key_exists( $code, $names ) ) {
528 return $names[$code];
531 function getMonthName( $key ) {
532 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
535 function getMonthNameGen( $key ) {
536 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
539 function getMonthAbbreviation( $key ) {
540 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
543 function getWeekdayName( $key ) {
544 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
547 function getWeekdayAbbreviation( $key ) {
548 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
551 function getIranianCalendarMonthName( $key ) {
552 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
555 function getHebrewCalendarMonthName( $key ) {
556 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
559 function getHebrewCalendarMonthNameGen( $key ) {
560 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
563 function getHijriCalendarMonthName( $key ) {
564 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
568 * Used by date() and time() to adjust the time output.
570 * @param $ts Int the time in date('YmdHis') format
571 * @param $tz Mixed: adjust the time by this amount (default false, mean we
572 * get user timecorrection setting)
575 function userAdjust( $ts, $tz = false ) {
576 global $wgUser, $wgLocalTZoffset;
578 if ( $tz === false ) {
579 $tz = $wgUser->getOption( 'timecorrection' );
582 $data = explode( '|', $tz, 3 );
584 if ( $data[0] == 'ZoneInfo' ) {
585 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
586 $date = date_create( $ts, timezone_open( 'UTC' ) );
587 date_timezone_set( $date, timezone_open( $data[2] ) );
588 $date = date_format( $date, 'YmdHis' );
591 # Unrecognized timezone, default to 'Offset' with the stored offset.
596 if ( $data[0] == 'System' ||
$tz == '' ) {
597 # Global offset in minutes.
598 if ( isset( $wgLocalTZoffset ) ) {
599 $minDiff = $wgLocalTZoffset;
601 } else if ( $data[0] == 'Offset' ) {
602 $minDiff = intval( $data[1] );
604 $data = explode( ':', $tz );
605 if ( count( $data ) == 2 ) {
606 $data[0] = intval( $data[0] );
607 $data[1] = intval( $data[1] );
608 $minDiff = abs( $data[0] ) * 60 +
$data[1];
609 if ( $data[0] < 0 ) {
610 $minDiff = -$minDiff;
613 $minDiff = intval( $data[0] ) * 60;
617 # No difference ? Return time unchanged
618 if ( 0 == $minDiff ) {
622 wfSuppressWarnings(); // E_STRICT system time bitching
623 # Generate an adjusted date; take advantage of the fact that mktime
624 # will normalize out-of-range values so we don't have to split $minDiff
625 # into hours and minutes.
627 (int)substr( $ts, 8, 2 ) ), # Hours
628 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
629 (int)substr( $ts, 12, 2 ), # Seconds
630 (int)substr( $ts, 4, 2 ), # Month
631 (int)substr( $ts, 6, 2 ), # Day
632 (int)substr( $ts, 0, 4 ) ); # Year
634 $date = date( 'YmdHis', $t );
641 * This is a workalike of PHP's date() function, but with better
642 * internationalisation, a reduced set of format characters, and a better
645 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
646 * PHP manual for definitions. There are a number of extensions, which
649 * xn Do not translate digits of the next numeric format character
650 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
651 * xr Use roman numerals for the next numeric format character
652 * xh Use hebrew numerals for the next numeric format character
654 * xg Genitive month name
656 * xij j (day number) in Iranian calendar
657 * xiF F (month name) in Iranian calendar
658 * xin n (month number) in Iranian calendar
659 * xiY Y (full year) in Iranian calendar
661 * xjj j (day number) in Hebrew calendar
662 * xjF F (month name) in Hebrew calendar
663 * xjt t (days in month) in Hebrew calendar
664 * xjx xg (genitive month name) in Hebrew calendar
665 * xjn n (month number) in Hebrew calendar
666 * xjY Y (full year) in Hebrew calendar
668 * xmj j (day number) in Hijri calendar
669 * xmF F (month name) in Hijri calendar
670 * xmn n (month number) in Hijri calendar
671 * xmY Y (full year) in Hijri calendar
673 * xkY Y (full year) in Thai solar calendar. Months and days are
674 * identical to the Gregorian calendar
675 * xoY Y (full year) in Minguo calendar or Juche year.
676 * Months and days are identical to the
678 * xtY Y (full year) in Japanese nengo. Months and days are
679 * identical to the Gregorian calendar
681 * Characters enclosed in double quotes will be considered literal (with
682 * the quotes themselves removed). Unmatched quotes will be considered
683 * literal quotes. Example:
685 * "The month is" F => The month is January
688 * Backslash escaping is also supported.
690 * Input timestamp is assumed to be pre-normalized to the desired local
693 * @param $format String
694 * @param $ts String: 14-character timestamp
697 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
699 function sprintfDate( $format, $ts ) {
712 for ( $p = 0; $p < strlen( $format ); $p++
) {
715 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
716 $code .= $format[++
$p];
719 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
720 $code .= $format[++
$p];
731 $rawToggle = !$rawToggle;
740 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
743 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
744 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
747 $num = substr( $ts, 6, 2 );
750 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
751 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
754 $num = intval( substr( $ts, 6, 2 ) );
758 $iranian = self
::tsToIranian( $ts );
764 $hijri = self
::tsToHijri( $ts );
770 $hebrew = self
::tsToHebrew( $ts );
776 $unix = wfTimestamp( TS_UNIX
, $ts );
778 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
782 $unix = wfTimestamp( TS_UNIX
, $ts );
784 $w = gmdate( 'w', $unix );
789 $unix = wfTimestamp( TS_UNIX
, $ts );
791 $num = gmdate( 'w', $unix );
795 $unix = wfTimestamp( TS_UNIX
, $ts );
797 $num = gmdate( 'z', $unix );
801 $unix = wfTimestamp( TS_UNIX
, $ts );
803 $num = gmdate( 'W', $unix );
806 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
810 $iranian = self
::tsToIranian( $ts );
812 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
816 $hijri = self
::tsToHijri( $ts );
818 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
822 $hebrew = self
::tsToHebrew( $ts );
824 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
827 $num = substr( $ts, 4, 2 );
830 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
833 $num = intval( substr( $ts, 4, 2 ) );
837 $iranian = self
::tsToIranian( $ts );
843 $hijri = self
::tsToHijri ( $ts );
849 $hebrew = self
::tsToHebrew( $ts );
855 $unix = wfTimestamp( TS_UNIX
, $ts );
857 $num = gmdate( 't', $unix );
861 $hebrew = self
::tsToHebrew( $ts );
867 $unix = wfTimestamp( TS_UNIX
, $ts );
869 $num = gmdate( 'L', $unix );
873 $unix = wfTimestamp( TS_UNIX
, $ts );
875 $num = date( 'o', $unix );
878 $num = substr( $ts, 0, 4 );
882 $iranian = self
::tsToIranian( $ts );
888 $hijri = self
::tsToHijri( $ts );
894 $hebrew = self
::tsToHebrew( $ts );
900 $thai = self
::tsToYear( $ts, 'thai' );
906 $minguo = self
::tsToYear( $ts, 'minguo' );
912 $tenno = self
::tsToYear( $ts, 'tenno' );
917 $num = substr( $ts, 2, 2 );
920 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
923 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
926 $h = substr( $ts, 8, 2 );
927 $num = $h %
12 ?
$h %
12 : 12;
930 $num = intval( substr( $ts, 8, 2 ) );
933 $h = substr( $ts, 8, 2 );
934 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
937 $num = substr( $ts, 8, 2 );
940 $num = substr( $ts, 10, 2 );
943 $num = substr( $ts, 12, 2 );
947 $unix = wfTimestamp( TS_UNIX
, $ts );
949 $s .= gmdate( 'c', $unix );
953 $unix = wfTimestamp( TS_UNIX
, $ts );
955 $s .= gmdate( 'r', $unix );
959 $unix = wfTimestamp( TS_UNIX
, $ts );
965 if ( $p < strlen( $format ) - 1 ) {
973 if ( $p < strlen( $format ) - 1 ) {
974 $endQuote = strpos( $format, '"', $p +
1 );
975 if ( $endQuote === false ) {
976 # No terminating quote, assume literal "
979 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
983 # Quote at end of string, assume literal "
990 if ( $num !== false ) {
991 if ( $rawToggle ||
$raw ) {
994 } elseif ( $roman ) {
995 $s .= self
::romanNumeral( $num );
997 } elseif ( $hebrewNum ) {
998 $s .= self
::hebrewNumeral( $num );
1001 $s .= $this->formatNum( $num, true );
1008 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1009 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1011 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1012 * Gregorian dates to Iranian dates. Originally written in C, it
1013 * is released under the terms of GNU Lesser General Public
1014 * License. Conversion to PHP was performed by Niklas Laxström.
1016 * Link: http://www.farsiweb.info/jalali/jalali.c
1018 private static function tsToIranian( $ts ) {
1019 $gy = substr( $ts, 0, 4 ) -1600;
1020 $gm = substr( $ts, 4, 2 ) -1;
1021 $gd = substr( $ts, 6, 2 ) -1;
1023 # Days passed from the beginning (including leap years)
1025 +
floor( ( $gy +
3 ) / 4 )
1026 - floor( ( $gy +
99 ) / 100 )
1027 +
floor( ( $gy +
399 ) / 400 );
1030 // Add days of the past months of this year
1031 for ( $i = 0; $i < $gm; $i++
) {
1032 $gDayNo +
= self
::$GREG_DAYS[$i];
1036 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1040 // Days passed in current month
1043 $jDayNo = $gDayNo - 79;
1045 $jNp = floor( $jDayNo / 12053 );
1048 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1051 if ( $jDayNo >= 366 ) {
1052 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1053 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1056 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1057 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1063 return array( $jy, $jm, $jd );
1067 * Converting Gregorian dates to Hijri dates.
1069 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1071 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1073 private static function tsToHijri( $ts ) {
1074 $year = substr( $ts, 0, 4 );
1075 $month = substr( $ts, 4, 2 );
1076 $day = substr( $ts, 6, 2 );
1084 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1085 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1088 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1089 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1090 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1093 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1094 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1097 $zl = $zjd -1948440 +
10632;
1098 $zn = (int)( ( $zl - 1 ) / 10631 );
1099 $zl = $zl - 10631 * $zn +
354;
1100 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1101 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1102 $zm = (int)( ( 24 * $zl ) / 709 );
1103 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1104 $zy = 30 * $zn +
$zj - 30;
1106 return array( $zy, $zm, $zd );
1110 * Converting Gregorian dates to Hebrew dates.
1112 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1113 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1114 * to translate the relevant functions into PHP and release them under
1117 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1118 * and Adar II is 14. In a non-leap year, Adar is 6.
1120 private static function tsToHebrew( $ts ) {
1122 $year = substr( $ts, 0, 4 );
1123 $month = substr( $ts, 4, 2 );
1124 $day = substr( $ts, 6, 2 );
1126 # Calculate Hebrew year
1127 $hebrewYear = $year +
3760;
1129 # Month number when September = 1, August = 12
1131 if ( $month > 12 ) {
1138 # Calculate day of year from 1 September
1140 for ( $i = 1; $i < $month; $i++
) {
1144 # Check if the year is leap
1145 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1148 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1155 # Calculate the start of the Hebrew year
1156 $start = self
::hebrewYearStart( $hebrewYear );
1158 # Calculate next year's start
1159 if ( $dayOfYear <= $start ) {
1160 # Day is before the start of the year - it is the previous year
1162 $nextStart = $start;
1166 # Add days since previous year's 1 September
1168 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1172 # Start of the new (previous) year
1173 $start = self
::hebrewYearStart( $hebrewYear );
1176 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1179 # Calculate Hebrew day of year
1180 $hebrewDayOfYear = $dayOfYear - $start;
1182 # Difference between year's days
1183 $diff = $nextStart - $start;
1184 # Add 12 (or 13 for leap years) days to ignore the difference between
1185 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1186 # difference is only about the year type
1187 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1193 # Check the year pattern, and is leap year
1194 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1195 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1196 # and non-leap years
1197 $yearPattern = $diff %
30;
1198 # Check if leap year
1199 $isLeap = $diff >= 30;
1201 # Calculate day in the month from number of day in the Hebrew year
1202 # Don't check Adar - if the day is not in Adar, we will stop before;
1203 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1204 $hebrewDay = $hebrewDayOfYear;
1207 while ( $hebrewMonth <= 12 ) {
1208 # Calculate days in this month
1209 if ( $isLeap && $hebrewMonth == 6 ) {
1210 # Adar in a leap year
1212 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1214 if ( $hebrewDay <= $days ) {
1218 # Subtract the days of Adar I
1219 $hebrewDay -= $days;
1222 if ( $hebrewDay <= $days ) {
1228 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1229 # Cheshvan in a complete year (otherwise as the rule below)
1231 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1232 # Kislev in an incomplete year (otherwise as the rule below)
1235 # Odd months have 30 days, even have 29
1236 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1238 if ( $hebrewDay <= $days ) {
1239 # In the current month
1242 # Subtract the days of the current month
1243 $hebrewDay -= $days;
1244 # Try in the next month
1249 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1253 * This calculates the Hebrew year start, as days since 1 September.
1254 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1255 * Used for Hebrew date.
1257 private static function hebrewYearStart( $year ) {
1258 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1259 $b = intval( ( $year - 1 ) %
4 );
1260 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1264 $Mar = intval( $m );
1270 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1271 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1273 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1275 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1279 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1284 * Algorithm to convert Gregorian dates to Thai solar dates,
1285 * Minguo dates or Minguo dates.
1287 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1288 * http://en.wikipedia.org/wiki/Minguo_calendar
1289 * http://en.wikipedia.org/wiki/Japanese_era_name
1291 * @param $ts String: 14-character timestamp
1292 * @param $cName String: calender name
1293 * @return Array: converted year, month, day
1295 private static function tsToYear( $ts, $cName ) {
1296 $gy = substr( $ts, 0, 4 );
1297 $gm = substr( $ts, 4, 2 );
1298 $gd = substr( $ts, 6, 2 );
1300 if ( !strcmp( $cName, 'thai' ) ) {
1302 # Add 543 years to the Gregorian calendar
1303 # Months and days are identical
1304 $gy_offset = $gy +
543;
1305 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1307 # Deduct 1911 years from the Gregorian calendar
1308 # Months and days are identical
1309 $gy_offset = $gy - 1911;
1310 } else if ( !strcmp( $cName, 'tenno' ) ) {
1311 # Nengō dates up to Meiji period
1312 # Deduct years from the Gregorian calendar
1313 # depending on the nengo periods
1314 # Months and days are identical
1315 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1317 $gy_gannen = $gy - 1868 +
1;
1318 $gy_offset = $gy_gannen;
1319 if ( $gy_gannen == 1 ) {
1322 $gy_offset = '明治' . $gy_offset;
1324 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1325 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1326 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1327 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1328 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1332 $gy_gannen = $gy - 1912 +
1;
1333 $gy_offset = $gy_gannen;
1334 if ( $gy_gannen == 1 ) {
1337 $gy_offset = '大正' . $gy_offset;
1339 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1340 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1341 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1345 $gy_gannen = $gy - 1926 +
1;
1346 $gy_offset = $gy_gannen;
1347 if ( $gy_gannen == 1 ) {
1350 $gy_offset = '昭和' . $gy_offset;
1353 $gy_gannen = $gy - 1989 +
1;
1354 $gy_offset = $gy_gannen;
1355 if ( $gy_gannen == 1 ) {
1358 $gy_offset = '平成' . $gy_offset;
1364 return array( $gy_offset, $gm, $gd );
1368 * Roman number formatting up to 3000
1370 static function romanNumeral( $num ) {
1371 static $table = array(
1372 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1373 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1374 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1375 array( '', 'M', 'MM', 'MMM' )
1378 $num = intval( $num );
1379 if ( $num > 3000 ||
$num <= 0 ) {
1384 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1385 if ( $num >= $pow10 ) {
1386 $s .= $table[$i][floor( $num / $pow10 )];
1388 $num = $num %
$pow10;
1394 * Hebrew Gematria number formatting up to 9999
1396 static function hebrewNumeral( $num ) {
1397 static $table = array(
1398 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1399 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1400 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1401 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1404 $num = intval( $num );
1405 if ( $num > 9999 ||
$num <= 0 ) {
1410 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1411 if ( $num >= $pow10 ) {
1412 if ( $num == 15 ||
$num == 16 ) {
1413 $s .= $table[0][9] . $table[0][$num - 9];
1416 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1417 if ( $pow10 == 1000 ) {
1422 $num = $num %
$pow10;
1424 if ( strlen( $s ) == 2 ) {
1427 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1428 $str .= substr( $s, strlen( $s ) - 2, 2 );
1430 $start = substr( $str, 0, strlen( $str ) - 2 );
1431 $end = substr( $str, strlen( $str ) - 2 );
1434 $str = $start . 'ך';
1437 $str = $start . 'ם';
1440 $str = $start . 'ן';
1443 $str = $start . 'ף';
1446 $str = $start . 'ץ';
1453 * This is meant to be used by time(), date(), and timeanddate() to get
1454 * the date preference they're supposed to use, it should be used in
1458 * function timeanddate([...], $format = true) {
1459 * $datePreference = $this->dateFormat($format);
1464 * @param $usePrefs Mixed: if true, the user's preference is used
1465 * if false, the site/language default is used
1466 * if int/string, assumed to be a format.
1469 function dateFormat( $usePrefs = true ) {
1472 if ( is_bool( $usePrefs ) ) {
1474 $datePreference = $wgUser->getDatePreference();
1476 $datePreference = (string)User
::getDefaultOption( 'date' );
1479 $datePreference = (string)$usePrefs;
1483 if ( $datePreference == '' ) {
1487 return $datePreference;
1491 * Get a format string for a given type and preference
1492 * @param $type May be date, time or both
1493 * @param $pref The format name as it appears in Messages*.php
1495 function getDateFormatString( $type, $pref ) {
1496 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1497 if ( $pref == 'default' ) {
1498 $pref = $this->getDefaultDateFormat();
1499 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1501 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1502 if ( is_null( $df ) ) {
1503 $pref = $this->getDefaultDateFormat();
1504 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1507 $this->dateFormatStrings
[$type][$pref] = $df;
1509 return $this->dateFormatStrings
[$type][$pref];
1513 * @param $ts Mixed: the time format which needs to be turned into a
1514 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1515 * @param $adj Bool: whether to adjust the time output according to the
1516 * user configured offset ($timecorrection)
1517 * @param $format Mixed: true to use user's date format preference
1518 * @param $timecorrection String: the time offset as returned by
1519 * validateTimeZone() in Special:Preferences
1522 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1523 $ts = wfTimestamp( TS_MW
, $ts );
1525 $ts = $this->userAdjust( $ts, $timecorrection );
1527 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1528 return $this->sprintfDate( $df, $ts );
1532 * @param $ts Mixed: the time format which needs to be turned into a
1533 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1534 * @param $adj Bool: whether to adjust the time output according to the
1535 * user configured offset ($timecorrection)
1536 * @param $format Mixed: true to use user's date format preference
1537 * @param $timecorrection String: the time offset as returned by
1538 * validateTimeZone() in Special:Preferences
1541 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1542 $ts = wfTimestamp( TS_MW
, $ts );
1544 $ts = $this->userAdjust( $ts, $timecorrection );
1546 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1547 return $this->sprintfDate( $df, $ts );
1551 * @param $ts Mixed: the time format which needs to be turned into a
1552 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1553 * @param $adj Bool: whether to adjust the time output according to the
1554 * user configured offset ($timecorrection)
1555 * @param $format Mixed: what format to return, if it's false output the
1556 * default one (default true)
1557 * @param $timecorrection String: the time offset as returned by
1558 * validateTimeZone() in Special:Preferences
1561 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1562 $ts = wfTimestamp( TS_MW
, $ts );
1564 $ts = $this->userAdjust( $ts, $timecorrection );
1566 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1567 return $this->sprintfDate( $df, $ts );
1570 function getMessage( $key ) {
1571 return self
::$dataCache->getSubitem( $this->getCodeForMessage(), 'messages', $key );
1574 function getAllMessages() {
1575 return self
::$dataCache->getItem( $this->getCodeForMessage(), 'messages' );
1578 function iconv( $in, $out, $string ) {
1579 # This is a wrapper for iconv in all languages except esperanto,
1580 # which does some nasty x-conversions beforehand
1582 # Even with //IGNORE iconv can whine about illegal characters in
1583 # *input* string. We just ignore those too.
1584 # REF: http://bugs.php.net/bug.php?id=37166
1585 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1586 wfSuppressWarnings();
1587 $text = iconv( $in, $out . '//IGNORE', $string );
1588 wfRestoreWarnings();
1592 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1593 function ucwordbreaksCallbackAscii( $matches ) {
1594 return $this->ucfirst( $matches[1] );
1597 function ucwordbreaksCallbackMB( $matches ) {
1598 return mb_strtoupper( $matches[0] );
1601 function ucCallback( $matches ) {
1602 list( $wikiUpperChars ) = self
::getCaseMaps();
1603 return strtr( $matches[1], $wikiUpperChars );
1606 function lcCallback( $matches ) {
1607 list( , $wikiLowerChars ) = self
::getCaseMaps();
1608 return strtr( $matches[1], $wikiLowerChars );
1611 function ucwordsCallbackMB( $matches ) {
1612 return mb_strtoupper( $matches[0] );
1615 function ucwordsCallbackWiki( $matches ) {
1616 list( $wikiUpperChars ) = self
::getCaseMaps();
1617 return strtr( $matches[0], $wikiUpperChars );
1621 * Make a string's first character uppercase
1623 function ucfirst( $str ) {
1625 if ( $o < 96 ) { // if already uppercase...
1627 } elseif ( $o < 128 ) {
1628 return ucfirst( $str ); // use PHP's ucfirst()
1630 // fall back to more complex logic in case of multibyte strings
1631 return $this->uc( $str, true );
1636 * Convert a string to uppercase
1638 function uc( $str, $first = false ) {
1639 if ( function_exists( 'mb_strtoupper' ) ) {
1641 if ( $this->isMultibyte( $str ) ) {
1642 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1644 return ucfirst( $str );
1647 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1650 if ( $this->isMultibyte( $str ) ) {
1651 $x = $first ?
'^' : '';
1652 return preg_replace_callback(
1653 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1654 array( $this, 'ucCallback' ),
1658 return $first ?
ucfirst( $str ) : strtoupper( $str );
1663 function lcfirst( $str ) {
1666 return strval( $str );
1667 } elseif ( $o >= 128 ) {
1668 return $this->lc( $str, true );
1669 } elseif ( $o > 96 ) {
1672 $str[0] = strtolower( $str[0] );
1677 function lc( $str, $first = false ) {
1678 if ( function_exists( 'mb_strtolower' ) ) {
1680 if ( $this->isMultibyte( $str ) ) {
1681 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1683 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1686 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1689 if ( $this->isMultibyte( $str ) ) {
1690 $x = $first ?
'^' : '';
1691 return preg_replace_callback(
1692 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1693 array( $this, 'lcCallback' ),
1697 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1702 function isMultibyte( $str ) {
1703 return (bool)preg_match( '/[\x80-\xff]/', $str );
1706 function ucwords( $str ) {
1707 if ( $this->isMultibyte( $str ) ) {
1708 $str = $this->lc( $str );
1710 // regexp to find first letter in each word (i.e. after each space)
1711 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1713 // function to use to capitalize a single char
1714 if ( function_exists( 'mb_strtoupper' ) ) {
1715 return preg_replace_callback(
1717 array( $this, 'ucwordsCallbackMB' ),
1721 return preg_replace_callback(
1723 array( $this, 'ucwordsCallbackWiki' ),
1728 return ucwords( strtolower( $str ) );
1732 # capitalize words at word breaks
1733 function ucwordbreaks( $str ) {
1734 if ( $this->isMultibyte( $str ) ) {
1735 $str = $this->lc( $str );
1737 // since \b doesn't work for UTF-8, we explicitely define word break chars
1738 $breaks = "[ \-\(\)\}\{\.,\?!]";
1740 // find first letter after word break
1741 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1743 if ( function_exists( 'mb_strtoupper' ) ) {
1744 return preg_replace_callback(
1746 array( $this, 'ucwordbreaksCallbackMB' ),
1750 return preg_replace_callback(
1752 array( $this, 'ucwordsCallbackWiki' ),
1757 return preg_replace_callback(
1758 '/\b([\w\x80-\xff]+)\b/',
1759 array( $this, 'ucwordbreaksCallbackAscii' ),
1766 * Return a case-folded representation of $s
1768 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1769 * and $s2 are the same except for the case of their characters. It is not
1770 * necessary for the value returned to make sense when displayed.
1772 * Do *not* perform any other normalisation in this function. If a caller
1773 * uses this function when it should be using a more general normalisation
1774 * function, then fix the caller.
1776 function caseFold( $s ) {
1777 return $this->uc( $s );
1780 function checkTitleEncoding( $s ) {
1781 if ( is_array( $s ) ) {
1782 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1784 # Check for non-UTF-8 URLs
1785 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1790 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1791 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1796 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1799 function fallback8bitEncoding() {
1800 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1804 * Most writing systems use whitespace to break up words.
1805 * Some languages such as Chinese don't conventionally do this,
1806 * which requires special handling when breaking up words for
1809 function hasWordBreaks() {
1814 * Some languages such as Chinese require word segmentation,
1815 * Specify such segmentation when overridden in derived class.
1817 * @param $string String
1820 function segmentByWord( $string ) {
1825 * Some languages have special punctuation need to be normalized.
1826 * Make such changes here.
1828 * @param $string String
1831 function normalizeForSearch( $string ) {
1832 return self
::convertDoubleWidth( $string );
1836 * convert double-width roman characters to single-width.
1837 * range: ff00-ff5f ~= 0020-007f
1839 protected static function convertDoubleWidth( $string ) {
1840 static $full = null;
1841 static $half = null;
1843 if ( $full === null ) {
1844 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1845 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1846 $full = str_split( $fullWidth, 3 );
1847 $half = str_split( $halfWidth );
1850 $string = str_replace( $full, $half, $string );
1854 protected static function insertSpace( $string, $pattern ) {
1855 $string = preg_replace( $pattern, " $1 ", $string );
1856 $string = preg_replace( '/ +/', ' ', $string );
1860 function convertForSearchResult( $termsArray ) {
1861 # some languages, e.g. Chinese, need to do a conversion
1862 # in order for search results to be displayed correctly
1867 * Get the first character of a string.
1872 function firstChar( $s ) {
1875 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1876 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1881 if ( isset( $matches[1] ) ) {
1882 if ( strlen( $matches[1] ) != 3 ) {
1886 // Break down Hangul syllables to grab the first jamo
1887 $code = utf8ToCodepoint( $matches[1] );
1888 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1890 } elseif ( $code < 0xb098 ) {
1891 return "\xe3\x84\xb1";
1892 } elseif ( $code < 0xb2e4 ) {
1893 return "\xe3\x84\xb4";
1894 } elseif ( $code < 0xb77c ) {
1895 return "\xe3\x84\xb7";
1896 } elseif ( $code < 0xb9c8 ) {
1897 return "\xe3\x84\xb9";
1898 } elseif ( $code < 0xbc14 ) {
1899 return "\xe3\x85\x81";
1900 } elseif ( $code < 0xc0ac ) {
1901 return "\xe3\x85\x82";
1902 } elseif ( $code < 0xc544 ) {
1903 return "\xe3\x85\x85";
1904 } elseif ( $code < 0xc790 ) {
1905 return "\xe3\x85\x87";
1906 } elseif ( $code < 0xcc28 ) {
1907 return "\xe3\x85\x88";
1908 } elseif ( $code < 0xce74 ) {
1909 return "\xe3\x85\x8a";
1910 } elseif ( $code < 0xd0c0 ) {
1911 return "\xe3\x85\x8b";
1912 } elseif ( $code < 0xd30c ) {
1913 return "\xe3\x85\x8c";
1914 } elseif ( $code < 0xd558 ) {
1915 return "\xe3\x85\x8d";
1917 return "\xe3\x85\x8e";
1924 function initEncoding() {
1925 # Some languages may have an alternate char encoding option
1926 # (Esperanto X-coding, Japanese furigana conversion, etc)
1927 # If this language is used as the primary content language,
1928 # an override to the defaults can be set here on startup.
1931 function recodeForEdit( $s ) {
1932 # For some languages we'll want to explicitly specify
1933 # which characters make it into the edit box raw
1934 # or are converted in some way or another.
1935 # Note that if wgOutputEncoding is different from
1936 # wgInputEncoding, this text will be further converted
1937 # to wgOutputEncoding.
1938 global $wgEditEncoding;
1939 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1942 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1946 function recodeInput( $s ) {
1947 # Take the previous into account.
1948 global $wgEditEncoding;
1949 if ( $wgEditEncoding != '' ) {
1950 $enc = $wgEditEncoding;
1954 if ( $enc == 'UTF-8' ) {
1957 return $this->iconv( $enc, 'UTF-8', $s );
1962 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1963 * also cleans up certain backwards-compatible sequences, converting them
1964 * to the modern Unicode equivalent.
1966 * This is language-specific for performance reasons only.
1968 function normalize( $s ) {
1969 global $wgAllUnicodeFixes;
1970 $s = UtfNormal
::cleanUp( $s );
1971 if ( $wgAllUnicodeFixes ) {
1972 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1973 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1980 * Transform a string using serialized data stored in the given file (which
1981 * must be in the serialized subdirectory of $IP). The file contains pairs
1982 * mapping source characters to destination characters.
1984 * The data is cached in process memory. This will go faster if you have the
1985 * FastStringSearch extension.
1987 function transformUsingPairFile( $file, $string ) {
1988 if ( !isset( $this->transformData
[$file] ) ) {
1989 $data = wfGetPrecompiledData( $file );
1990 if ( $data === false ) {
1991 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1993 $this->transformData
[$file] = new ReplacementArray( $data );
1995 return $this->transformData
[$file]->replace( $string );
1999 * For right-to-left language support
2004 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2008 * Return the correct HTML 'dir' attribute value for this language.
2012 return $this->isRTL() ?
'rtl' : 'ltr';
2016 * Return 'left' or 'right' as appropriate alignment for line-start
2017 * for this language's text direction.
2019 * Should be equivalent to CSS3 'start' text-align value....
2023 function alignStart() {
2024 return $this->isRTL() ?
'right' : 'left';
2028 * Return 'right' or 'left' as appropriate alignment for line-end
2029 * for this language's text direction.
2031 * Should be equivalent to CSS3 'end' text-align value....
2035 function alignEnd() {
2036 return $this->isRTL() ?
'left' : 'right';
2040 * A hidden direction mark (LRM or RLM), depending on the language direction
2044 function getDirMark() {
2045 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2048 function capitalizeAllNouns() {
2049 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2053 * An arrow, depending on the language direction
2057 function getArrow() {
2058 return $this->isRTL() ?
'←' : '→';
2062 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2066 function linkPrefixExtension() {
2067 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2070 function getMagicWords() {
2071 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2074 # Fill a MagicWord object with data from here
2075 function getMagic( $mw ) {
2076 if ( !$this->mMagicHookDone
) {
2077 $this->mMagicHookDone
= true;
2078 wfProfileIn( 'LanguageGetMagic' );
2079 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2080 wfProfileOut( 'LanguageGetMagic' );
2082 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2083 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2085 $magicWords = $this->getMagicWords();
2086 if ( isset( $magicWords[$mw->mId
] ) ) {
2087 $rawEntry = $magicWords[$mw->mId
];
2093 if ( !is_array( $rawEntry ) ) {
2094 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2096 $mw->mCaseSensitive
= $rawEntry[0];
2097 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2102 * Add magic words to the extension array
2104 function addMagicWordsByLang( $newWords ) {
2105 $code = $this->getCode();
2106 $fallbackChain = array();
2107 while ( $code && !in_array( $code, $fallbackChain ) ) {
2108 $fallbackChain[] = $code;
2109 $code = self
::getFallbackFor( $code );
2111 if ( !in_array( 'en', $fallbackChain ) ) {
2112 $fallbackChain[] = 'en';
2114 $fallbackChain = array_reverse( $fallbackChain );
2115 foreach ( $fallbackChain as $code ) {
2116 if ( isset( $newWords[$code] ) ) {
2117 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2123 * Get special page names, as an associative array
2124 * case folded alias => real name
2126 function getSpecialPageAliases() {
2127 // Cache aliases because it may be slow to load them
2128 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2130 $this->mExtendedSpecialPageAliases
=
2131 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2132 wfRunHooks( 'LanguageGetSpecialPageAliases',
2133 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2136 return $this->mExtendedSpecialPageAliases
;
2140 * Italic is unsuitable for some languages
2142 * @param $text String: the text to be emphasized.
2145 function emphasize( $text ) {
2146 return "<em>$text</em>";
2150 * Normally we output all numbers in plain en_US style, that is
2151 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2152 * point twohundredthirtyfive. However this is not sutable for all
2153 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2154 * Icelandic just want to use commas instead of dots, and dots instead
2155 * of commas like "293.291,235".
2157 * An example of this function being called:
2159 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2162 * See LanguageGu.php for the Gujarati implementation and
2163 * $separatorTransformTable on MessageIs.php for
2164 * the , => . and . => , implementation.
2166 * @todo check if it's viable to use localeconv() for the decimal
2168 * @param $number Mixed: the string to be formatted, should be an integer
2169 * or a floating point number.
2170 * @param $nocommafy Bool: set to true for special numbers like dates
2173 function formatNum( $number, $nocommafy = false ) {
2174 global $wgTranslateNumerals;
2175 if ( !$nocommafy ) {
2176 $number = $this->commafy( $number );
2177 $s = $this->separatorTransformTable();
2179 $number = strtr( $number, $s );
2183 if ( $wgTranslateNumerals ) {
2184 $s = $this->digitTransformTable();
2186 $number = strtr( $number, $s );
2193 function parseFormattedNumber( $number ) {
2194 $s = $this->digitTransformTable();
2196 $number = strtr( $number, array_flip( $s ) );
2199 $s = $this->separatorTransformTable();
2201 $number = strtr( $number, array_flip( $s ) );
2204 $number = strtr( $number, array( ',' => '' ) );
2209 * Adds commas to a given number
2214 function commafy( $_ ) {
2215 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2218 function digitTransformTable() {
2219 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2222 function separatorTransformTable() {
2223 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2227 * Take a list of strings and build a locale-friendly comma-separated
2228 * list, using the local comma-separator message.
2229 * The last two strings are chained with an "and".
2234 function listToText( $l ) {
2236 $m = count( $l ) - 1;
2238 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2240 for ( $i = $m; $i >= 0; $i-- ) {
2243 } else if ( $i == $m - 1 ) {
2244 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2246 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2254 * Take a list of strings and build a locale-friendly comma-separated
2255 * list, using the local comma-separator message.
2256 * @param $list array of strings to put in a comma list
2259 function commaList( $list ) {
2264 array( 'parsemag', 'escapenoentities', 'language' => $this )
2270 * Take a list of strings and build a locale-friendly semicolon-separated
2271 * list, using the local semicolon-separator message.
2272 * @param $list array of strings to put in a semicolon list
2275 function semicolonList( $list ) {
2279 'semicolon-separator',
2280 array( 'parsemag', 'escapenoentities', 'language' => $this )
2286 * Same as commaList, but separate it with the pipe instead.
2287 * @param $list array of strings to put in a pipe list
2290 function pipeList( $list ) {
2295 array( 'escapenoentities', 'language' => $this )
2301 * Truncate a string to a specified length in bytes, appending an optional
2302 * string (e.g. for ellipses)
2304 * The database offers limited byte lengths for some columns in the database;
2305 * multi-byte character sets mean we need to ensure that only whole characters
2306 * are included, otherwise broken characters can be passed to the user
2308 * If $length is negative, the string will be truncated from the beginning
2310 * @param $string String to truncate
2311 * @param $length Int: maximum length (excluding ellipses)
2312 * @param $ellipsis String to append to the truncated text
2315 function truncate( $string, $length, $ellipsis = '...' ) {
2316 # Use the localized ellipsis character
2317 if ( $ellipsis == '...' ) {
2318 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2320 # Check if there is no need to truncate
2321 if ( $length == 0 ) {
2323 } elseif ( strlen( $string ) <= abs( $length ) ) {
2326 $stringOriginal = $string;
2327 if ( $length > 0 ) {
2328 $string = substr( $string, 0, $length ); // xyz...
2329 $string = $this->removeBadCharLast( $string );
2330 $string = $string . $ellipsis;
2332 $string = substr( $string, $length ); // ...xyz
2333 $string = $this->removeBadCharFirst( $string );
2334 $string = $ellipsis . $string;
2336 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2337 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2340 return $stringOriginal;
2345 * Remove bytes that represent an incomplete Unicode character
2346 * at the end of string (e.g. bytes of the char are missing)
2348 * @param $string String
2351 protected function removeBadCharLast( $string ) {
2352 $char = ord( $string[strlen( $string ) - 1] );
2354 if ( $char >= 0xc0 ) {
2355 # We got the first byte only of a multibyte char; remove it.
2356 $string = substr( $string, 0, -1 );
2357 } elseif ( $char >= 0x80 &&
2358 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2359 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2361 # We chopped in the middle of a character; remove it
2368 * Remove bytes that represent an incomplete Unicode character
2369 * at the start of string (e.g. bytes of the char are missing)
2371 * @param $string String
2374 protected function removeBadCharFirst( $string ) {
2375 $char = ord( $string[0] );
2376 if ( $char >= 0x80 && $char < 0xc0 ) {
2377 # We chopped in the middle of a character; remove the whole thing
2378 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2384 * Truncate a string of valid HTML to a specified length in bytes,
2385 * appending an optional string (e.g. for ellipses), and return valid HTML
2387 * This is only intended for styled/linked text, such as HTML with
2388 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2390 * Note: tries to fix broken HTML with MWTidy
2392 * @param string $text HTML string to truncate
2393 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2394 * @param string $ellipsis String to append to the truncated text
2397 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2398 # Use the localized ellipsis character
2399 if ( $ellipsis == '...' ) {
2400 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2402 # Check if there is no need to truncate
2403 if ( $length <= 0 ) {
2404 return $ellipsis; // no text shown, nothing to format
2405 } elseif ( strlen( $text ) <= $length ) {
2406 return $text; // string short enough even *with* HTML
2408 $text = MWTidy
::tidy( $text ); // fix tags
2409 $displayLen = 0; // innerHTML legth so far
2410 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2411 $tagType = 0; // 0-open, 1-close
2412 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2413 $entityState = 0; // 0-not entity, 1-entity
2415 $openTags = array(); // open tag stack
2416 $textLen = strlen( $text );
2417 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2419 $lastCh = $pos ?
$text[$pos - 1] : '';
2420 $ret .= $ch; // add to result string
2422 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2423 $entityState = 0; // for bad HTML
2424 $bracketState = 1; // tag started (checking for backslash)
2425 } elseif ( $ch == '>' ) {
2426 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2427 $entityState = 0; // for bad HTML
2428 $bracketState = 0; // out of brackets
2429 } elseif ( $bracketState == 1 ) {
2431 $tagType = 1; // close tag (e.g. "</span>")
2433 $tagType = 0; // open tag (e.g. "<span>")
2436 $bracketState = 2; // building tag name
2437 } elseif ( $bracketState == 2 ) {
2441 // Name found (e.g. "<a href=..."), add on tag attributes...
2442 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2444 } elseif ( $bracketState == 0 ) {
2445 if ( $entityState ) {
2448 $displayLen++
; // entity is one displayed char
2452 $entityState = 1; // entity found, (e.g. " ")
2454 $displayLen++
; // this char is displayed
2455 // Add on the other display text after this...
2456 $skipped = $this->truncate_skip(
2457 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2458 $displayLen +
= $skipped;
2463 # Consider truncation once the display length has reached the maximim.
2464 # Double-check that we're not in the middle of a bracket/entity...
2465 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2466 if ( !$testingEllipsis ) {
2467 $testingEllipsis = true;
2468 # Save where we are; we will truncate here unless
2469 # the ellipsis actually makes the string longer.
2470 $pOpenTags = $openTags; // save state
2471 $pRet = $ret; // save state
2472 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2473 # Ellipsis won't make string longer/equal, the truncation point was OK.
2474 $openTags = $pOpenTags; // reload state
2475 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2476 $ret .= $ellipsis; // add ellipsis
2481 if ( $displayLen == 0 ) {
2482 return ''; // no text shown, nothing to format
2484 // Close the last tag if left unclosed by bad HTML
2485 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2486 while ( count( $openTags ) > 0 ) {
2487 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2492 // truncateHtml() helper function
2493 // like strcspn() but adds the skipped chars to $ret
2494 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2496 if ( $start < strlen( $text ) ) {
2497 $skipCount = strcspn( $text, $search, $start, $len );
2498 $ret .= substr( $text, $start, $skipCount );
2504 * truncateHtml() helper function
2505 * (a) push or pop $tag from $openTags as needed
2506 * (b) clear $tag value
2507 * @param String &$tag Current HTML tag name we are looking at
2508 * @param int $tagType (0-open tag, 1-close tag)
2509 * @param char $lastCh Character before the '>' that ended this tag
2510 * @param array &$openTags Open tag stack (not accounting for $tag)
2512 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2513 $tag = ltrim( $tag );
2515 if ( $tagType == 0 && $lastCh != '/' ) {
2516 $openTags[] = $tag; // tag opened (didn't close itself)
2517 } else if ( $tagType == 1 ) {
2518 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2519 array_pop( $openTags ); // tag closed
2527 * Grammatical transformations, needed for inflected languages
2528 * Invoked by putting {{grammar:case|word}} in a message
2530 * @param $word string
2531 * @param $case string
2534 function convertGrammar( $word, $case ) {
2535 global $wgGrammarForms;
2536 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2537 return $wgGrammarForms[$this->getCode()][$case][$word];
2543 * Provides an alternative text depending on specified gender.
2544 * Usage {{gender:username|masculine|feminine|neutral}}.
2545 * username is optional, in which case the gender of current user is used,
2546 * but only in (some) interface messages; otherwise default gender is used.
2547 * If second or third parameter are not specified, masculine is used.
2548 * These details may be overriden per language.
2550 function gender( $gender, $forms ) {
2551 if ( !count( $forms ) ) {
2554 $forms = $this->preConvertPlural( $forms, 2 );
2555 if ( $gender === 'male' ) {
2558 if ( $gender === 'female' ) {
2561 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2565 * Plural form transformations, needed for some languages.
2566 * For example, there are 3 form of plural in Russian and Polish,
2567 * depending on "count mod 10". See [[w:Plural]]
2568 * For English it is pretty simple.
2570 * Invoked by putting {{plural:count|wordform1|wordform2}}
2571 * or {{plural:count|wordform1|wordform2|wordform3}}
2573 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2575 * @param $count Integer: non-localized number
2576 * @param $forms Array: different plural forms
2577 * @return string Correct form of plural for $count in this language
2579 function convertPlural( $count, $forms ) {
2580 if ( !count( $forms ) ) {
2583 $forms = $this->preConvertPlural( $forms, 2 );
2585 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2589 * Checks that convertPlural was given an array and pads it to requested
2590 * amound of forms by copying the last one.
2592 * @param $count Integer: How many forms should there be at least
2593 * @param $forms Array of forms given to convertPlural
2594 * @return array Padded array of forms or an exception if not an array
2596 protected function preConvertPlural( /* Array */ $forms, $count ) {
2597 while ( count( $forms ) < $count ) {
2598 $forms[] = $forms[count( $forms ) - 1];
2604 * For translating of expiry times
2605 * @param $str String: the validated block time in English
2606 * @return Somehow translated block time
2607 * @see LanguageFi.php for example implementation
2609 function translateBlockExpiry( $str ) {
2610 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2612 if ( $scBlockExpiryOptions == '-' ) {
2616 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2617 if ( strpos( $option, ':' ) === false ) {
2620 list( $show, $value ) = explode( ':', $option );
2621 if ( strcmp( $str, $value ) == 0 ) {
2622 return htmlspecialchars( trim( $show ) );
2630 * languages like Chinese need to be segmented in order for the diff
2633 * @param $text String
2636 function segmentForDiff( $text ) {
2641 * and unsegment to show the result
2643 * @param $text String
2646 function unsegmentForDiff( $text ) {
2650 # convert text to all supported variants
2651 function autoConvertToAllVariants( $text ) {
2652 return $this->mConverter
->autoConvertToAllVariants( $text );
2655 # convert text to different variants of a language.
2656 function convert( $text ) {
2657 return $this->mConverter
->convert( $text );
2660 # Convert a Title object to a string in the preferred variant
2661 function convertTitle( $title ) {
2662 return $this->mConverter
->convertTitle( $title );
2665 # Check if this is a language with variants
2666 function hasVariants() {
2667 return sizeof( $this->getVariants() ) > 1;
2670 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2671 function armourMath( $text ) {
2672 return $this->mConverter
->armourMath( $text );
2676 * Perform output conversion on a string, and encode for safe HTML output.
2677 * @param $text String text to be converted
2678 * @param $isTitle Bool whether this conversion is for the article title
2680 * @todo this should get integrated somewhere sane
2682 function convertHtml( $text, $isTitle = false ) {
2683 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2686 function convertCategoryKey( $key ) {
2687 return $this->mConverter
->convertCategoryKey( $key );
2691 * Get the list of variants supported by this language
2692 * see sample implementation in LanguageZh.php
2694 * @return array an array of language codes
2696 function getVariants() {
2697 return $this->mConverter
->getVariants();
2700 function getPreferredVariant() {
2701 return $this->mConverter
->getPreferredVariant();
2704 function getDefaultVariant() {
2705 return $this->mConverter
->getDefaultVariant();
2708 function getURLVariant() {
2709 return $this->mConverter
->getURLVariant();
2713 * If a language supports multiple variants, it is
2714 * possible that non-existing link in one variant
2715 * actually exists in another variant. this function
2716 * tries to find it. See e.g. LanguageZh.php
2718 * @param $link String: the name of the link
2719 * @param $nt Mixed: the title object of the link
2720 * @param $ignoreOtherCond Boolean: to disable other conditions when
2721 * we need to transclude a template or update a category's link
2722 * @return null the input parameters may be modified upon return
2724 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2725 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2729 * If a language supports multiple variants, converts text
2730 * into an array of all possible variants of the text:
2731 * 'variant' => text in that variant
2733 * @deprecated Use autoConvertToAllVariants()
2735 function convertLinkToAllVariants( $text ) {
2736 return $this->mConverter
->convertLinkToAllVariants( $text );
2740 * returns language specific options used by User::getPageRenderHash()
2741 * for example, the preferred language variant
2745 function getExtraHashOptions() {
2746 return $this->mConverter
->getExtraHashOptions();
2750 * For languages that support multiple variants, the title of an
2751 * article may be displayed differently in different variants. this
2752 * function returns the apporiate title defined in the body of the article.
2756 function getParsedTitle() {
2757 return $this->mConverter
->getParsedTitle();
2761 * Enclose a string with the "no conversion" tag. This is used by
2762 * various functions in the Parser
2764 * @param $text String: text to be tagged for no conversion
2766 * @return string the tagged text
2768 function markNoConversion( $text, $noParse = false ) {
2769 return $this->mConverter
->markNoConversion( $text, $noParse );
2773 * A regular expression to match legal word-trailing characters
2774 * which should be merged onto a link of the form [[foo]]bar.
2778 function linkTrail() {
2779 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2782 function getLangObj() {
2787 * Get the RFC 3066 code for this language object
2789 function getCode() {
2790 return $this->mCode
;
2794 * Get langcode for message
2795 * Some language, like Chinese (zh, without any suffix), has multiple
2796 * interface languages, we could choose a better one for user.
2797 * Inherit class can override this function if necessary.
2801 function getCodeForMessage() {
2802 return $this->getPreferredVariant();
2805 function setCode( $code ) {
2806 $this->mCode
= $code;
2810 * Get the name of a file for a certain language code
2811 * @param $prefix string Prepend this to the filename
2812 * @param $code string Language code
2813 * @param $suffix string Append this to the filename
2814 * @return string $prefix . $mangledCode . $suffix
2816 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2817 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2821 * Get the language code from a file name. Inverse of getFileName()
2822 * @param $filename string $prefix . $languageCode . $suffix
2823 * @param $prefix string Prefix before the language code
2824 * @param $suffix string Suffix after the language code
2825 * @return Language code, or false if $prefix or $suffix isn't found
2827 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2829 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2830 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2831 if ( !count( $m ) ) {
2834 return str_replace( '_', '-', strtolower( $m[1] ) );
2837 static function getMessagesFileName( $code ) {
2839 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2842 static function getClassFileName( $code ) {
2844 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2848 * Get the fallback for a given language
2850 static function getFallbackFor( $code ) {
2851 if ( $code === 'en' ) {
2855 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2860 * Get all messages for a given language
2861 * WARNING: this may take a long time
2863 static function getMessagesFor( $code ) {
2864 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2868 * Get a message for a given language
2870 static function getMessageFor( $key, $code ) {
2871 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2874 function fixVariableInNamespace( $talk ) {
2875 if ( strpos( $talk, '$1' ) === false ) {
2879 global $wgMetaNamespace;
2880 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2882 # Allow grammar transformations
2883 # Allowing full message-style parsing would make simple requests
2884 # such as action=raw much more expensive than they need to be.
2885 # This will hopefully cover most cases.
2886 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2887 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2888 return str_replace( ' ', '_', $talk );
2891 function replaceGrammarInNamespace( $m ) {
2892 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2895 static function getCaseMaps() {
2896 static $wikiUpperChars, $wikiLowerChars;
2897 if ( isset( $wikiUpperChars ) ) {
2898 return array( $wikiUpperChars, $wikiLowerChars );
2901 wfProfileIn( __METHOD__
);
2902 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2903 if ( $arr === false ) {
2904 throw new MWException(
2905 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2907 $wikiUpperChars = $arr['wikiUpperChars'];
2908 $wikiLowerChars = $arr['wikiLowerChars'];
2909 wfProfileOut( __METHOD__
);
2910 return array( $wikiUpperChars, $wikiLowerChars );
2913 function formatTimePeriod( $seconds ) {
2914 if ( round( $seconds * 10 ) < 100 ) {
2915 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2916 } elseif ( round( $seconds ) < 60 ) {
2917 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2918 } elseif ( round( $seconds ) < 3600 ) {
2919 $minutes = floor( $seconds / 60 );
2920 $secondsPart = round( fmod( $seconds, 60 ) );
2921 if ( $secondsPart == 60 ) {
2925 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2926 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2928 $hours = floor( $seconds / 3600 );
2929 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2930 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2931 if ( $secondsPart == 60 ) {
2935 if ( $minutes == 60 ) {
2939 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2940 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2941 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2945 function formatBitrate( $bps ) {
2946 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2948 return $this->formatNum( $bps ) . $units[0];
2950 $unitIndex = floor( log10( $bps ) / 3 );
2951 $mantissa = $bps / pow( 1000, $unitIndex );
2952 if ( $mantissa < 10 ) {
2953 $mantissa = round( $mantissa, 1 );
2955 $mantissa = round( $mantissa );
2957 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2961 * Format a size in bytes for output, using an appropriate
2962 * unit (B, KB, MB or GB) according to the magnitude in question
2964 * @param $size Size to format
2965 * @return string Plain text (not HTML)
2967 function formatSize( $size ) {
2968 // For small sizes no decimal places necessary
2970 if ( $size > 1024 ) {
2971 $size = $size / 1024;
2972 if ( $size > 1024 ) {
2973 $size = $size / 1024;
2974 // For MB and bigger two decimal places are smarter
2976 if ( $size > 1024 ) {
2977 $size = $size / 1024;
2978 $msg = 'size-gigabytes';
2980 $msg = 'size-megabytes';
2983 $msg = 'size-kilobytes';
2986 $msg = 'size-bytes';
2988 $size = round( $size, $round );
2989 $text = $this->getMessageFromDB( $msg );
2990 return str_replace( '$1', $this->formatNum( $size ), $text );
2994 * Get the conversion rule title, if any.
2996 function getConvRuleTitle() {
2997 return $this->mConverter
->getConvRuleTitle();
3001 * Given a string, convert it to a (hopefully short) key that can be used
3002 * for efficient sorting. A binary sort according to the sortkeys
3003 * corresponds to a logical sort of the corresponding strings. Current
3004 * code expects that a null character should sort before all others, but
3005 * has no other particular expectations (and that one can be changed if
3008 * @param string $string UTF-8 string
3009 * @return string Binary sortkey
3011 public function convertToSortkey( $string ) {
3012 # Fake function for now
3013 return strtoupper( $string );
3017 * Given a string, return the logical "first letter" to be used for
3018 * grouping on category pages and so on. This has to be coordinated
3019 * carefully with convertToSortkey(), or else the sorted list might jump
3020 * back and forth between the same "initial letters" or other pathological
3021 * behavior. For instance, if you just return the first character, but "a"
3022 * sorts the same as "A" based on convertToSortkey(), then you might get a
3034 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
3036 * @param string $string UTF-8 string
3037 * @return string UTF-8 string corresponding to the first letter of input
3039 public function firstLetterForLists( $string ) {
3040 if ( $string[0] == "\0" ) {
3041 $string = substr( $string, 1 );
3043 return strtoupper( $this->firstChar( $string ) );