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 ) { return $t; }
40 function convertTitle( $t ) { return $t->getPrefixedText(); }
41 function getVariants() { return array( $this->mLang
->getCode() ); }
42 function getPreferredVariant() { return $this->mLang
->getCode(); }
43 function getConvRuleTitle() { return false; }
44 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
45 function getExtraHashOptions() { return ''; }
46 function getParsedTitle() { return ''; }
47 function markNoConversion( $text, $noParse = false ) { return $text; }
48 function convertCategoryKey( $key ) { return $key; }
49 function convertLinkToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
50 function armourMath( $text ) { return $text; }
54 * Internationalisation code
58 var $mConverter, $mVariants, $mCode, $mLoaded = false;
59 var $mMagicExtensions = array(), $mMagicHookDone = false;
61 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
62 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 # Sometimes a language will be localised but not actually exist on this wiki.
261 global $wgCanonicalNamespaceNames;
262 $validNamespaces = array_keys($wgCanonicalNamespaceNames);
263 $validNamespaces[] = NS_MAIN
;
264 foreach( $this->namespaceNames
as $key => $text ) {
265 if ( ! in_array( $key, $validNamespaces ) ) {
266 unset( $this->namespaceNames
[$key] );
270 # The above mixing may leave namespaces out of canonical order.
271 # Re-order by namespace ID number...
272 ksort( $this->namespaceNames
);
274 return $this->namespaceNames
;
278 * A convenience function that returns the same thing as
279 * getNamespaces() except with the array values changed to ' '
280 * where it found '_', useful for producing output to be displayed
281 * e.g. in <select> forms.
285 function getFormattedNamespaces() {
286 $ns = $this->getNamespaces();
287 foreach ( $ns as $k => $v ) {
288 $ns[$k] = strtr( $v, '_', ' ' );
294 * Get a namespace value by key
296 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
297 * echo $mw_ns; // prints 'MediaWiki'
300 * @param $index Int: the array key of the namespace to return
301 * @return mixed, string if the namespace value exists, otherwise false
303 function getNsText( $index ) {
304 $ns = $this->getNamespaces();
305 return isset( $ns[$index] ) ?
$ns[$index] : false;
309 * A convenience function that returns the same thing as
310 * getNsText() except with '_' changed to ' ', useful for
315 function getFormattedNsText( $index ) {
316 $ns = $this->getNsText( $index );
317 return strtr( $ns, '_', ' ' );
321 * Get a namespace key by value, case insensitive.
322 * Only matches namespace names for the current language, not the
323 * canonical ones defined in Namespace.php.
325 * @param $text String
326 * @return mixed An integer if $text is a valid value otherwise false
328 function getLocalNsIndex( $text ) {
329 $lctext = $this->lc( $text );
330 $ids = $this->getNamespaceIds();
331 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
334 function getNamespaceAliases() {
335 if ( is_null( $this->namespaceAliases
) ) {
336 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
340 foreach ( $aliases as $name => $index ) {
341 if ( $index === NS_PROJECT_TALK
) {
342 unset( $aliases[$name] );
343 $name = $this->fixVariableInNamespace( $name );
344 $aliases[$name] = $index;
348 $this->namespaceAliases
= $aliases;
350 return $this->namespaceAliases
;
353 function getNamespaceIds() {
354 if ( is_null( $this->mNamespaceIds
) ) {
355 global $wgNamespaceAliases;
356 # Put namespace names and aliases into a hashtable.
357 # If this is too slow, then we should arrange it so that it is done
358 # before caching. The catch is that at pre-cache time, the above
359 # class-specific fixup hasn't been done.
360 $this->mNamespaceIds
= array();
361 foreach ( $this->getNamespaces() as $index => $name ) {
362 $this->mNamespaceIds
[$this->lc( $name )] = $index;
364 foreach ( $this->getNamespaceAliases() as $name => $index ) {
365 $this->mNamespaceIds
[$this->lc( $name )] = $index;
367 if ( $wgNamespaceAliases ) {
368 foreach ( $wgNamespaceAliases as $name => $index ) {
369 $this->mNamespaceIds
[$this->lc( $name )] = $index;
373 return $this->mNamespaceIds
;
378 * Get a namespace key by value, case insensitive. Canonical namespace
379 * names override custom ones defined for the current language.
381 * @param $text String
382 * @return mixed An integer if $text is a valid value otherwise false
384 function getNsIndex( $text ) {
385 $lctext = $this->lc( $text );
386 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
389 $ids = $this->getNamespaceIds();
390 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
394 * short names for language variants used for language conversion links.
396 * @param $code String
399 function getVariantname( $code ) {
400 return $this->getMessageFromDB( "variantname-$code" );
403 function specialPage( $name ) {
404 $aliases = $this->getSpecialPageAliases();
405 if ( isset( $aliases[$name][0] ) ) {
406 $name = $aliases[$name][0];
408 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
411 function getQuickbarSettings() {
413 $this->getMessage( 'qbsettings-none' ),
414 $this->getMessage( 'qbsettings-fixedleft' ),
415 $this->getMessage( 'qbsettings-fixedright' ),
416 $this->getMessage( 'qbsettings-floatingleft' ),
417 $this->getMessage( 'qbsettings-floatingright' )
421 function getMathNames() {
422 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
425 function getDatePreferences() {
426 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
429 function getDateFormats() {
430 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
433 function getDefaultDateFormat() {
434 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
435 if ( $df === 'dmy or mdy' ) {
436 global $wgAmericanDates;
437 return $wgAmericanDates ?
'mdy' : 'dmy';
443 function getDatePreferenceMigrationMap() {
444 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
447 function getImageFile( $image ) {
448 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
451 function getDefaultUserOptionOverrides() {
452 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
455 function getExtraUserToggles() {
456 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
459 function getUserToggle( $tog ) {
460 return $this->getMessageFromDB( "tog-$tog" );
464 * Get language names, indexed by code.
465 * If $customisedOnly is true, only returns codes with a messages file
467 public static function getLanguageNames( $customisedOnly = false ) {
468 global $wgLanguageNames, $wgExtraLanguageNames;
469 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
470 if ( !$customisedOnly ) {
476 $dir = opendir( "$IP/languages/messages" );
477 while ( false !== ( $file = readdir( $dir ) ) ) {
478 $code = self
::getCodeFromFileName( $file, 'Messages' );
479 if ( $code && isset( $allNames[$code] ) ) {
480 $names[$code] = $allNames[$code];
488 * Get a message from the MediaWiki namespace.
490 * @param $msg String: message name
493 function getMessageFromDB( $msg ) {
494 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
497 function getLanguageName( $code ) {
498 $names = self
::getLanguageNames();
499 if ( !array_key_exists( $code, $names ) ) {
502 return $names[$code];
505 function getMonthName( $key ) {
506 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
509 function getMonthNameGen( $key ) {
510 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
513 function getMonthAbbreviation( $key ) {
514 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
517 function getWeekdayName( $key ) {
518 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
521 function getWeekdayAbbreviation( $key ) {
522 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
525 function getIranianCalendarMonthName( $key ) {
526 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
529 function getHebrewCalendarMonthName( $key ) {
530 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
533 function getHebrewCalendarMonthNameGen( $key ) {
534 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
537 function getHijriCalendarMonthName( $key ) {
538 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
542 * Used by date() and time() to adjust the time output.
544 * @param $ts Int the time in date('YmdHis') format
545 * @param $tz Mixed: adjust the time by this amount (default false, mean we
546 * get user timecorrection setting)
549 function userAdjust( $ts, $tz = false ) {
550 global $wgUser, $wgLocalTZoffset;
552 if ( $tz === false ) {
553 $tz = $wgUser->getOption( 'timecorrection' );
556 $data = explode( '|', $tz, 3 );
558 if ( $data[0] == 'ZoneInfo' ) {
559 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
560 $date = date_create( $ts, timezone_open( 'UTC' ) );
561 date_timezone_set( $date, timezone_open( $data[2] ) );
562 $date = date_format( $date, 'YmdHis' );
565 # Unrecognized timezone, default to 'Offset' with the stored offset.
570 if ( $data[0] == 'System' ||
$tz == '' ) {
571 # Global offset in minutes.
572 if ( isset( $wgLocalTZoffset ) ) {
573 $minDiff = $wgLocalTZoffset;
575 } else if ( $data[0] == 'Offset' ) {
576 $minDiff = intval( $data[1] );
578 $data = explode( ':', $tz );
579 if ( count( $data ) == 2 ) {
580 $data[0] = intval( $data[0] );
581 $data[1] = intval( $data[1] );
582 $minDiff = abs( $data[0] ) * 60 +
$data[1];
583 if ( $data[0] < 0 ) {
584 $minDiff = -$minDiff;
587 $minDiff = intval( $data[0] ) * 60;
591 # No difference ? Return time unchanged
592 if ( 0 == $minDiff ) {
596 wfSuppressWarnings(); // E_STRICT system time bitching
597 # Generate an adjusted date; take advantage of the fact that mktime
598 # will normalize out-of-range values so we don't have to split $minDiff
599 # into hours and minutes.
601 (int)substr( $ts, 8, 2 ) ), # Hours
602 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
603 (int)substr( $ts, 12, 2 ), # Seconds
604 (int)substr( $ts, 4, 2 ), # Month
605 (int)substr( $ts, 6, 2 ), # Day
606 (int)substr( $ts, 0, 4 ) ); # Year
608 $date = date( 'YmdHis', $t );
615 * This is a workalike of PHP's date() function, but with better
616 * internationalisation, a reduced set of format characters, and a better
619 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
620 * PHP manual for definitions. "o" format character is supported since
621 * PHP 5.1.0, previous versions return literal o.
622 * There are a number of extensions, which start with "x":
624 * xn Do not translate digits of the next numeric format character
625 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
626 * xr Use roman numerals for the next numeric format character
627 * xh Use hebrew numerals for the next numeric format character
629 * xg Genitive month name
631 * xij j (day number) in Iranian calendar
632 * xiF F (month name) in Iranian calendar
633 * xin n (month number) in Iranian calendar
634 * xiY Y (full year) in Iranian calendar
636 * xjj j (day number) in Hebrew calendar
637 * xjF F (month name) in Hebrew calendar
638 * xjt t (days in month) in Hebrew calendar
639 * xjx xg (genitive month name) in Hebrew calendar
640 * xjn n (month number) in Hebrew calendar
641 * xjY Y (full year) in Hebrew calendar
643 * xmj j (day number) in Hijri calendar
644 * xmF F (month name) in Hijri calendar
645 * xmn n (month number) in Hijri calendar
646 * xmY Y (full year) in Hijri calendar
648 * xkY Y (full year) in Thai solar calendar. Months and days are
649 * identical to the Gregorian calendar
650 * xoY Y (full year) in Minguo calendar or Juche year.
651 * Months and days are identical to the
653 * xtY Y (full year) in Japanese nengo. Months and days are
654 * identical to the Gregorian calendar
656 * Characters enclosed in double quotes will be considered literal (with
657 * the quotes themselves removed). Unmatched quotes will be considered
658 * literal quotes. Example:
660 * "The month is" F => The month is January
663 * Backslash escaping is also supported.
665 * Input timestamp is assumed to be pre-normalized to the desired local
668 * @param $format String
669 * @param $ts String: 14-character timestamp
672 * @todo emulation of "o" format character for PHP pre 5.1.0
673 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
675 function sprintfDate( $format, $ts ) {
688 for ( $p = 0; $p < strlen( $format ); $p++
) {
691 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
692 $code .= $format[++
$p];
695 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
696 $code .= $format[++
$p];
707 $rawToggle = !$rawToggle;
716 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
719 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
720 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
723 $num = substr( $ts, 6, 2 );
726 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
727 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
730 $num = intval( substr( $ts, 6, 2 ) );
734 $iranian = self
::tsToIranian( $ts );
740 $hijri = self
::tsToHijri( $ts );
746 $hebrew = self
::tsToHebrew( $ts );
752 $unix = wfTimestamp( TS_UNIX
, $ts );
754 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
758 $unix = wfTimestamp( TS_UNIX
, $ts );
760 $w = gmdate( 'w', $unix );
765 $unix = wfTimestamp( TS_UNIX
, $ts );
767 $num = gmdate( 'w', $unix );
771 $unix = wfTimestamp( TS_UNIX
, $ts );
773 $num = gmdate( 'z', $unix );
777 $unix = wfTimestamp( TS_UNIX
, $ts );
779 $num = gmdate( 'W', $unix );
782 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
786 $iranian = self
::tsToIranian( $ts );
788 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
792 $hijri = self
::tsToHijri( $ts );
794 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
798 $hebrew = self
::tsToHebrew( $ts );
800 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
803 $num = substr( $ts, 4, 2 );
806 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
809 $num = intval( substr( $ts, 4, 2 ) );
813 $iranian = self
::tsToIranian( $ts );
819 $hijri = self
::tsToHijri ( $ts );
825 $hebrew = self
::tsToHebrew( $ts );
831 $unix = wfTimestamp( TS_UNIX
, $ts );
833 $num = gmdate( 't', $unix );
837 $hebrew = self
::tsToHebrew( $ts );
843 $unix = wfTimestamp( TS_UNIX
, $ts );
845 $num = gmdate( 'L', $unix );
847 # 'o' is supported since PHP 5.1.0
848 # return literal if not supported
849 # TODO: emulation for pre 5.1.0 versions
852 $unix = wfTimestamp( TS_UNIX
, $ts );
854 if ( version_compare( PHP_VERSION
, '5.1.0' ) === 1 ) {
855 $num = date( 'o', $unix );
861 $num = substr( $ts, 0, 4 );
865 $iranian = self
::tsToIranian( $ts );
871 $hijri = self
::tsToHijri( $ts );
877 $hebrew = self
::tsToHebrew( $ts );
883 $thai = self
::tsToYear( $ts, 'thai' );
889 $minguo = self
::tsToYear( $ts, 'minguo' );
895 $tenno = self
::tsToYear( $ts, 'tenno' );
900 $num = substr( $ts, 2, 2 );
903 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
906 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
909 $h = substr( $ts, 8, 2 );
910 $num = $h %
12 ?
$h %
12 : 12;
913 $num = intval( substr( $ts, 8, 2 ) );
916 $h = substr( $ts, 8, 2 );
917 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
920 $num = substr( $ts, 8, 2 );
923 $num = substr( $ts, 10, 2 );
926 $num = substr( $ts, 12, 2 );
930 $unix = wfTimestamp( TS_UNIX
, $ts );
932 $s .= gmdate( 'c', $unix );
936 $unix = wfTimestamp( TS_UNIX
, $ts );
938 $s .= gmdate( 'r', $unix );
942 $unix = wfTimestamp( TS_UNIX
, $ts );
948 if ( $p < strlen( $format ) - 1 ) {
956 if ( $p < strlen( $format ) - 1 ) {
957 $endQuote = strpos( $format, '"', $p +
1 );
958 if ( $endQuote === false ) {
959 # No terminating quote, assume literal "
962 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
966 # Quote at end of string, assume literal "
973 if ( $num !== false ) {
974 if ( $rawToggle ||
$raw ) {
977 } elseif ( $roman ) {
978 $s .= self
::romanNumeral( $num );
980 } elseif ( $hebrewNum ) {
981 $s .= self
::hebrewNumeral( $num );
984 $s .= $this->formatNum( $num, true );
992 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
993 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
995 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
996 * Gregorian dates to Iranian dates. Originally written in C, it
997 * is released under the terms of GNU Lesser General Public
998 * License. Conversion to PHP was performed by Niklas Laxström.
1000 * Link: http://www.farsiweb.info/jalali/jalali.c
1002 private static function tsToIranian( $ts ) {
1003 $gy = substr( $ts, 0, 4 ) -1600;
1004 $gm = substr( $ts, 4, 2 ) -1;
1005 $gd = substr( $ts, 6, 2 ) -1;
1007 # Days passed from the beginning (including leap years)
1009 +
floor( ( $gy +
3 ) / 4 )
1010 - floor( ( $gy +
99 ) / 100 )
1011 +
floor( ( $gy +
399 ) / 400 );
1014 // Add days of the past months of this year
1015 for ( $i = 0; $i < $gm; $i++
) {
1016 $gDayNo +
= self
::$GREG_DAYS[$i];
1020 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1024 // Days passed in current month
1027 $jDayNo = $gDayNo - 79;
1029 $jNp = floor( $jDayNo / 12053 );
1032 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1035 if ( $jDayNo >= 366 ) {
1036 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1037 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1040 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1041 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1047 return array( $jy, $jm, $jd );
1051 * Converting Gregorian dates to Hijri dates.
1053 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1055 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1057 private static function tsToHijri( $ts ) {
1058 $year = substr( $ts, 0, 4 );
1059 $month = substr( $ts, 4, 2 );
1060 $day = substr( $ts, 6, 2 );
1068 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1069 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1072 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1073 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1074 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1077 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1078 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1081 $zl = $zjd -1948440 +
10632;
1082 $zn = (int)( ( $zl - 1 ) / 10631 );
1083 $zl = $zl - 10631 * $zn +
354;
1084 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1085 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1086 $zm = (int)( ( 24 * $zl ) / 709 );
1087 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1088 $zy = 30 * $zn +
$zj - 30;
1090 return array( $zy, $zm, $zd );
1094 * Converting Gregorian dates to Hebrew dates.
1096 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1097 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1098 * to translate the relevant functions into PHP and release them under
1101 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1102 * and Adar II is 14. In a non-leap year, Adar is 6.
1104 private static function tsToHebrew( $ts ) {
1106 $year = substr( $ts, 0, 4 );
1107 $month = substr( $ts, 4, 2 );
1108 $day = substr( $ts, 6, 2 );
1110 # Calculate Hebrew year
1111 $hebrewYear = $year +
3760;
1113 # Month number when September = 1, August = 12
1115 if ( $month > 12 ) {
1122 # Calculate day of year from 1 September
1124 for ( $i = 1; $i < $month; $i++
) {
1128 # Check if the year is leap
1129 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1132 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1139 # Calculate the start of the Hebrew year
1140 $start = self
::hebrewYearStart( $hebrewYear );
1142 # Calculate next year's start
1143 if ( $dayOfYear <= $start ) {
1144 # Day is before the start of the year - it is the previous year
1146 $nextStart = $start;
1150 # Add days since previous year's 1 September
1152 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1156 # Start of the new (previous) year
1157 $start = self
::hebrewYearStart( $hebrewYear );
1160 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1163 # Calculate Hebrew day of year
1164 $hebrewDayOfYear = $dayOfYear - $start;
1166 # Difference between year's days
1167 $diff = $nextStart - $start;
1168 # Add 12 (or 13 for leap years) days to ignore the difference between
1169 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1170 # difference is only about the year type
1171 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1177 # Check the year pattern, and is leap year
1178 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1179 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1180 # and non-leap years
1181 $yearPattern = $diff %
30;
1182 # Check if leap year
1183 $isLeap = $diff >= 30;
1185 # Calculate day in the month from number of day in the Hebrew year
1186 # Don't check Adar - if the day is not in Adar, we will stop before;
1187 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1188 $hebrewDay = $hebrewDayOfYear;
1191 while ( $hebrewMonth <= 12 ) {
1192 # Calculate days in this month
1193 if ( $isLeap && $hebrewMonth == 6 ) {
1194 # Adar in a leap year
1196 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1198 if ( $hebrewDay <= $days ) {
1202 # Subtract the days of Adar I
1203 $hebrewDay -= $days;
1206 if ( $hebrewDay <= $days ) {
1212 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1213 # Cheshvan in a complete year (otherwise as the rule below)
1215 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1216 # Kislev in an incomplete year (otherwise as the rule below)
1219 # Odd months have 30 days, even have 29
1220 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1222 if ( $hebrewDay <= $days ) {
1223 # In the current month
1226 # Subtract the days of the current month
1227 $hebrewDay -= $days;
1228 # Try in the next month
1233 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1237 * This calculates the Hebrew year start, as days since 1 September.
1238 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1239 * Used for Hebrew date.
1241 private static function hebrewYearStart( $year ) {
1242 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1243 $b = intval( ( $year - 1 ) %
4 );
1244 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1248 $Mar = intval( $m );
1254 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1255 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1257 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1259 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1263 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1268 * Algorithm to convert Gregorian dates to Thai solar dates,
1269 * Minguo dates or Minguo dates.
1271 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1272 * http://en.wikipedia.org/wiki/Minguo_calendar
1273 * http://en.wikipedia.org/wiki/Japanese_era_name
1275 * @param $ts String: 14-character timestamp
1276 * @param $cName String: calender name
1277 * @return Array: converted year, month, day
1279 private static function tsToYear( $ts, $cName ) {
1280 $gy = substr( $ts, 0, 4 );
1281 $gm = substr( $ts, 4, 2 );
1282 $gd = substr( $ts, 6, 2 );
1284 if ( !strcmp( $cName, 'thai' ) ) {
1286 # Add 543 years to the Gregorian calendar
1287 # Months and days are identical
1288 $gy_offset = $gy +
543;
1289 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1291 # Deduct 1911 years from the Gregorian calendar
1292 # Months and days are identical
1293 $gy_offset = $gy - 1911;
1294 } else if ( !strcmp( $cName, 'tenno' ) ) {
1295 # Nengō dates up to Meiji period
1296 # Deduct years from the Gregorian calendar
1297 # depending on the nengo periods
1298 # Months and days are identical
1299 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1301 $gy_gannen = $gy - 1868 +
1;
1302 $gy_offset = $gy_gannen;
1303 if ( $gy_gannen == 1 ) {
1306 $gy_offset = '明治' . $gy_offset;
1308 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1309 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1310 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1311 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1312 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1316 $gy_gannen = $gy - 1912 +
1;
1317 $gy_offset = $gy_gannen;
1318 if ( $gy_gannen == 1 ) {
1321 $gy_offset = '大正' . $gy_offset;
1323 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1324 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1325 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1329 $gy_gannen = $gy - 1926 +
1;
1330 $gy_offset = $gy_gannen;
1331 if ( $gy_gannen == 1 ) {
1334 $gy_offset = '昭和' . $gy_offset;
1337 $gy_gannen = $gy - 1989 +
1;
1338 $gy_offset = $gy_gannen;
1339 if ( $gy_gannen == 1 ) {
1342 $gy_offset = '平成' . $gy_offset;
1348 return array( $gy_offset, $gm, $gd );
1352 * Roman number formatting up to 3000
1354 static function romanNumeral( $num ) {
1355 static $table = array(
1356 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1357 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1358 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1359 array( '', 'M', 'MM', 'MMM' )
1362 $num = intval( $num );
1363 if ( $num > 3000 ||
$num <= 0 ) {
1368 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1369 if ( $num >= $pow10 ) {
1370 $s .= $table[$i][floor( $num / $pow10 )];
1372 $num = $num %
$pow10;
1378 * Hebrew Gematria number formatting up to 9999
1380 static function hebrewNumeral( $num ) {
1381 static $table = array(
1382 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1383 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1384 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1385 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1388 $num = intval( $num );
1389 if ( $num > 9999 ||
$num <= 0 ) {
1394 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1395 if ( $num >= $pow10 ) {
1396 if ( $num == 15 ||
$num == 16 ) {
1397 $s .= $table[0][9] . $table[0][$num - 9];
1400 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1401 if ( $pow10 == 1000 ) {
1406 $num = $num %
$pow10;
1408 if ( strlen( $s ) == 2 ) {
1411 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1412 $str .= substr( $s, strlen( $s ) - 2, 2 );
1414 $start = substr( $str, 0, strlen( $str ) - 2 );
1415 $end = substr( $str, strlen( $str ) - 2 );
1418 $str = $start . 'ך';
1421 $str = $start . 'ם';
1424 $str = $start . 'ן';
1427 $str = $start . 'ף';
1430 $str = $start . 'ץ';
1437 * This is meant to be used by time(), date(), and timeanddate() to get
1438 * the date preference they're supposed to use, it should be used in
1442 * function timeanddate([...], $format = true) {
1443 * $datePreference = $this->dateFormat($format);
1448 * @param $usePrefs Mixed: if true, the user's preference is used
1449 * if false, the site/language default is used
1450 * if int/string, assumed to be a format.
1453 function dateFormat( $usePrefs = true ) {
1456 if ( is_bool( $usePrefs ) ) {
1458 $datePreference = $wgUser->getDatePreference();
1460 $datePreference = (string)User
::getDefaultOption( 'date' );
1463 $datePreference = (string)$usePrefs;
1467 if ( $datePreference == '' ) {
1471 return $datePreference;
1475 * Get a format string for a given type and preference
1476 * @param $type May be date, time or both
1477 * @param $pref The format name as it appears in Messages*.php
1479 function getDateFormatString( $type, $pref ) {
1480 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1481 if ( $pref == 'default' ) {
1482 $pref = $this->getDefaultDateFormat();
1483 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1485 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1486 if ( is_null( $df ) ) {
1487 $pref = $this->getDefaultDateFormat();
1488 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1491 $this->dateFormatStrings
[$type][$pref] = $df;
1493 return $this->dateFormatStrings
[$type][$pref];
1497 * @param $ts Mixed: the time format which needs to be turned into a
1498 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1499 * @param $adj Bool: whether to adjust the time output according to the
1500 * user configured offset ($timecorrection)
1501 * @param $format Mixed: true to use user's date format preference
1502 * @param $timecorrection String: the time offset as returned by
1503 * validateTimeZone() in Special:Preferences
1506 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1508 $ts = $this->userAdjust( $ts, $timecorrection );
1510 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1511 return $this->sprintfDate( $df, $ts );
1515 * @param $ts Mixed: the time format which needs to be turned into a
1516 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1517 * @param $adj Bool: whether to adjust the time output according to the
1518 * user configured offset ($timecorrection)
1519 * @param $format Mixed: true to use user's date format preference
1520 * @param $timecorrection String: the time offset as returned by
1521 * validateTimeZone() in Special:Preferences
1524 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1526 $ts = $this->userAdjust( $ts, $timecorrection );
1528 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1529 return $this->sprintfDate( $df, $ts );
1533 * @param $ts Mixed: the time format which needs to be turned into a
1534 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1535 * @param $adj Bool: whether to adjust the time output according to the
1536 * user configured offset ($timecorrection)
1537 * @param $format Mixed: what format to return, if it's false output the
1538 * default one (default true)
1539 * @param $timecorrection String: the time offset as returned by
1540 * validateTimeZone() in Special:Preferences
1543 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1544 $ts = wfTimestamp( TS_MW
, $ts );
1546 $ts = $this->userAdjust( $ts, $timecorrection );
1548 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1549 return $this->sprintfDate( $df, $ts );
1552 function getMessage( $key ) {
1553 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1556 function getAllMessages() {
1557 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1560 function iconv( $in, $out, $string ) {
1561 # This is a wrapper for iconv in all languages except esperanto,
1562 # which does some nasty x-conversions beforehand
1564 # Even with //IGNORE iconv can whine about illegal characters in
1565 # *input* string. We just ignore those too.
1566 # REF: http://bugs.php.net/bug.php?id=37166
1567 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1568 wfSuppressWarnings();
1569 $text = iconv( $in, $out . '//IGNORE', $string );
1570 wfRestoreWarnings();
1574 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1575 function ucwordbreaksCallbackAscii( $matches ) {
1576 return $this->ucfirst( $matches[1] );
1579 function ucwordbreaksCallbackMB( $matches ) {
1580 return mb_strtoupper( $matches[0] );
1583 function ucCallback( $matches ) {
1584 list( $wikiUpperChars ) = self
::getCaseMaps();
1585 return strtr( $matches[1], $wikiUpperChars );
1588 function lcCallback( $matches ) {
1589 list( , $wikiLowerChars ) = self
::getCaseMaps();
1590 return strtr( $matches[1], $wikiLowerChars );
1593 function ucwordsCallbackMB( $matches ) {
1594 return mb_strtoupper( $matches[0] );
1597 function ucwordsCallbackWiki( $matches ) {
1598 list( $wikiUpperChars ) = self
::getCaseMaps();
1599 return strtr( $matches[0], $wikiUpperChars );
1602 function ucfirst( $str ) {
1606 } elseif ( $o < 128 ) {
1607 return ucfirst( $str );
1609 // fall back to more complex logic in case of multibyte strings
1610 return $this->uc( $str, true );
1614 function uc( $str, $first = false ) {
1615 if ( function_exists( 'mb_strtoupper' ) ) {
1617 if ( $this->isMultibyte( $str ) ) {
1618 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1620 return ucfirst( $str );
1623 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1626 if ( $this->isMultibyte( $str ) ) {
1627 $x = $first ?
'^' : '';
1628 return preg_replace_callback(
1629 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1630 array( $this, 'ucCallback' ),
1634 return $first ?
ucfirst( $str ) : strtoupper( $str );
1639 function lcfirst( $str ) {
1642 return strval( $str );
1643 } elseif ( $o >= 128 ) {
1644 return $this->lc( $str, true );
1645 } elseif ( $o > 96 ) {
1648 $str[0] = strtolower( $str[0] );
1653 function lc( $str, $first = false ) {
1654 if ( function_exists( 'mb_strtolower' ) ) {
1656 if ( $this->isMultibyte( $str ) ) {
1657 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1659 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1662 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1665 if ( $this->isMultibyte( $str ) ) {
1666 $x = $first ?
'^' : '';
1667 return preg_replace_callback(
1668 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1669 array( $this, 'lcCallback' ),
1673 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1678 function isMultibyte( $str ) {
1679 return (bool)preg_match( '/[\x80-\xff]/', $str );
1682 function ucwords( $str ) {
1683 if ( $this->isMultibyte( $str ) ) {
1684 $str = $this->lc( $str );
1686 // regexp to find first letter in each word (i.e. after each space)
1687 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1689 // function to use to capitalize a single char
1690 if ( function_exists( 'mb_strtoupper' ) ) {
1691 return preg_replace_callback(
1693 array( $this, 'ucwordsCallbackMB' ),
1697 return preg_replace_callback(
1699 array( $this, 'ucwordsCallbackWiki' ),
1704 return ucwords( strtolower( $str ) );
1708 # capitalize words at word breaks
1709 function ucwordbreaks( $str ) {
1710 if ( $this->isMultibyte( $str ) ) {
1711 $str = $this->lc( $str );
1713 // since \b doesn't work for UTF-8, we explicitely define word break chars
1714 $breaks = "[ \-\(\)\}\{\.,\?!]";
1716 // find first letter after word break
1717 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1719 if ( function_exists( 'mb_strtoupper' ) ) {
1720 return preg_replace_callback(
1722 array( $this, 'ucwordbreaksCallbackMB' ),
1726 return preg_replace_callback(
1728 array( $this, 'ucwordsCallbackWiki' ),
1733 return preg_replace_callback(
1734 '/\b([\w\x80-\xff]+)\b/',
1735 array( $this, 'ucwordbreaksCallbackAscii' ),
1742 * Return a case-folded representation of $s
1744 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1745 * and $s2 are the same except for the case of their characters. It is not
1746 * necessary for the value returned to make sense when displayed.
1748 * Do *not* perform any other normalisation in this function. If a caller
1749 * uses this function when it should be using a more general normalisation
1750 * function, then fix the caller.
1752 function caseFold( $s ) {
1753 return $this->uc( $s );
1756 function checkTitleEncoding( $s ) {
1757 if ( is_array( $s ) ) {
1758 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1760 # Check for non-UTF-8 URLs
1761 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1766 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1767 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1772 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1775 function fallback8bitEncoding() {
1776 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1780 * Most writing systems use whitespace to break up words.
1781 * Some languages such as Chinese don't conventionally do this,
1782 * which requires special handling when breaking up words for
1785 function hasWordBreaks() {
1790 * Some languages such as Chinese require word segmentation,
1791 * Specify such segmentation when overridden in derived class.
1793 * @param $string String
1796 function segmentByWord( $string ) {
1801 * Some languages have special punctuation need to be normalized.
1802 * Make such changes here.
1804 * @param $string String
1807 function normalizeForSearch( $string ) {
1808 return self
::convertDoubleWidth( $string );
1812 * convert double-width roman characters to single-width.
1813 * range: ff00-ff5f ~= 0020-007f
1815 protected static function convertDoubleWidth( $string ) {
1816 static $full = null;
1817 static $half = null;
1819 if ( $full === null ) {
1820 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1821 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1822 $full = str_split( $fullWidth, 3 );
1823 $half = str_split( $halfWidth );
1826 $string = str_replace( $full, $half, $string );
1830 protected static function insertSpace( $string, $pattern ) {
1831 $string = preg_replace( $pattern, " $1 ", $string );
1832 $string = preg_replace( '/ +/', ' ', $string );
1836 function convertForSearchResult( $termsArray ) {
1837 # some languages, e.g. Chinese, need to do a conversion
1838 # in order for search results to be displayed correctly
1843 * Get the first character of a string.
1848 function firstChar( $s ) {
1851 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1852 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1857 if ( isset( $matches[1] ) ) {
1858 if ( strlen( $matches[1] ) != 3 ) {
1862 // Break down Hangul syllables to grab the first jamo
1863 $code = utf8ToCodepoint( $matches[1] );
1864 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1866 } elseif ( $code < 0xb098 ) {
1867 return "\xe3\x84\xb1";
1868 } elseif ( $code < 0xb2e4 ) {
1869 return "\xe3\x84\xb4";
1870 } elseif ( $code < 0xb77c ) {
1871 return "\xe3\x84\xb7";
1872 } elseif ( $code < 0xb9c8 ) {
1873 return "\xe3\x84\xb9";
1874 } elseif ( $code < 0xbc14 ) {
1875 return "\xe3\x85\x81";
1876 } elseif ( $code < 0xc0ac ) {
1877 return "\xe3\x85\x82";
1878 } elseif ( $code < 0xc544 ) {
1879 return "\xe3\x85\x85";
1880 } elseif ( $code < 0xc790 ) {
1881 return "\xe3\x85\x87";
1882 } elseif ( $code < 0xcc28 ) {
1883 return "\xe3\x85\x88";
1884 } elseif ( $code < 0xce74 ) {
1885 return "\xe3\x85\x8a";
1886 } elseif ( $code < 0xd0c0 ) {
1887 return "\xe3\x85\x8b";
1888 } elseif ( $code < 0xd30c ) {
1889 return "\xe3\x85\x8c";
1890 } elseif ( $code < 0xd558 ) {
1891 return "\xe3\x85\x8d";
1893 return "\xe3\x85\x8e";
1900 function initEncoding() {
1901 # Some languages may have an alternate char encoding option
1902 # (Esperanto X-coding, Japanese furigana conversion, etc)
1903 # If this language is used as the primary content language,
1904 # an override to the defaults can be set here on startup.
1907 function recodeForEdit( $s ) {
1908 # For some languages we'll want to explicitly specify
1909 # which characters make it into the edit box raw
1910 # or are converted in some way or another.
1911 # Note that if wgOutputEncoding is different from
1912 # wgInputEncoding, this text will be further converted
1913 # to wgOutputEncoding.
1914 global $wgEditEncoding;
1915 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1918 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1922 function recodeInput( $s ) {
1923 # Take the previous into account.
1924 global $wgEditEncoding;
1925 if ( $wgEditEncoding != '' ) {
1926 $enc = $wgEditEncoding;
1930 if ( $enc == 'UTF-8' ) {
1933 return $this->iconv( $enc, 'UTF-8', $s );
1938 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1939 * also cleans up certain backwards-compatible sequences, converting them
1940 * to the modern Unicode equivalent.
1942 * This is language-specific for performance reasons only.
1944 function normalize( $s ) {
1945 global $wgAllUnicodeFixes;
1946 $s = UtfNormal
::cleanUp( $s );
1947 if ( $wgAllUnicodeFixes ) {
1948 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1949 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1956 * Transform a string using serialized data stored in the given file (which
1957 * must be in the serialized subdirectory of $IP). The file contains pairs
1958 * mapping source characters to destination characters.
1960 * The data is cached in process memory. This will go faster if you have the
1961 * FastStringSearch extension.
1963 function transformUsingPairFile( $file, $string ) {
1964 if ( !isset( $this->transformData
[$file] ) ) {
1965 $data = wfGetPrecompiledData( $file );
1966 if ( $data === false ) {
1967 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1969 $this->transformData
[$file] = new ReplacementArray( $data );
1971 return $this->transformData
[$file]->replace( $string );
1975 * For right-to-left language support
1980 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1984 * Return the correct HTML 'dir' attribute value for this language.
1988 return $this->isRTL() ?
'rtl' : 'ltr';
1992 * Return 'left' or 'right' as appropriate alignment for line-start
1993 * for this language's text direction.
1995 * Should be equivalent to CSS3 'start' text-align value....
1999 function alignStart() {
2000 return $this->isRTL() ?
'right' : 'left';
2004 * Return 'right' or 'left' as appropriate alignment for line-end
2005 * for this language's text direction.
2007 * Should be equivalent to CSS3 'end' text-align value....
2011 function alignEnd() {
2012 return $this->isRTL() ?
'left' : 'right';
2016 * A hidden direction mark (LRM or RLM), depending on the language direction
2020 function getDirMark() {
2021 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2024 function capitalizeAllNouns() {
2025 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2029 * An arrow, depending on the language direction
2033 function getArrow() {
2034 return $this->isRTL() ?
'←' : '→';
2038 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2042 function linkPrefixExtension() {
2043 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2046 function getMagicWords() {
2047 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2050 # Fill a MagicWord object with data from here
2051 function getMagic( $mw ) {
2052 if ( !$this->mMagicHookDone
) {
2053 $this->mMagicHookDone
= true;
2054 wfProfileIn( 'LanguageGetMagic' );
2055 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2056 wfProfileOut( 'LanguageGetMagic' );
2058 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2059 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2061 $magicWords = $this->getMagicWords();
2062 if ( isset( $magicWords[$mw->mId
] ) ) {
2063 $rawEntry = $magicWords[$mw->mId
];
2069 if ( !is_array( $rawEntry ) ) {
2070 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2072 $mw->mCaseSensitive
= $rawEntry[0];
2073 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2078 * Add magic words to the extension array
2080 function addMagicWordsByLang( $newWords ) {
2081 $code = $this->getCode();
2082 $fallbackChain = array();
2083 while ( $code && !in_array( $code, $fallbackChain ) ) {
2084 $fallbackChain[] = $code;
2085 $code = self
::getFallbackFor( $code );
2087 if ( !in_array( 'en', $fallbackChain ) ) {
2088 $fallbackChain[] = 'en';
2090 $fallbackChain = array_reverse( $fallbackChain );
2091 foreach ( $fallbackChain as $code ) {
2092 if ( isset( $newWords[$code] ) ) {
2093 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2099 * Get special page names, as an associative array
2100 * case folded alias => real name
2102 function getSpecialPageAliases() {
2103 // Cache aliases because it may be slow to load them
2104 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2106 $this->mExtendedSpecialPageAliases
=
2107 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2108 wfRunHooks( 'LanguageGetSpecialPageAliases',
2109 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2112 return $this->mExtendedSpecialPageAliases
;
2116 * Italic is unsuitable for some languages
2118 * @param $text String: the text to be emphasized.
2121 function emphasize( $text ) {
2122 return "<em>$text</em>";
2126 * Normally we output all numbers in plain en_US style, that is
2127 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2128 * point twohundredthirtyfive. However this is not sutable for all
2129 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2130 * Icelandic just want to use commas instead of dots, and dots instead
2131 * of commas like "293.291,235".
2133 * An example of this function being called:
2135 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2138 * See LanguageGu.php for the Gujarati implementation and
2139 * $separatorTransformTable on MessageIs.php for
2140 * the , => . and . => , implementation.
2142 * @todo check if it's viable to use localeconv() for the decimal
2144 * @param $number Mixed: the string to be formatted, should be an integer
2145 * or a floating point number.
2146 * @param $nocommafy Bool: set to true for special numbers like dates
2149 function formatNum( $number, $nocommafy = false ) {
2150 global $wgTranslateNumerals;
2151 if ( !$nocommafy ) {
2152 $number = $this->commafy( $number );
2153 $s = $this->separatorTransformTable();
2155 $number = strtr( $number, $s );
2159 if ( $wgTranslateNumerals ) {
2160 $s = $this->digitTransformTable();
2162 $number = strtr( $number, $s );
2169 function parseFormattedNumber( $number ) {
2170 $s = $this->digitTransformTable();
2172 $number = strtr( $number, array_flip( $s ) );
2175 $s = $this->separatorTransformTable();
2177 $number = strtr( $number, array_flip( $s ) );
2180 $number = strtr( $number, array( ',' => '' ) );
2185 * Adds commas to a given number
2190 function commafy( $_ ) {
2191 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2194 function digitTransformTable() {
2195 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2198 function separatorTransformTable() {
2199 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2203 * Take a list of strings and build a locale-friendly comma-separated
2204 * list, using the local comma-separator message.
2205 * The last two strings are chained with an "and".
2210 function listToText( $l ) {
2212 $m = count( $l ) - 1;
2214 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2216 for ( $i = $m; $i >= 0; $i-- ) {
2219 } else if ( $i == $m - 1 ) {
2220 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2222 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2230 * Take a list of strings and build a locale-friendly comma-separated
2231 * list, using the local comma-separator message.
2232 * @param $list array of strings to put in a comma list
2235 function commaList( $list ) {
2240 array( 'parsemag', 'escapenoentities', 'language' => $this )
2246 * Take a list of strings and build a locale-friendly semicolon-separated
2247 * list, using the local semicolon-separator message.
2248 * @param $list array of strings to put in a semicolon list
2251 function semicolonList( $list ) {
2255 'semicolon-separator',
2256 array( 'parsemag', 'escapenoentities', 'language' => $this )
2262 * Same as commaList, but separate it with the pipe instead.
2263 * @param $list array of strings to put in a pipe list
2266 function pipeList( $list ) {
2271 array( 'escapenoentities', 'language' => $this )
2277 * Truncate a string to a specified length in bytes, appending an optional
2278 * string (e.g. for ellipses)
2280 * The database offers limited byte lengths for some columns in the database;
2281 * multi-byte character sets mean we need to ensure that only whole characters
2282 * are included, otherwise broken characters can be passed to the user
2284 * If $length is negative, the string will be truncated from the beginning
2286 * @param $string String to truncate
2287 * @param $length Int: maximum length (excluding ellipses)
2288 * @param $ellipsis String to append to the truncated text
2291 function truncate( $string, $length, $ellipsis = '...' ) {
2292 # Use the localized ellipsis character
2293 if ( $ellipsis == '...' ) {
2294 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2296 # Check if there is no need to truncate
2297 if ( $length == 0 ) {
2299 } elseif ( strlen( $string ) <= abs( $length ) ) {
2302 $stringOriginal = $string;
2303 if ( $length > 0 ) {
2304 $string = substr( $string, 0, $length ); // xyz...
2305 $string = $this->removeBadCharLast( $string );
2306 $string = $string . $ellipsis;
2308 $string = substr( $string, $length ); // ...xyz
2309 $string = $this->removeBadCharFirst( $string );
2310 $string = $ellipsis . $string;
2312 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2313 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2316 return $stringOriginal;
2321 * Remove bytes that represent an incomplete Unicode character
2322 * at the end of string (e.g. bytes of the char are missing)
2324 * @param $string String
2327 protected function removeBadCharLast( $string ) {
2328 $char = ord( $string[strlen( $string ) - 1] );
2330 if ( $char >= 0xc0 ) {
2331 # We got the first byte only of a multibyte char; remove it.
2332 $string = substr( $string, 0, -1 );
2333 } elseif ( $char >= 0x80 &&
2334 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2335 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2337 # We chopped in the middle of a character; remove it
2344 * Remove bytes that represent an incomplete Unicode character
2345 * at the start of string (e.g. bytes of the char are missing)
2347 * @param $string String
2350 protected function removeBadCharFirst( $string ) {
2351 $char = ord( $string[0] );
2352 if ( $char >= 0x80 && $char < 0xc0 ) {
2353 # We chopped in the middle of a character; remove the whole thing
2354 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2360 * Truncate a string of valid HTML to a specified length in bytes,
2361 * appending an optional string (e.g. for ellipses), and return valid HTML
2363 * This is only intended for styled/linked text, such as HTML with
2364 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2366 * Note: tries to fix broken HTML with MWTidy
2368 * @param string $text String to truncate
2369 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2370 * @param string $ellipsis String to append to the truncated text
2373 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2374 # Use the localized ellipsis character
2375 if ( $ellipsis == '...' ) {
2376 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2378 # Check if there is no need to truncate
2379 if ( $length <= 0 ) {
2380 return $ellipsis; // no text shown, nothing to format
2381 } elseif ( strlen( $text ) <= $length ) {
2382 return $text; // string short enough even *with* HTML
2384 $text = MWTidy
::tidy( $text ); // fix tags
2385 $displayLen = 0; // innerHTML legth so far
2386 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2387 $tagType = 0; // 0-open, 1-close
2388 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2389 $entityState = 0; // 0-not entity, 1-entity
2390 $tag = $ret = $ch = '';
2391 $openTags = array();
2392 $textLen = strlen( $text );
2393 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2395 $lastCh = $pos ?
$text[$pos - 1] : '';
2396 $ret .= $ch; // add to result string
2398 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2399 $entityState = 0; // for bad HTML
2400 $bracketState = 1; // tag started (checking for backslash)
2401 } elseif ( $ch == '>' ) {
2402 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2403 $entityState = 0; // for bad HTML
2404 $bracketState = 0; // out of brackets
2405 } elseif ( $bracketState == 1 ) {
2407 $tagType = 1; // close tag (e.g. "</span>")
2409 $tagType = 0; // open tag (e.g. "<span>")
2412 $bracketState = 2; // building tag name
2413 } elseif ( $bracketState == 2 ) {
2417 // Name found (e.g. "<a href=..."), add on tag attributes...
2418 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2420 } elseif ( $bracketState == 0 ) {
2421 if ( $entityState ) {
2424 $displayLen++
; // entity is one displayed char
2428 $entityState = 1; // entity found, (e.g. " ")
2430 $displayLen++
; // this char is displayed
2431 // Add on the other display text after this...
2432 $skipped = $this->truncate_skip(
2433 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2434 $displayLen +
= $skipped;
2439 # Consider truncation once the display length has reached the maximim.
2440 # Double-check that we're not in the middle of a bracket/entity...
2441 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2442 if ( !$testingEllipsis ) {
2443 $testingEllipsis = true;
2444 # Save where we are; we will truncate here unless
2445 # the ellipsis actually makes the string longer.
2446 $pOpenTags = $openTags; // save state
2447 $pRet = $ret; // save state
2448 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2449 # Ellipsis won't make string longer/equal, the truncation point was OK.
2450 $openTags = $pOpenTags; // reload state
2451 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2452 $ret .= $ellipsis; // add ellipsis
2457 if ( $displayLen == 0 ) {
2458 return ''; // no text shown, nothing to format
2460 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
2461 while ( count( $openTags ) > 0 ) {
2462 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2467 // truncateHtml() helper function
2468 // like strcspn() but adds the skipped chars to $ret
2469 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2471 if ( $start < strlen( $text ) ) {
2472 $skipCount = strcspn( $text, $search, $start, $len );
2473 $ret .= substr( $text, $start, $skipCount );
2478 // truncateHtml() helper function
2479 // (a) push or pop $tag from $openTags as needed
2480 // (b) clear $tag value
2481 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2482 $tag = ltrim( $tag );
2484 if ( $tagType == 0 && $lastCh != '/' ) {
2485 $openTags[] = $tag; // tag opened (didn't close itself)
2486 } else if ( $tagType == 1 ) {
2487 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2488 array_pop( $openTags ); // tag closed
2496 * Grammatical transformations, needed for inflected languages
2497 * Invoked by putting {{grammar:case|word}} in a message
2499 * @param $word string
2500 * @param $case string
2503 function convertGrammar( $word, $case ) {
2504 global $wgGrammarForms;
2505 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2506 return $wgGrammarForms[$this->getCode()][$case][$word];
2512 * Provides an alternative text depending on specified gender.
2513 * Usage {{gender:username|masculine|feminine|neutral}}.
2514 * username is optional, in which case the gender of current user is used,
2515 * but only in (some) interface messages; otherwise default gender is used.
2516 * If second or third parameter are not specified, masculine is used.
2517 * These details may be overriden per language.
2519 function gender( $gender, $forms ) {
2520 if ( !count( $forms ) ) {
2523 $forms = $this->preConvertPlural( $forms, 2 );
2524 if ( $gender === 'male' ) {
2527 if ( $gender === 'female' ) {
2530 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2534 * Plural form transformations, needed for some languages.
2535 * For example, there are 3 form of plural in Russian and Polish,
2536 * depending on "count mod 10". See [[w:Plural]]
2537 * For English it is pretty simple.
2539 * Invoked by putting {{plural:count|wordform1|wordform2}}
2540 * or {{plural:count|wordform1|wordform2|wordform3}}
2542 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2544 * @param $count Integer: non-localized number
2545 * @param $forms Array: different plural forms
2546 * @return string Correct form of plural for $count in this language
2548 function convertPlural( $count, $forms ) {
2549 if ( !count( $forms ) ) {
2552 $forms = $this->preConvertPlural( $forms, 2 );
2554 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2558 * Checks that convertPlural was given an array and pads it to requested
2559 * amound of forms by copying the last one.
2561 * @param $count Integer: How many forms should there be at least
2562 * @param $forms Array of forms given to convertPlural
2563 * @return array Padded array of forms or an exception if not an array
2565 protected function preConvertPlural( /* Array */ $forms, $count ) {
2566 while ( count( $forms ) < $count ) {
2567 $forms[] = $forms[count( $forms ) - 1];
2573 * For translating of expiry times
2574 * @param $str String: the validated block time in English
2575 * @return Somehow translated block time
2576 * @see LanguageFi.php for example implementation
2578 function translateBlockExpiry( $str ) {
2579 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2581 if ( $scBlockExpiryOptions == '-' ) {
2585 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2586 if ( strpos( $option, ':' ) === false ) {
2589 list( $show, $value ) = explode( ':', $option );
2590 if ( strcmp( $str, $value ) == 0 ) {
2591 return htmlspecialchars( trim( $show ) );
2599 * languages like Chinese need to be segmented in order for the diff
2602 * @param $text String
2605 function segmentForDiff( $text ) {
2610 * and unsegment to show the result
2612 * @param $text String
2615 function unsegmentForDiff( $text ) {
2619 # convert text to all supported variants
2620 function autoConvertToAllVariants( $text ) {
2621 return $this->mConverter
->autoConvertToAllVariants( $text );
2624 # convert text to different variants of a language.
2625 function convert( $text ) {
2626 return $this->mConverter
->convert( $text );
2629 # Convert a Title object to a string in the preferred variant
2630 function convertTitle( $title ) {
2631 return $this->mConverter
->convertTitle( $title );
2634 # Check if this is a language with variants
2635 function hasVariants() {
2636 return sizeof( $this->getVariants() ) > 1;
2639 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2640 function armourMath( $text ) {
2641 return $this->mConverter
->armourMath( $text );
2645 * Perform output conversion on a string, and encode for safe HTML output.
2646 * @param $text String text to be converted
2647 * @param $isTitle Bool whether this conversion is for the article title
2649 * @todo this should get integrated somewhere sane
2651 function convertHtml( $text, $isTitle = false ) {
2652 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2655 function convertCategoryKey( $key ) {
2656 return $this->mConverter
->convertCategoryKey( $key );
2660 * Get the list of variants supported by this langauge
2661 * see sample implementation in LanguageZh.php
2663 * @return array an array of language codes
2665 function getVariants() {
2666 return $this->mConverter
->getVariants();
2669 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2670 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2674 * If a language supports multiple variants, it is
2675 * possible that non-existing link in one variant
2676 * actually exists in another variant. this function
2677 * tries to find it. See e.g. LanguageZh.php
2679 * @param $link String: the name of the link
2680 * @param $nt Mixed: the title object of the link
2681 * @param $ignoreOtherCond Boolean: to disable other conditions when
2682 * we need to transclude a template or update a category's link
2683 * @return null the input parameters may be modified upon return
2685 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2686 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2690 * If a language supports multiple variants, converts text
2691 * into an array of all possible variants of the text:
2692 * 'variant' => text in that variant
2694 function convertLinkToAllVariants( $text ) {
2695 return $this->mConverter
->convertLinkToAllVariants( $text );
2699 * returns language specific options used by User::getPageRenderHash()
2700 * for example, the preferred language variant
2704 function getExtraHashOptions() {
2705 return $this->mConverter
->getExtraHashOptions();
2709 * For languages that support multiple variants, the title of an
2710 * article may be displayed differently in different variants. this
2711 * function returns the apporiate title defined in the body of the article.
2715 function getParsedTitle() {
2716 return $this->mConverter
->getParsedTitle();
2720 * Enclose a string with the "no conversion" tag. This is used by
2721 * various functions in the Parser
2723 * @param $text String: text to be tagged for no conversion
2725 * @return string the tagged text
2727 function markNoConversion( $text, $noParse = false ) {
2728 return $this->mConverter
->markNoConversion( $text, $noParse );
2732 * A regular expression to match legal word-trailing characters
2733 * which should be merged onto a link of the form [[foo]]bar.
2737 function linkTrail() {
2738 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2741 function getLangObj() {
2746 * Get the RFC 3066 code for this language object
2748 function getCode() {
2749 return $this->mCode
;
2752 function setCode( $code ) {
2753 $this->mCode
= $code;
2757 * Get the name of a file for a certain language code
2758 * @param $prefix string Prepend this to the filename
2759 * @param $code string Language code
2760 * @param $suffix string Append this to the filename
2761 * @return string $prefix . $mangledCode . $suffix
2763 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2764 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2768 * Get the language code from a file name. Inverse of getFileName()
2769 * @param $filename string $prefix . $languageCode . $suffix
2770 * @param $prefix string Prefix before the language code
2771 * @param $suffix string Suffix after the language code
2772 * @return Language code, or false if $prefix or $suffix isn't found
2774 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2776 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2777 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2778 if ( !count( $m ) ) {
2781 return str_replace( '_', '-', strtolower( $m[1] ) );
2784 static function getMessagesFileName( $code ) {
2786 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2789 static function getClassFileName( $code ) {
2791 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2795 * Get the fallback for a given language
2797 static function getFallbackFor( $code ) {
2798 if ( $code === 'en' ) {
2802 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2807 * Get all messages for a given language
2808 * WARNING: this may take a long time
2810 static function getMessagesFor( $code ) {
2811 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2815 * Get a message for a given language
2817 static function getMessageFor( $key, $code ) {
2818 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2821 function fixVariableInNamespace( $talk ) {
2822 if ( strpos( $talk, '$1' ) === false ) {
2826 global $wgMetaNamespace;
2827 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2829 # Allow grammar transformations
2830 # Allowing full message-style parsing would make simple requests
2831 # such as action=raw much more expensive than they need to be.
2832 # This will hopefully cover most cases.
2833 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2834 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2835 return str_replace( ' ', '_', $talk );
2838 function replaceGrammarInNamespace( $m ) {
2839 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2842 static function getCaseMaps() {
2843 static $wikiUpperChars, $wikiLowerChars;
2844 if ( isset( $wikiUpperChars ) ) {
2845 return array( $wikiUpperChars, $wikiLowerChars );
2848 wfProfileIn( __METHOD__
);
2849 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2850 if ( $arr === false ) {
2851 throw new MWException(
2852 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2855 wfProfileOut( __METHOD__
);
2856 return array( $wikiUpperChars, $wikiLowerChars );
2859 function formatTimePeriod( $seconds ) {
2860 if ( $seconds < 10 ) {
2861 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2862 } elseif ( $seconds < 60 ) {
2863 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2864 } elseif ( $seconds < 3600 ) {
2865 $minutes = floor( $seconds / 60 );
2866 $secondsPart = round( fmod( $seconds, 60 ) );
2867 if ( $secondsPart == 60 ) {
2871 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2872 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2874 $hours = floor( $seconds / 3600 );
2875 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2876 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2877 if ( $secondsPart == 60 ) {
2881 if ( $minutes == 60 ) {
2885 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2886 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2887 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2891 function formatBitrate( $bps ) {
2892 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2894 return $this->formatNum( $bps ) . $units[0];
2896 $unitIndex = floor( log10( $bps ) / 3 );
2897 $mantissa = $bps / pow( 1000, $unitIndex );
2898 if ( $mantissa < 10 ) {
2899 $mantissa = round( $mantissa, 1 );
2901 $mantissa = round( $mantissa );
2903 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2907 * Format a size in bytes for output, using an appropriate
2908 * unit (B, KB, MB or GB) according to the magnitude in question
2910 * @param $size Size to format
2911 * @return string Plain text (not HTML)
2913 function formatSize( $size ) {
2914 // For small sizes no decimal places necessary
2916 if ( $size > 1024 ) {
2917 $size = $size / 1024;
2918 if ( $size > 1024 ) {
2919 $size = $size / 1024;
2920 // For MB and bigger two decimal places are smarter
2922 if ( $size > 1024 ) {
2923 $size = $size / 1024;
2924 $msg = 'size-gigabytes';
2926 $msg = 'size-megabytes';
2929 $msg = 'size-kilobytes';
2932 $msg = 'size-bytes';
2934 $size = round( $size, $round );
2935 $text = $this->getMessageFromDB( $msg );
2936 return str_replace( '$1', $this->formatNum( $size ), $text );
2940 * Get the conversion rule title, if any.
2942 function getConvRuleTitle() {
2943 return $this->mConverter
->getConvRuleTitle();
2947 * Given a string, convert it to a (hopefully short) key that can be used
2948 * for efficient sorting. A binary sort according to the sortkeys
2949 * corresponds to a logical sort of the corresponding strings. Current
2950 * code expects that a null character should sort before all others, but
2951 * has no other particular expectations (and that one can be changed if
2954 * @param string $string UTF-8 string
2955 * @return string Binary sortkey
2957 public function convertToSortkey( $string ) {
2958 # Fake function for now
2959 return strtoupper( $string );
2963 * Does it make sense for lists to be split up into sections based on their
2964 * first letter? Logogram-based scripts probably want to return false.
2966 * TODO: Use this in CategoryPage.php.
2970 public function usesFirstLettersInLists() {
2975 * Given a string, return the logical "first letter" to be used for
2976 * grouping on category pages and so on. This has to be coordinated
2977 * carefully with convertToSortkey(), or else the sorted list might jump
2978 * back and forth between the same "initial letters" or other pathological
2979 * behavior. For instance, if you just return the first character, but "a"
2980 * sorts the same as "A" based on convertToSortkey(), then you might get a
2992 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2993 * Obviously, this is ignored if usesFirstLettersInLists() is false.
2995 * @param string $string UTF-8 string
2996 * @return string UTF-8 string corresponding to the first letter of input
2998 public function firstLetterForLists( $string ) {
2999 if ( $string[0] == "\0" ) {
3000 $string = substr( $string, 1 );
3002 return strtoupper( $this->firstChar( $string ) );