3 * @defgroup Language Language
9 if( !defined( 'MEDIAWIKI' ) ) {
10 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 global $wgLanguageNames;
16 require_once( dirname(__FILE__
) . '/Names.php' ) ;
18 global $wgInputEncoding, $wgOutputEncoding;
21 * These are always UTF-8, they exist only for backwards compatibility
23 $wgInputEncoding = "UTF-8";
24 $wgOutputEncoding = "UTF-8";
26 if( function_exists( 'mb_strtoupper' ) ) {
27 mb_internal_encoding('UTF-8');
31 * a fake language converter
37 function FakeConverter($langobj) {$this->mLang
= $langobj;}
38 function autoConvertToAllVariants($text) {return $text;}
39 function convert($t, $i) {return $t;}
40 function parserConvert($t, $p) {return $t;}
41 function getVariants() { return array( $this->mLang
->getCode() ); }
42 function getPreferredVariant() {return $this->mLang
->getCode(); }
43 function findVariantLink(&$l, &$n, $ignoreOtherCond = false) {}
44 function getExtraHashOptions() {return '';}
45 function getParsedTitle() {return '';}
46 function markNoConversion($text, $noParse=false) {return $text;}
47 function convertCategoryKey( $key ) {return $key; }
48 function convertLinkToAllVariants($text){ return array( $this->mLang
->getCode() => $text); }
49 function armourMath($text){ return $text; }
53 * Internationalisation code
57 var $mConverter, $mVariants, $mCode, $mLoaded = false;
58 var $mMagicExtensions = array(), $mMagicHookDone = false;
60 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
61 var $dateFormatStrings = array();
63 var $mExtendedSpecialPageAliases;
66 * ReplacementArray object caches
68 var $transformData = array();
70 static public $dataCache;
71 static public $mLangObjCache = array();
73 static public $mWeekdayMsgs = array(
74 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
78 static public $mWeekdayAbbrevMsgs = array(
79 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
82 static public $mMonthMsgs = array(
83 'january', 'february', 'march', 'april', 'may_long', 'june',
84 'july', 'august', 'september', 'october', 'november',
87 static public $mMonthGenMsgs = array(
88 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
89 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
92 static public $mMonthAbbrevMsgs = array(
93 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
94 'sep', 'oct', 'nov', 'dec'
97 static public $mIranianCalendarMonthMsgs = array(
98 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
99 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
100 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
101 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
104 static public $mHebrewCalendarMonthMsgs = array(
105 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
106 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
107 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
108 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
109 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
112 static public $mHebrewCalendarMonthGenMsgs = array(
113 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
114 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
115 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
116 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
117 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
120 static public $mHijriCalendarMonthMsgs = array(
121 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
122 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
123 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
124 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
128 * Get a cached language object for a given language code
130 static function factory( $code ) {
131 if ( !isset( self
::$mLangObjCache[$code] ) ) {
132 if( count( self
::$mLangObjCache ) > 10 ) {
133 // Don't keep a billion objects around, that's stupid.
134 self
::$mLangObjCache = array();
136 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
138 return self
::$mLangObjCache[$code];
142 * Create a language object for a given language code
144 protected static function newFromCode( $code ) {
146 static $recursionLevel = 0;
147 if ( $code == 'en' ) {
150 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
151 // Preload base classes to work around APC/PHP5 bug
152 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
153 include_once("$IP/languages/classes/$class.deps.php");
155 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
156 include_once("$IP/languages/classes/$class.php");
160 if ( $recursionLevel > 5 ) {
161 throw new MWException( "Language fallback loop detected when creating class $class\n" );
164 if( ! class_exists( $class ) ) {
165 $fallback = Language
::getFallbackFor( $code );
167 $lang = Language
::newFromCode( $fallback );
169 $lang->setCode( $code );
177 * Get the LocalisationCache instance
179 public static function getLocalisationCache() {
180 if ( is_null( self
::$dataCache ) ) {
181 global $wgLocalisationCacheConf;
182 $class = $wgLocalisationCacheConf['class'];
183 self
::$dataCache = new $class( $wgLocalisationCacheConf );
185 return self
::$dataCache;
188 function __construct() {
189 $this->mConverter
= new FakeConverter($this);
190 // Set the code to the name of the descendant
191 if ( get_class( $this ) == 'Language' ) {
194 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
196 self
::getLocalisationCache();
200 * Reduce memory usage
202 function __destruct() {
203 foreach ( $this as $name => $value ) {
204 unset( $this->$name );
209 * Hook which will be called if this is the content language.
210 * Descendants can use this to register hook functions or modify globals
212 function initContLang() {}
215 * @deprecated Use User::getDefaultOptions()
218 function getDefaultUserOptions() {
219 wfDeprecated( __METHOD__
);
220 return User
::getDefaultOptions();
223 function getFallbackLanguageCode() {
224 if ( $this->mCode
=== 'en' ) {
227 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
232 * Exports $wgBookstoreListEn
235 function getBookstoreList() {
236 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
242 function getNamespaces() {
243 if ( is_null( $this->namespaceNames
) ) {
244 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk;
246 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
247 if ( $wgExtraNamespaces ) {
248 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames
;
251 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
252 if ( $wgMetaNamespaceTalk ) {
253 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
255 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
256 $this->namespaceNames
[NS_PROJECT_TALK
] =
257 $this->fixVariableInNamespace( $talk );
260 # The above mixing may leave namespaces out of canonical order.
261 # Re-order by namespace ID number...
262 ksort( $this->namespaceNames
);
264 return $this->namespaceNames
;
268 * A convenience function that returns the same thing as
269 * getNamespaces() except with the array values changed to ' '
270 * where it found '_', useful for producing output to be displayed
271 * e.g. in <select> forms.
275 function getFormattedNamespaces() {
276 $ns = $this->getNamespaces();
277 foreach($ns as $k => $v) {
278 $ns[$k] = strtr($v, '_', ' ');
284 * Get a namespace value by key
286 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
287 * echo $mw_ns; // prints 'MediaWiki'
290 * @param $index Int: the array key of the namespace to return
291 * @return mixed, string if the namespace value exists, otherwise false
293 function getNsText( $index ) {
294 $ns = $this->getNamespaces();
295 return isset( $ns[$index] ) ?
$ns[$index] : false;
299 * A convenience function that returns the same thing as
300 * getNsText() except with '_' changed to ' ', useful for
305 function getFormattedNsText( $index ) {
306 $ns = $this->getNsText( $index );
307 return strtr($ns, '_', ' ');
311 * Get a namespace key by value, case insensitive.
312 * Only matches namespace names for the current language, not the
313 * canonical ones defined in Namespace.php.
315 * @param $text String
316 * @return mixed An integer if $text is a valid value otherwise false
318 function getLocalNsIndex( $text ) {
319 $lctext = $this->lc($text);
320 $ids = $this->getNamespaceIds();
321 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
324 function getNamespaceAliases() {
325 if ( is_null( $this->namespaceAliases
) ) {
326 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
330 foreach ( $aliases as $name => $index ) {
331 if ( $index === NS_PROJECT_TALK
) {
332 unset( $aliases[$name] );
333 $name = $this->fixVariableInNamespace( $name );
334 $aliases[$name] = $index;
338 $this->namespaceAliases
= $aliases;
340 return $this->namespaceAliases
;
343 function getNamespaceIds() {
344 if ( is_null( $this->mNamespaceIds
) ) {
345 global $wgNamespaceAliases;
346 # Put namespace names and aliases into a hashtable.
347 # If this is too slow, then we should arrange it so that it is done
348 # before caching. The catch is that at pre-cache time, the above
349 # class-specific fixup hasn't been done.
350 $this->mNamespaceIds
= array();
351 foreach ( $this->getNamespaces() as $index => $name ) {
352 $this->mNamespaceIds
[$this->lc($name)] = $index;
354 foreach ( $this->getNamespaceAliases() as $name => $index ) {
355 $this->mNamespaceIds
[$this->lc($name)] = $index;
357 if ( $wgNamespaceAliases ) {
358 foreach ( $wgNamespaceAliases as $name => $index ) {
359 $this->mNamespaceIds
[$this->lc($name)] = $index;
363 return $this->mNamespaceIds
;
368 * Get a namespace key by value, case insensitive. Canonical namespace
369 * names override custom ones defined for the current language.
371 * @param $text String
372 * @return mixed An integer if $text is a valid value otherwise false
374 function getNsIndex( $text ) {
375 $lctext = $this->lc($text);
376 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
379 $ids = $this->getNamespaceIds();
380 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
384 * short names for language variants used for language conversion links.
386 * @param $code String
389 function getVariantname( $code ) {
390 return $this->getMessageFromDB( "variantname-$code" );
393 function specialPage( $name ) {
394 $aliases = $this->getSpecialPageAliases();
395 if ( isset( $aliases[$name][0] ) ) {
396 $name = $aliases[$name][0];
398 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
401 function getQuickbarSettings() {
403 $this->getMessage( 'qbsettings-none' ),
404 $this->getMessage( 'qbsettings-fixedleft' ),
405 $this->getMessage( 'qbsettings-fixedright' ),
406 $this->getMessage( 'qbsettings-floatingleft' ),
407 $this->getMessage( 'qbsettings-floatingright' )
411 function getMathNames() {
412 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
415 function getDatePreferences() {
416 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
419 function getDateFormats() {
420 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
423 function getDefaultDateFormat() {
424 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
425 if ( $df === 'dmy or mdy' ) {
426 global $wgAmericanDates;
427 return $wgAmericanDates ?
'mdy' : 'dmy';
433 function getDatePreferenceMigrationMap() {
434 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
437 function getImageFile( $image ) {
438 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
441 function getDefaultUserOptionOverrides() {
442 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
445 function getExtraUserToggles() {
446 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
449 function getUserToggle( $tog ) {
450 return $this->getMessageFromDB( "tog-$tog" );
454 * Get language names, indexed by code.
455 * If $customisedOnly is true, only returns codes with a messages file
457 public static function getLanguageNames( $customisedOnly = false ) {
458 global $wgLanguageNames, $wgExtraLanguageNames;
459 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
460 if ( !$customisedOnly ) {
466 $dir = opendir( "$IP/languages/messages" );
467 while( false !== ( $file = readdir( $dir ) ) ) {
469 if( preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $file, $m ) ) {
470 $code = str_replace( '_', '-', strtolower( $m[1] ) );
471 if ( isset( $allNames[$code] ) ) {
472 $names[$code] = $allNames[$code];
481 * Get a message from the MediaWiki namespace.
483 * @param $msg String: message name
486 function getMessageFromDB( $msg ) {
487 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
490 function getLanguageName( $code ) {
491 $names = self
::getLanguageNames();
492 if ( !array_key_exists( $code, $names ) ) {
495 return $names[$code];
498 function getMonthName( $key ) {
499 return $this->getMessageFromDB( self
::$mMonthMsgs[$key-1] );
502 function getMonthNameGen( $key ) {
503 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key-1] );
506 function getMonthAbbreviation( $key ) {
507 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key-1] );
510 function getWeekdayName( $key ) {
511 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key-1] );
514 function getWeekdayAbbreviation( $key ) {
515 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key-1] );
518 function getIranianCalendarMonthName( $key ) {
519 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key-1] );
522 function getHebrewCalendarMonthName( $key ) {
523 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key-1] );
526 function getHebrewCalendarMonthNameGen( $key ) {
527 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key-1] );
530 function getHijriCalendarMonthName( $key ) {
531 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key-1] );
535 * Used by date() and time() to adjust the time output.
537 * @param $ts Int the time in date('YmdHis') format
538 * @param $tz Mixed: adjust the time by this amount (default false, mean we
539 * get user timecorrection setting)
542 function userAdjust( $ts, $tz = false ) {
543 global $wgUser, $wgLocalTZoffset;
545 if ( $tz === false ) {
546 $tz = $wgUser->getOption( 'timecorrection' );
549 $data = explode( '|', $tz, 3 );
551 if ( $data[0] == 'ZoneInfo' ) {
552 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
553 $date = date_create( $ts, timezone_open( 'UTC' ) );
554 date_timezone_set( $date, timezone_open( $data[2] ) );
555 $date = date_format( $date, 'YmdHis' );
558 # Unrecognized timezone, default to 'Offset' with the stored offset.
563 if ( $data[0] == 'System' ||
$tz == '' ) {
564 # Global offset in minutes.
565 if( isset($wgLocalTZoffset) ) $minDiff = $wgLocalTZoffset;
566 } else if ( $data[0] == 'Offset' ) {
567 $minDiff = intval( $data[1] );
569 $data = explode( ':', $tz );
570 if( count( $data ) == 2 ) {
571 $data[0] = intval( $data[0] );
572 $data[1] = intval( $data[1] );
573 $minDiff = abs( $data[0] ) * 60 +
$data[1];
574 if ( $data[0] < 0 ) $minDiff = -$minDiff;
576 $minDiff = intval( $data[0] ) * 60;
580 # No difference ? Return time unchanged
581 if ( 0 == $minDiff ) return $ts;
583 wfSuppressWarnings(); // E_STRICT system time bitching
584 # Generate an adjusted date; take advantage of the fact that mktime
585 # will normalize out-of-range values so we don't have to split $minDiff
586 # into hours and minutes.
588 (int)substr( $ts, 8, 2) ), # Hours
589 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
590 (int)substr( $ts, 12, 2 ), # Seconds
591 (int)substr( $ts, 4, 2 ), # Month
592 (int)substr( $ts, 6, 2 ), # Day
593 (int)substr( $ts, 0, 4 ) ); #Year
595 $date = date( 'YmdHis', $t );
602 * This is a workalike of PHP's date() function, but with better
603 * internationalisation, a reduced set of format characters, and a better
606 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
607 * PHP manual for definitions. "o" format character is supported since
608 * PHP 5.1.0, previous versions return literal o.
609 * There are a number of extensions, which start with "x":
611 * xn Do not translate digits of the next numeric format character
612 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
613 * xr Use roman numerals for the next numeric format character
614 * xh Use hebrew numerals for the next numeric format character
616 * xg Genitive month name
618 * xij j (day number) in Iranian calendar
619 * xiF F (month name) in Iranian calendar
620 * xin n (month number) in Iranian calendar
621 * xiY Y (full year) in Iranian calendar
623 * xjj j (day number) in Hebrew calendar
624 * xjF F (month name) in Hebrew calendar
625 * xjt t (days in month) in Hebrew calendar
626 * xjx xg (genitive month name) in Hebrew calendar
627 * xjn n (month number) in Hebrew calendar
628 * xjY Y (full year) in Hebrew calendar
630 * xmj j (day number) in Hijri calendar
631 * xmF F (month name) in Hijri calendar
632 * xmn n (month number) in Hijri calendar
633 * xmY Y (full year) in Hijri calendar
635 * xkY Y (full year) in Thai solar calendar. Months and days are
636 * identical to the Gregorian calendar
637 * xoY Y (full year) in Minguo calendar or Juche year.
638 * Months and days are identical to the
640 * xtY Y (full year) in Japanese nengo. Months and days are
641 * identical to the Gregorian calendar
643 * Characters enclosed in double quotes will be considered literal (with
644 * the quotes themselves removed). Unmatched quotes will be considered
645 * literal quotes. Example:
647 * "The month is" F => The month is January
650 * Backslash escaping is also supported.
652 * Input timestamp is assumed to be pre-normalized to the desired local
655 * @param $format String
656 * @param $ts String: 14-character timestamp
659 * @todo emulation of "o" format character for PHP pre 5.1.0
660 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
662 function sprintfDate( $format, $ts ) {
675 for ( $p = 0; $p < strlen( $format ); $p++
) {
678 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
679 $code .= $format[++
$p];
682 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
683 $code .= $format[++
$p];
694 $rawToggle = !$rawToggle;
703 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
706 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
707 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
710 $num = substr( $ts, 6, 2 );
713 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
714 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
717 $num = intval( substr( $ts, 6, 2 ) );
720 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
724 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
728 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
732 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
733 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
736 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
737 $w = gmdate( 'w', $unix );
741 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
742 $num = gmdate( 'w', $unix );
745 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
746 $num = gmdate( 'z', $unix );
749 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
750 $num = gmdate( 'W', $unix );
753 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
756 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
757 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
760 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
761 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
764 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
765 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
768 $num = substr( $ts, 4, 2 );
771 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
774 $num = intval( substr( $ts, 4, 2 ) );
777 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
781 if ( !$hijri ) $hijri = self
::tsToHijri ( $ts );
785 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
789 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
790 $num = gmdate( 't', $unix );
793 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
797 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
798 $num = gmdate( 'L', $unix );
800 # 'o' is supported since PHP 5.1.0
801 # return literal if not supported
802 # TODO: emulation for pre 5.1.0 versions
804 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
805 if ( version_compare(PHP_VERSION
, '5.1.0') === 1 )
806 $num = date( 'o', $unix );
811 $num = substr( $ts, 0, 4 );
814 if ( !$iranian ) $iranian = self
::tsToIranian( $ts );
818 if ( !$hijri ) $hijri = self
::tsToHijri( $ts );
822 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
826 if ( !$thai ) $thai = self
::tsToYear( $ts, 'thai' );
830 if ( !$minguo ) $minguo = self
::tsToYear( $ts, 'minguo' );
834 if ( !$tenno ) $tenno = self
::tsToYear( $ts, 'tenno' );
838 $num = substr( $ts, 2, 2 );
841 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
844 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
847 $h = substr( $ts, 8, 2 );
848 $num = $h %
12 ?
$h %
12 : 12;
851 $num = intval( substr( $ts, 8, 2 ) );
854 $h = substr( $ts, 8, 2 );
855 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
858 $num = substr( $ts, 8, 2 );
861 $num = substr( $ts, 10, 2 );
864 $num = substr( $ts, 12, 2 );
867 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
868 $s .= gmdate( 'c', $unix );
871 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
872 $s .= gmdate( 'r', $unix );
875 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
880 if ( $p < strlen( $format ) - 1 ) {
888 if ( $p < strlen( $format ) - 1 ) {
889 $endQuote = strpos( $format, '"', $p +
1 );
890 if ( $endQuote === false ) {
891 # No terminating quote, assume literal "
894 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
898 # Quote at end of string, assume literal "
905 if ( $num !== false ) {
906 if ( $rawToggle ||
$raw ) {
909 } elseif ( $roman ) {
910 $s .= self
::romanNumeral( $num );
912 } elseif( $hebrewNum ) {
913 $s .= self
::hebrewNumeral( $num );
916 $s .= $this->formatNum( $num, true );
924 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
925 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
927 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
928 * Gregorian dates to Iranian dates. Originally written in C, it
929 * is released under the terms of GNU Lesser General Public
930 * License. Conversion to PHP was performed by Niklas Laxström.
932 * Link: http://www.farsiweb.info/jalali/jalali.c
934 private static function tsToIranian( $ts ) {
935 $gy = substr( $ts, 0, 4 ) -1600;
936 $gm = substr( $ts, 4, 2 ) -1;
937 $gd = substr( $ts, 6, 2 ) -1;
939 # Days passed from the beginning (including leap years)
942 - floor(($gy+
99) / 100)
943 +
floor(($gy+
399) / 400);
946 // Add days of the past months of this year
947 for( $i = 0; $i < $gm; $i++
) {
948 $gDayNo +
= self
::$GREG_DAYS[$i];
952 if ( $gm > 1 && (($gy%4
===0 && $gy%100
!==0 ||
($gy%400
==0)))) {
956 // Days passed in current month
959 $jDayNo = $gDayNo - 79;
961 $jNp = floor($jDayNo / 12053);
964 $jy = 979 +
33*$jNp +
4*floor($jDayNo/1461);
967 if ( $jDayNo >= 366 ) {
968 $jy +
= floor(($jDayNo-1)/365);
969 $jDayNo = floor(($jDayNo-1)%365
);
972 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
973 $jDayNo -= self
::$IRANIAN_DAYS[$i];
979 return array($jy, $jm, $jd);
982 * Converting Gregorian dates to Hijri dates.
984 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
986 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
988 private static function tsToHijri ( $ts ) {
989 $year = substr( $ts, 0, 4 );
990 $month = substr( $ts, 4, 2 );
991 $day = substr( $ts, 6, 2 );
1000 if (($zy>1582)||
(($zy==1582)&&($zm>10))||
(($zy==1582)&&($zm==10)&&($zd>14)))
1004 $zjd=(int)((1461*($zy +
4800 +
(int)( ($zm-14) /12) ))/4) +
(int)((367*($zm-2-12*((int)(($zm-14)/12))))/12)-(int)((3*(int)(( ($zy+
4900+
(int)(($zm-14)/12))/100)))/4)+
$zd-32075;
1008 $zjd = 367*$zy-(int)((7*($zy+
5001+
(int)(($zm-9)/7)))/4)+
(int)((275*$zm)/9)+
$zd+
1729777;
1011 $zl=$zjd-1948440+
10632;
1012 $zn=(int)(($zl-1)/10631);
1013 $zl=$zl-10631*$zn+
354;
1014 $zj=((int)((10985-$zl)/5316))*((int)((50*$zl)/17719))+
((int)($zl/5670))*((int)((43*$zl)/15238));
1015 $zl=$zl-((int)((30-$zj)/15))*((int)((17719*$zj)/50))-((int)($zj/16))*((int)((15238*$zj)/43))+
29;
1016 $zm=(int)((24*$zl)/709);
1017 $zd=$zl-(int)((709*$zm)/24);
1020 return array ($zy, $zm, $zd);
1024 * Converting Gregorian dates to Hebrew dates.
1026 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1027 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1028 * to translate the relevant functions into PHP and release them under
1031 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1032 * and Adar II is 14. In a non-leap year, Adar is 6.
1034 private static function tsToHebrew( $ts ) {
1036 $year = substr( $ts, 0, 4 );
1037 $month = substr( $ts, 4, 2 );
1038 $day = substr( $ts, 6, 2 );
1040 # Calculate Hebrew year
1041 $hebrewYear = $year +
3760;
1043 # Month number when September = 1, August = 12
1052 # Calculate day of year from 1 September
1054 for( $i = 1; $i < $month; $i++
) {
1058 # Check if the year is leap
1059 if( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1062 } elseif( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1069 # Calculate the start of the Hebrew year
1070 $start = self
::hebrewYearStart( $hebrewYear );
1072 # Calculate next year's start
1073 if( $dayOfYear <= $start ) {
1074 # Day is before the start of the year - it is the previous year
1076 $nextStart = $start;
1080 # Add days since previous year's 1 September
1082 if( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1086 # Start of the new (previous) year
1087 $start = self
::hebrewYearStart( $hebrewYear );
1090 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1093 # Calculate Hebrew day of year
1094 $hebrewDayOfYear = $dayOfYear - $start;
1096 # Difference between year's days
1097 $diff = $nextStart - $start;
1098 # Add 12 (or 13 for leap years) days to ignore the difference between
1099 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1100 # difference is only about the year type
1101 if( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1107 # Check the year pattern, and is leap year
1108 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1109 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1110 # and non-leap years
1111 $yearPattern = $diff %
30;
1112 # Check if leap year
1113 $isLeap = $diff >= 30;
1115 # Calculate day in the month from number of day in the Hebrew year
1116 # Don't check Adar - if the day is not in Adar, we will stop before;
1117 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1118 $hebrewDay = $hebrewDayOfYear;
1121 while( $hebrewMonth <= 12 ) {
1122 # Calculate days in this month
1123 if( $isLeap && $hebrewMonth == 6 ) {
1124 # Adar in a leap year
1126 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1128 if( $hebrewDay <= $days ) {
1132 # Subtract the days of Adar I
1133 $hebrewDay -= $days;
1136 if( $hebrewDay <= $days ) {
1142 } elseif( $hebrewMonth == 2 && $yearPattern == 2 ) {
1143 # Cheshvan in a complete year (otherwise as the rule below)
1145 } elseif( $hebrewMonth == 3 && $yearPattern == 0 ) {
1146 # Kislev in an incomplete year (otherwise as the rule below)
1149 # Odd months have 30 days, even have 29
1150 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1152 if( $hebrewDay <= $days ) {
1153 # In the current month
1156 # Subtract the days of the current month
1157 $hebrewDay -= $days;
1158 # Try in the next month
1163 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1167 * This calculates the Hebrew year start, as days since 1 September.
1168 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1169 * Used for Hebrew date.
1171 private static function hebrewYearStart( $year ) {
1172 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1173 $b = intval( ( $year - 1 ) %
4 );
1174 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1178 $Mar = intval( $m );
1184 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7);
1185 if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1187 } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1189 } else if( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1193 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1198 * Algorithm to convert Gregorian dates to Thai solar dates,
1199 * Minguo dates or Minguo dates.
1201 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1202 * http://en.wikipedia.org/wiki/Minguo_calendar
1203 * http://en.wikipedia.org/wiki/Japanese_era_name
1205 * @param $ts String: 14-character timestamp, calender name
1206 * @return array converted year, month, day
1208 private static function tsToYear( $ts, $cName ) {
1209 $gy = substr( $ts, 0, 4 );
1210 $gm = substr( $ts, 4, 2 );
1211 $gd = substr( $ts, 6, 2 );
1213 if (!strcmp($cName,'thai')) {
1215 # Add 543 years to the Gregorian calendar
1216 # Months and days are identical
1217 $gy_offset = $gy +
543;
1218 } else if ((!strcmp($cName,'minguo')) ||
!strcmp($cName,'juche')) {
1220 # Deduct 1911 years from the Gregorian calendar
1221 # Months and days are identical
1222 $gy_offset = $gy - 1911;
1223 } else if (!strcmp($cName,'tenno')) {
1224 # Nengō dates up to Meiji period
1225 # Deduct years from the Gregorian calendar
1226 # depending on the nengo periods
1227 # Months and days are identical
1228 if (($gy < 1912) ||
(($gy == 1912) && ($gm < 7)) ||
(($gy == 1912) && ($gm == 7) && ($gd < 31))) {
1230 $gy_gannen = $gy - 1868 +
1;
1231 $gy_offset = $gy_gannen;
1232 if ($gy_gannen == 1)
1234 $gy_offset = '明治'.$gy_offset;
1235 } else if ((($gy == 1912) && ($gm == 7) && ($gd == 31)) ||
(($gy == 1912) && ($gm >= 8)) ||
(($gy > 1912) && ($gy < 1926)) ||
(($gy == 1926) && ($gm < 12)) ||
(($gy == 1926) && ($gm == 12) && ($gd < 26))) {
1237 $gy_gannen = $gy - 1912 +
1;
1238 $gy_offset = $gy_gannen;
1239 if ($gy_gannen == 1)
1241 $gy_offset = '大正'.$gy_offset;
1242 } else if ((($gy == 1926) && ($gm == 12) && ($gd >= 26)) ||
(($gy > 1926) && ($gy < 1989)) ||
(($gy == 1989) && ($gm == 1) && ($gd < 8))) {
1244 $gy_gannen = $gy - 1926 +
1;
1245 $gy_offset = $gy_gannen;
1246 if ($gy_gannen == 1)
1248 $gy_offset = '昭和'.$gy_offset;
1251 $gy_gannen = $gy - 1989 +
1;
1252 $gy_offset = $gy_gannen;
1253 if ($gy_gannen == 1)
1255 $gy_offset = '平成'.$gy_offset;
1261 return array( $gy_offset, $gm, $gd );
1265 * Roman number formatting up to 3000
1267 static function romanNumeral( $num ) {
1268 static $table = array(
1269 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1270 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1271 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1272 array( '', 'M', 'MM', 'MMM' )
1275 $num = intval( $num );
1276 if ( $num > 3000 ||
$num <= 0 ) {
1281 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1282 if ( $num >= $pow10 ) {
1283 $s .= $table[$i][floor($num / $pow10)];
1285 $num = $num %
$pow10;
1291 * Hebrew Gematria number formatting up to 9999
1293 static function hebrewNumeral( $num ) {
1294 static $table = array(
1295 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1296 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1297 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1298 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1301 $num = intval( $num );
1302 if ( $num > 9999 ||
$num <= 0 ) {
1307 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1308 if ( $num >= $pow10 ) {
1309 if ( $num == 15 ||
$num == 16 ) {
1310 $s .= $table[0][9] . $table[0][$num - 9];
1313 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1314 if( $pow10 == 1000 ) {
1319 $num = $num %
$pow10;
1321 if( strlen( $s ) == 2 ) {
1324 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1325 $str .= substr( $s, strlen( $s ) - 2, 2 );
1327 $start = substr( $str, 0, strlen( $str ) - 2 );
1328 $end = substr( $str, strlen( $str ) - 2 );
1331 $str = $start . 'ך';
1334 $str = $start . 'ם';
1337 $str = $start . 'ן';
1340 $str = $start . 'ף';
1343 $str = $start . 'ץ';
1350 * This is meant to be used by time(), date(), and timeanddate() to get
1351 * the date preference they're supposed to use, it should be used in
1355 * function timeanddate([...], $format = true) {
1356 * $datePreference = $this->dateFormat($format);
1361 * @param $usePrefs Mixed: if true, the user's preference is used
1362 * if false, the site/language default is used
1363 * if int/string, assumed to be a format.
1366 function dateFormat( $usePrefs = true ) {
1369 if( is_bool( $usePrefs ) ) {
1371 $datePreference = $wgUser->getDatePreference();
1373 $options = User
::getDefaultOptions();
1374 $datePreference = (string)$options['date'];
1377 $datePreference = (string)$usePrefs;
1381 if( $datePreference == '' ) {
1385 return $datePreference;
1389 * Get a format string for a given type and preference
1390 * @param $type May be date, time or both
1391 * @param $pref The format name as it appears in Messages*.php
1393 function getDateFormatString( $type, $pref ) {
1394 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1395 if ( $pref == 'default' ) {
1396 $pref = $this->getDefaultDateFormat();
1397 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1399 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1400 if ( is_null( $df ) ) {
1401 $pref = $this->getDefaultDateFormat();
1402 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1405 $this->dateFormatStrings
[$type][$pref] = $df;
1407 return $this->dateFormatStrings
[$type][$pref];
1411 * @param $ts Mixed: the time format which needs to be turned into a
1412 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1413 * @param $adj Bool: whether to adjust the time output according to the
1414 * user configured offset ($timecorrection)
1415 * @param $format Mixed: true to use user's date format preference
1416 * @param $timecorrection String: the time offset as returned by
1417 * validateTimeZone() in Special:Preferences
1420 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1422 $ts = $this->userAdjust( $ts, $timecorrection );
1424 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1425 return $this->sprintfDate( $df, $ts );
1429 * @param $ts Mixed: the time format which needs to be turned into a
1430 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1431 * @param $adj Bool: whether to adjust the time output according to the
1432 * user configured offset ($timecorrection)
1433 * @param $format Mixed: true to use user's date format preference
1434 * @param $timecorrection String: the time offset as returned by
1435 * validateTimeZone() in Special:Preferences
1438 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1440 $ts = $this->userAdjust( $ts, $timecorrection );
1442 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1443 return $this->sprintfDate( $df, $ts );
1447 * @param $ts Mixed: the time format which needs to be turned into a
1448 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1449 * @param $adj Bool: whether to adjust the time output according to the
1450 * user configured offset ($timecorrection)
1451 * @param $format Mixed: what format to return, if it's false output the
1452 * default one (default true)
1453 * @param $timecorrection String: the time offset as returned by
1454 * validateTimeZone() in Special:Preferences
1457 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
1458 $ts = wfTimestamp( TS_MW
, $ts );
1460 $ts = $this->userAdjust( $ts, $timecorrection );
1462 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1463 return $this->sprintfDate( $df, $ts );
1466 function getMessage( $key ) {
1467 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1470 function getAllMessages() {
1471 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1474 function iconv( $in, $out, $string ) {
1475 # This is a wrapper for iconv in all languages except esperanto,
1476 # which does some nasty x-conversions beforehand
1478 # Even with //IGNORE iconv can whine about illegal characters in
1479 # *input* string. We just ignore those too.
1480 # REF: http://bugs.php.net/bug.php?id=37166
1481 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1482 wfSuppressWarnings();
1483 $text = iconv( $in, $out . '//IGNORE', $string );
1484 wfRestoreWarnings();
1488 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1489 function ucwordbreaksCallbackAscii($matches){
1490 return $this->ucfirst($matches[1]);
1493 function ucwordbreaksCallbackMB($matches){
1494 return mb_strtoupper($matches[0]);
1497 function ucCallback($matches){
1498 list( $wikiUpperChars ) = self
::getCaseMaps();
1499 return strtr( $matches[1], $wikiUpperChars );
1502 function lcCallback($matches){
1503 list( , $wikiLowerChars ) = self
::getCaseMaps();
1504 return strtr( $matches[1], $wikiLowerChars );
1507 function ucwordsCallbackMB($matches){
1508 return mb_strtoupper($matches[0]);
1511 function ucwordsCallbackWiki($matches){
1512 list( $wikiUpperChars ) = self
::getCaseMaps();
1513 return strtr( $matches[0], $wikiUpperChars );
1516 function ucfirst( $str ) {
1520 } elseif ( $o < 128 ) {
1521 return ucfirst($str);
1523 // fall back to more complex logic in case of multibyte strings
1524 return self
::uc($str,true);
1528 function uc( $str, $first = false ) {
1529 if ( function_exists( 'mb_strtoupper' ) ) {
1531 if ( self
::isMultibyte( $str ) ) {
1532 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1534 return ucfirst( $str );
1537 return self
::isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1540 if ( self
::isMultibyte( $str ) ) {
1541 list( $wikiUpperChars ) = $this->getCaseMaps();
1542 $x = $first ?
'^' : '';
1543 return preg_replace_callback(
1544 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1545 array($this,"ucCallback"),
1549 return $first ?
ucfirst( $str ) : strtoupper( $str );
1554 function lcfirst( $str ) {
1557 return strval( $str );
1558 } elseif ( $o >= 128 ) {
1559 return self
::lc( $str, true );
1560 } elseif ( $o > 96 ) {
1563 $str[0] = strtolower( $str[0] );
1568 function lc( $str, $first = false ) {
1569 if ( function_exists( 'mb_strtolower' ) )
1571 if ( self
::isMultibyte( $str ) )
1572 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1574 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1576 return self
::isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1578 if ( self
::isMultibyte( $str ) ) {
1579 list( , $wikiLowerChars ) = self
::getCaseMaps();
1580 $x = $first ?
'^' : '';
1581 return preg_replace_callback(
1582 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1583 array($this,"lcCallback"),
1587 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1590 function isMultibyte( $str ) {
1591 return (bool)preg_match( '/[\x80-\xff]/', $str );
1594 function ucwords($str) {
1595 if ( self
::isMultibyte( $str ) ) {
1596 $str = self
::lc($str);
1598 // regexp to find first letter in each word (i.e. after each space)
1599 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1601 // function to use to capitalize a single char
1602 if ( function_exists( 'mb_strtoupper' ) )
1603 return preg_replace_callback(
1605 array($this,"ucwordsCallbackMB"),
1609 return preg_replace_callback(
1611 array($this,"ucwordsCallbackWiki"),
1616 return ucwords( strtolower( $str ) );
1619 # capitalize words at word breaks
1620 function ucwordbreaks($str){
1621 if (self
::isMultibyte( $str ) ) {
1622 $str = self
::lc($str);
1624 // since \b doesn't work for UTF-8, we explicitely define word break chars
1625 $breaks= "[ \-\(\)\}\{\.,\?!]";
1627 // find first letter after word break
1628 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1630 if ( function_exists( 'mb_strtoupper' ) )
1631 return preg_replace_callback(
1633 array($this,"ucwordbreaksCallbackMB"),
1637 return preg_replace_callback(
1639 array($this,"ucwordsCallbackWiki"),
1644 return preg_replace_callback(
1645 '/\b([\w\x80-\xff]+)\b/',
1646 array($this,"ucwordbreaksCallbackAscii"),
1651 * Return a case-folded representation of $s
1653 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1654 * and $s2 are the same except for the case of their characters. It is not
1655 * necessary for the value returned to make sense when displayed.
1657 * Do *not* perform any other normalisation in this function. If a caller
1658 * uses this function when it should be using a more general normalisation
1659 * function, then fix the caller.
1661 function caseFold( $s ) {
1662 return $this->uc( $s );
1665 function checkTitleEncoding( $s ) {
1666 if( is_array( $s ) ) {
1667 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1669 # Check for non-UTF-8 URLs
1670 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1671 if(!$ishigh) return $s;
1673 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1674 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1675 if( $isutf8 ) return $s;
1677 return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
1680 function fallback8bitEncoding() {
1681 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1685 * Most writing systems use whitespace to break up words.
1686 * Some languages such as Chinese don't conventionally do this,
1687 * which requires special handling when breaking up words for
1690 function hasWordBreaks() {
1695 * Some languages have special punctuation to strip out
1696 * or characters which need to be converted for MySQL's
1697 * indexing to grok it correctly. Make such changes here.
1699 * @param $string String
1702 function stripForSearch( $string ) {
1704 if ( $wgDBtype != 'mysql' ) {
1709 wfProfileIn( __METHOD__
);
1711 // MySQL fulltext index doesn't grok utf-8, so we
1712 // need to fold cases and convert to hex
1713 $out = preg_replace_callback(
1714 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
1715 array( $this, 'stripForSearchCallback' ),
1716 $this->lc( $string ) );
1718 // And to add insult to injury, the default indexing
1719 // ignores short words... Pad them so we can pass them
1720 // through without reconfiguring the server...
1721 $minLength = $this->minSearchLength();
1722 if( $minLength > 1 ) {
1724 $out = preg_replace(
1730 // Periods within things like hostnames and IP addresses
1731 // are also important -- we want a search for "example.com"
1732 // or "192.168.1.1" to work sanely.
1734 // MySQL's search seems to ignore them, so you'd match on
1735 // "example.wikipedia.com" and "192.168.83.1" as well.
1736 $out = preg_replace(
1741 wfProfileOut( __METHOD__
);
1746 * Armor a case-folded UTF-8 string to get through MySQL's
1747 * fulltext search without being mucked up by funny charset
1748 * settings or anything else of the sort.
1750 protected function stripForSearchCallback( $matches ) {
1751 return 'u8' . bin2hex( $matches[1] );
1755 * Check MySQL server's ft_min_word_len setting so we know
1756 * if we need to pad short words...
1758 protected function minSearchLength() {
1759 if( is_null( $this->minSearchLength
) ) {
1760 $sql = "show global variables like 'ft\\_min\\_word\\_len'";
1761 $dbr = wfGetDB( DB_SLAVE
);
1762 $result = $dbr->query( $sql );
1763 $row = $result->fetchObject();
1766 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
1767 $this->minSearchLength
= intval( $row->Value
);
1769 $this->minSearchLength
= 0;
1772 return $this->minSearchLength
;
1775 function convertForSearchResult( $termsArray ) {
1776 # some languages, e.g. Chinese, need to do a conversion
1777 # in order for search results to be displayed correctly
1782 * Get the first character of a string.
1787 function firstChar( $s ) {
1789 preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1790 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
1792 if ( isset( $matches[1] ) ) {
1793 if ( strlen( $matches[1] ) != 3 ) {
1797 // Break down Hangul syllables to grab the first jamo
1798 $code = utf8ToCodepoint( $matches[1] );
1799 if ( $code < 0xac00 ||
0xd7a4 <= $code) {
1801 } elseif ( $code < 0xb098 ) {
1802 return "\xe3\x84\xb1";
1803 } elseif ( $code < 0xb2e4 ) {
1804 return "\xe3\x84\xb4";
1805 } elseif ( $code < 0xb77c ) {
1806 return "\xe3\x84\xb7";
1807 } elseif ( $code < 0xb9c8 ) {
1808 return "\xe3\x84\xb9";
1809 } elseif ( $code < 0xbc14 ) {
1810 return "\xe3\x85\x81";
1811 } elseif ( $code < 0xc0ac ) {
1812 return "\xe3\x85\x82";
1813 } elseif ( $code < 0xc544 ) {
1814 return "\xe3\x85\x85";
1815 } elseif ( $code < 0xc790 ) {
1816 return "\xe3\x85\x87";
1817 } elseif ( $code < 0xcc28 ) {
1818 return "\xe3\x85\x88";
1819 } elseif ( $code < 0xce74 ) {
1820 return "\xe3\x85\x8a";
1821 } elseif ( $code < 0xd0c0 ) {
1822 return "\xe3\x85\x8b";
1823 } elseif ( $code < 0xd30c ) {
1824 return "\xe3\x85\x8c";
1825 } elseif ( $code < 0xd558 ) {
1826 return "\xe3\x85\x8d";
1828 return "\xe3\x85\x8e";
1835 function initEncoding() {
1836 # Some languages may have an alternate char encoding option
1837 # (Esperanto X-coding, Japanese furigana conversion, etc)
1838 # If this language is used as the primary content language,
1839 # an override to the defaults can be set here on startup.
1842 function recodeForEdit( $s ) {
1843 # For some languages we'll want to explicitly specify
1844 # which characters make it into the edit box raw
1845 # or are converted in some way or another.
1846 # Note that if wgOutputEncoding is different from
1847 # wgInputEncoding, this text will be further converted
1848 # to wgOutputEncoding.
1849 global $wgEditEncoding;
1850 if( $wgEditEncoding == '' or
1851 $wgEditEncoding == 'UTF-8' ) {
1854 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1858 function recodeInput( $s ) {
1859 # Take the previous into account.
1860 global $wgEditEncoding;
1861 if($wgEditEncoding != "") {
1862 $enc = $wgEditEncoding;
1866 if( $enc == 'UTF-8' ) {
1869 return $this->iconv( $enc, 'UTF-8', $s );
1874 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1875 * also cleans up certain backwards-compatible sequences, converting them
1876 * to the modern Unicode equivalent.
1878 * This is language-specific for performance reasons only.
1880 function normalize( $s ) {
1881 return UtfNormal
::cleanUp( $s );
1885 * Transform a string using serialized data stored in the given file (which
1886 * must be in the serialized subdirectory of $IP). The file contains pairs
1887 * mapping source characters to destination characters.
1889 * The data is cached in process memory. This will go faster if you have the
1890 * FastStringSearch extension.
1892 function transformUsingPairFile( $file, $string ) {
1893 if ( !isset( $this->transformData
[$file] ) ) {
1894 $data = wfGetPrecompiledData( $file );
1895 if ( $data === false ) {
1896 throw new MWException( __METHOD__
.": The transformation file $file is missing" );
1898 $this->transformData
[$file] = new ReplacementArray( $data );
1900 return $this->transformData
[$file]->replace( $string );
1904 * For right-to-left language support
1909 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1913 * Return the correct HTML 'dir' attribute value for this language.
1917 return $this->isRTL() ?
'rtl' : 'ltr';
1921 * Return 'left' or 'right' as appropriate alignment for line-start
1922 * for this language's text direction.
1924 * Should be equivalent to CSS3 'start' text-align value....
1928 function alignStart() {
1929 return $this->isRTL() ?
'right' : 'left';
1933 * Return 'right' or 'left' as appropriate alignment for line-end
1934 * for this language's text direction.
1936 * Should be equivalent to CSS3 'end' text-align value....
1940 function alignEnd() {
1941 return $this->isRTL() ?
'left' : 'right';
1945 * A hidden direction mark (LRM or RLM), depending on the language direction
1949 function getDirMark() {
1950 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
1953 function capitalizeAllNouns() {
1954 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
1958 * An arrow, depending on the language direction
1962 function getArrow() {
1963 return $this->isRTL() ?
'←' : '→';
1967 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
1971 function linkPrefixExtension() {
1972 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
1975 function getMagicWords() {
1976 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
1979 # Fill a MagicWord object with data from here
1980 function getMagic( $mw ) {
1981 if ( !$this->mMagicHookDone
) {
1982 $this->mMagicHookDone
= true;
1983 wfProfileIn( 'LanguageGetMagic' );
1984 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
1985 wfProfileOut( 'LanguageGetMagic' );
1987 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
1988 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
1990 $magicWords = $this->getMagicWords();
1991 if ( isset( $magicWords[$mw->mId
] ) ) {
1992 $rawEntry = $magicWords[$mw->mId
];
1998 if( !is_array( $rawEntry ) ) {
1999 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2001 $mw->mCaseSensitive
= $rawEntry[0];
2002 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2007 * Add magic words to the extension array
2009 function addMagicWordsByLang( $newWords ) {
2010 $code = $this->getCode();
2011 $fallbackChain = array();
2012 while ( $code && !in_array( $code, $fallbackChain ) ) {
2013 $fallbackChain[] = $code;
2014 $code = self
::getFallbackFor( $code );
2016 if ( !in_array( 'en', $fallbackChain ) ) {
2017 $fallbackChain[] = 'en';
2019 $fallbackChain = array_reverse( $fallbackChain );
2020 foreach ( $fallbackChain as $code ) {
2021 if ( isset( $newWords[$code] ) ) {
2022 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2028 * Get special page names, as an associative array
2029 * case folded alias => real name
2031 function getSpecialPageAliases() {
2032 // Cache aliases because it may be slow to load them
2033 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2035 $this->mExtendedSpecialPageAliases
=
2036 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2037 wfRunHooks( 'LanguageGetSpecialPageAliases',
2038 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2041 return $this->mExtendedSpecialPageAliases
;
2045 * Italic is unsuitable for some languages
2047 * @param $text String: the text to be emphasized.
2050 function emphasize( $text ) {
2051 return "<em>$text</em>";
2055 * Normally we output all numbers in plain en_US style, that is
2056 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2057 * point twohundredthirtyfive. However this is not sutable for all
2058 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2059 * Icelandic just want to use commas instead of dots, and dots instead
2060 * of commas like "293.291,235".
2062 * An example of this function being called:
2064 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2067 * See LanguageGu.php for the Gujarati implementation and
2068 * $separatorTransformTable on MessageIs.php for
2069 * the , => . and . => , implementation.
2071 * @todo check if it's viable to use localeconv() for the decimal
2073 * @param $number Mixed: the string to be formatted, should be an integer
2074 * or a floating point number.
2075 * @param $nocommafy Bool: set to true for special numbers like dates
2078 function formatNum( $number, $nocommafy = false ) {
2079 global $wgTranslateNumerals;
2081 $number = $this->commafy($number);
2082 $s = $this->separatorTransformTable();
2083 if ($s) { $number = strtr($number, $s); }
2086 if ($wgTranslateNumerals) {
2087 $s = $this->digitTransformTable();
2088 if ($s) { $number = strtr($number, $s); }
2094 function parseFormattedNumber( $number ) {
2095 $s = $this->digitTransformTable();
2096 if ($s) { $number = strtr($number, array_flip($s)); }
2098 $s = $this->separatorTransformTable();
2099 if ($s) { $number = strtr($number, array_flip($s)); }
2101 $number = strtr( $number, array (',' => '') );
2106 * Adds commas to a given number
2111 function commafy($_) {
2112 return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
2115 function digitTransformTable() {
2116 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2119 function separatorTransformTable() {
2120 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2125 * Take a list of strings and build a locale-friendly comma-separated
2126 * list, using the local comma-separator message.
2127 * The last two strings are chained with an "and".
2132 function listToText( $l ) {
2134 $m = count( $l ) - 1;
2136 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2139 for ( $i = $m; $i >= 0; $i-- ) {
2142 } else if( $i == $m - 1 ) {
2143 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2145 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2153 * Take a list of strings and build a locale-friendly comma-separated
2154 * list, using the local comma-separator message.
2155 * @param $list array of strings to put in a comma list
2158 function commaList( $list ) {
2161 wfMsgExt( 'comma-separator', array( 'parsemag', 'escapenoentities', 'language' => $this ) ) );
2165 * Take a list of strings and build a locale-friendly semicolon-separated
2166 * list, using the local semicolon-separator message.
2167 * @param $list array of strings to put in a semicolon list
2170 function semicolonList( $list ) {
2173 wfMsgExt( 'semicolon-separator', array( 'parsemag', 'escapenoentities', 'language' => $this ) ) );
2177 * Same as commaList, but separate it with the pipe instead.
2178 * @param $list array of strings to put in a pipe list
2181 function pipeList( $list ) {
2184 wfMsgExt( 'pipe-separator', array( 'escapenoentities', 'language' => $this ) ) );
2188 * Truncate a string to a specified length in bytes, appending an optional
2189 * string (e.g. for ellipses)
2191 * The database offers limited byte lengths for some columns in the database;
2192 * multi-byte character sets mean we need to ensure that only whole characters
2193 * are included, otherwise broken characters can be passed to the user
2195 * If $length is negative, the string will be truncated from the beginning
2197 * @param $string String to truncate
2198 * @param $length Int: maximum length (excluding ellipses)
2199 * @param $ellipsis String to append to the truncated text
2202 function truncate( $string, $length, $ellipsis = '...' ) {
2203 # Use the localized ellipsis character
2204 if( $ellipsis == '...' ) {
2205 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2208 if( $length == 0 ) {
2211 if ( strlen( $string ) <= abs( $length ) ) {
2215 $string = substr( $string, 0, $length );
2216 $char = ord( $string[strlen( $string ) - 1] );
2218 if ($char >= 0xc0) {
2219 # We got the first byte only of a multibyte char; remove it.
2220 $string = substr( $string, 0, -1 );
2221 } elseif( $char >= 0x80 &&
2222 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2223 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
2224 # We chopped in the middle of a character; remove it
2227 return $string . $ellipsis;
2229 $string = substr( $string, $length );
2230 $char = ord( $string[0] );
2231 if( $char >= 0x80 && $char < 0xc0 ) {
2232 # We chopped in the middle of a character; remove the whole thing
2233 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2235 return $ellipsis . $string;
2240 * Grammatical transformations, needed for inflected languages
2241 * Invoked by putting {{grammar:case|word}} in a message
2243 * @param $word string
2244 * @param $case string
2247 function convertGrammar( $word, $case ) {
2248 global $wgGrammarForms;
2249 if ( isset($wgGrammarForms[$this->getCode()][$case][$word]) ) {
2250 return $wgGrammarForms[$this->getCode()][$case][$word];
2256 * Provides an alternative text depending on specified gender.
2257 * Usage {{gender:username|masculine|feminine|neutral}}.
2258 * username is optional, in which case the gender of current user is used,
2259 * but only in (some) interface messages; otherwise default gender is used.
2260 * If second or third parameter are not specified, masculine is used.
2261 * These details may be overriden per language.
2263 function gender( $gender, $forms ) {
2264 if ( !count($forms) ) { return ''; }
2265 $forms = $this->preConvertPlural( $forms, 2 );
2266 if ( $gender === 'male' ) return $forms[0];
2267 if ( $gender === 'female' ) return $forms[1];
2268 return isset($forms[2]) ?
$forms[2] : $forms[0];
2272 * Plural form transformations, needed for some languages.
2273 * For example, there are 3 form of plural in Russian and Polish,
2274 * depending on "count mod 10". See [[w:Plural]]
2275 * For English it is pretty simple.
2277 * Invoked by putting {{plural:count|wordform1|wordform2}}
2278 * or {{plural:count|wordform1|wordform2|wordform3}}
2280 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2282 * @param $count Integer: non-localized number
2283 * @param $forms Array: different plural forms
2284 * @return string Correct form of plural for $count in this language
2286 function convertPlural( $count, $forms ) {
2287 if ( !count($forms) ) { return ''; }
2288 $forms = $this->preConvertPlural( $forms, 2 );
2290 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2294 * Checks that convertPlural was given an array and pads it to requested
2295 * amound of forms by copying the last one.
2297 * @param $count Integer: How many forms should there be at least
2298 * @param $forms Array of forms given to convertPlural
2299 * @return array Padded array of forms or an exception if not an array
2301 protected function preConvertPlural( /* Array */ $forms, $count ) {
2302 while ( count($forms) < $count ) {
2303 $forms[] = $forms[count($forms)-1];
2309 * For translaing of expiry times
2310 * @param $str String: the validated block time in English
2311 * @return Somehow translated block time
2312 * @see LanguageFi.php for example implementation
2314 function translateBlockExpiry( $str ) {
2316 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2318 if ( $scBlockExpiryOptions == '-') {
2322 foreach (explode(',', $scBlockExpiryOptions) as $option) {
2323 if ( strpos($option, ":") === false )
2325 list($show, $value) = explode(":", $option);
2326 if ( strcmp ( $str, $value) == 0 ) {
2327 return htmlspecialchars( trim( $show ) );
2335 * languages like Chinese need to be segmented in order for the diff
2338 * @param $text String
2341 function segmentForDiff( $text ) {
2346 * and unsegment to show the result
2348 * @param $text String
2351 function unsegmentForDiff( $text ) {
2355 # convert text to all supported variants
2356 function autoConvertToAllVariants($text) {
2357 return $this->mConverter
->autoConvertToAllVariants($text);
2360 # convert text to different variants of a language.
2361 function convert( $text, $isTitle = false) {
2362 return $this->mConverter
->convert($text, $isTitle);
2365 # Convert text from within Parser
2366 function parserConvert( $text, &$parser ) {
2367 return $this->mConverter
->parserConvert( $text, $parser );
2370 # Check if this is a language with variants
2371 function hasVariants(){
2372 return sizeof($this->getVariants())>1;
2375 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2376 function armourMath($text){
2377 return $this->mConverter
->armourMath($text);
2382 * Perform output conversion on a string, and encode for safe HTML output.
2383 * @param $text String text to be converted
2384 * @param $isTitle Bool whether this conversion is for the article title
2386 * @todo this should get integrated somewhere sane
2388 function convertHtml( $text, $isTitle = false ) {
2389 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2392 function convertCategoryKey( $key ) {
2393 return $this->mConverter
->convertCategoryKey( $key );
2397 * get the list of variants supported by this langauge
2398 * see sample implementation in LanguageZh.php
2400 * @return array an array of language codes
2402 function getVariants() {
2403 return $this->mConverter
->getVariants();
2407 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2408 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2412 * if a language supports multiple variants, it is
2413 * possible that non-existing link in one variant
2414 * actually exists in another variant. this function
2415 * tries to find it. See e.g. LanguageZh.php
2417 * @param $link String: the name of the link
2418 * @param $nt Mixed: the title object of the link
2419 * @param boolean $ignoreOtherCond: to disable other conditions when
2420 * we need to transclude a template or update a category's link
2421 * @return null the input parameters may be modified upon return
2423 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2424 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2428 * If a language supports multiple variants, converts text
2429 * into an array of all possible variants of the text:
2430 * 'variant' => text in that variant
2432 function convertLinkToAllVariants($text){
2433 return $this->mConverter
->convertLinkToAllVariants($text);
2438 * returns language specific options used by User::getPageRenderHash()
2439 * for example, the preferred language variant
2443 function getExtraHashOptions() {
2444 return $this->mConverter
->getExtraHashOptions();
2448 * for languages that support multiple variants, the title of an
2449 * article may be displayed differently in different variants. this
2450 * function returns the apporiate title defined in the body of the article.
2454 function getParsedTitle() {
2455 return $this->mConverter
->getParsedTitle();
2459 * Enclose a string with the "no conversion" tag. This is used by
2460 * various functions in the Parser
2462 * @param $text String: text to be tagged for no conversion
2464 * @return string the tagged text
2466 function markNoConversion( $text, $noParse=false ) {
2467 return $this->mConverter
->markNoConversion( $text, $noParse );
2471 * A regular expression to match legal word-trailing characters
2472 * which should be merged onto a link of the form [[foo]]bar.
2476 function linkTrail() {
2477 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2480 function getLangObj() {
2485 * Get the RFC 3066 code for this language object
2487 function getCode() {
2488 return $this->mCode
;
2491 function setCode( $code ) {
2492 $this->mCode
= $code;
2495 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2496 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2499 static function getMessagesFileName( $code ) {
2501 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2504 static function getClassFileName( $code ) {
2506 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2510 * Get the fallback for a given language
2512 static function getFallbackFor( $code ) {
2513 if ( $code === 'en' ) {
2517 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2522 * Get all messages for a given language
2523 * WARNING: this may take a long time
2525 static function getMessagesFor( $code ) {
2526 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2530 * Get a message for a given language
2532 static function getMessageFor( $key, $code ) {
2533 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2536 function fixVariableInNamespace( $talk ) {
2537 if ( strpos( $talk, '$1' ) === false ) return $talk;
2539 global $wgMetaNamespace;
2540 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2542 # Allow grammar transformations
2543 # Allowing full message-style parsing would make simple requests
2544 # such as action=raw much more expensive than they need to be.
2545 # This will hopefully cover most cases.
2546 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2547 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2548 return str_replace( ' ', '_', $talk );
2551 function replaceGrammarInNamespace( $m ) {
2552 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2555 static function getCaseMaps() {
2556 static $wikiUpperChars, $wikiLowerChars;
2557 if ( isset( $wikiUpperChars ) ) {
2558 return array( $wikiUpperChars, $wikiLowerChars );
2561 wfProfileIn( __METHOD__
);
2562 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2563 if ( $arr === false ) {
2564 throw new MWException(
2565 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2568 wfProfileOut( __METHOD__
);
2569 return array( $wikiUpperChars, $wikiLowerChars );
2572 function formatTimePeriod( $seconds ) {
2573 if ( $seconds < 10 ) {
2574 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . wfMsg( 'seconds-abbrev' );
2575 } elseif ( $seconds < 60 ) {
2576 return $this->formatNum( round( $seconds ) ) . wfMsg( 'seconds-abbrev' );
2577 } elseif ( $seconds < 3600 ) {
2578 return $this->formatNum( floor( $seconds / 60 ) ) . wfMsg( 'minutes-abbrev' ) .
2579 $this->formatNum( round( fmod( $seconds, 60 ) ) ) . wfMsg( 'seconds-abbrev' );
2581 $hours = floor( $seconds / 3600 );
2582 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2583 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2584 return $this->formatNum( $hours ) . wfMsg( 'hours-abbrev' ) .
2585 $this->formatNum( $minutes ) . wfMsg( 'minutes-abbrev' ) .
2586 $this->formatNum( $secondsPart ) . wfMsg( 'seconds-abbrev' );
2590 function formatBitrate( $bps ) {
2591 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2593 return $this->formatNum( $bps ) . $units[0];
2595 $unitIndex = floor( log10( $bps ) / 3 );
2596 $mantissa = $bps / pow( 1000, $unitIndex );
2597 if ( $mantissa < 10 ) {
2598 $mantissa = round( $mantissa, 1 );
2600 $mantissa = round( $mantissa );
2602 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2606 * Format a size in bytes for output, using an appropriate
2607 * unit (B, KB, MB or GB) according to the magnitude in question
2609 * @param $size Size to format
2610 * @return string Plain text (not HTML)
2612 function formatSize( $size ) {
2613 // For small sizes no decimal places necessary
2615 if( $size > 1024 ) {
2616 $size = $size / 1024;
2617 if( $size > 1024 ) {
2618 $size = $size / 1024;
2619 // For MB and bigger two decimal places are smarter
2621 if( $size > 1024 ) {
2622 $size = $size / 1024;
2623 $msg = 'size-gigabytes';
2625 $msg = 'size-megabytes';
2628 $msg = 'size-kilobytes';
2631 $msg = 'size-bytes';
2633 $size = round( $size, $round );
2634 $text = $this->getMessageFromDB( $msg );
2635 return str_replace( '$1', $this->formatNum( $size ), $text );