3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 global $wgInputEncoding, $wgOutputEncoding;
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
35 * a fake language converter
41 function FakeConverter( $langobj ) { $this->mLang
= $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang
->getCode() ); }
46 function getPreferredVariant() { return $this->mLang
->getCode(); }
47 function getConvRuleTitle() { return false; }
48 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
49 function getExtraHashOptions() { return ''; }
50 function getParsedTitle() { return ''; }
51 function markNoConversion( $text, $noParse = false ) { return $text; }
52 function convertCategoryKey( $key ) { return $key; }
53 function convertLinkToAllVariants( $text ) { return autoConvertToAllVariants( $text ); }
54 function armourMath( $text ) { return $text; }
58 * Internationalisation code
62 var $mConverter, $mVariants, $mCode, $mLoaded = false;
63 var $mMagicExtensions = array(), $mMagicHookDone = false;
65 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
66 var $dateFormatStrings = array();
67 var $mExtendedSpecialPageAliases;
70 * ReplacementArray object caches
72 var $transformData = array();
74 static public $dataCache;
75 static public $mLangObjCache = array();
77 static public $mWeekdayMsgs = array(
78 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
82 static public $mWeekdayAbbrevMsgs = array(
83 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
86 static public $mMonthMsgs = array(
87 'january', 'february', 'march', 'april', 'may_long', 'june',
88 'july', 'august', 'september', 'october', 'november',
91 static public $mMonthGenMsgs = array(
92 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
93 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
96 static public $mMonthAbbrevMsgs = array(
97 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
98 'sep', 'oct', 'nov', 'dec'
101 static public $mIranianCalendarMonthMsgs = array(
102 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
103 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
104 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
105 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
108 static public $mHebrewCalendarMonthMsgs = array(
109 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
110 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
111 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
112 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
113 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
116 static public $mHebrewCalendarMonthGenMsgs = array(
117 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
118 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
119 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
120 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
121 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
124 static public $mHijriCalendarMonthMsgs = array(
125 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
126 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
127 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
128 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
132 * Get a cached language object for a given language code
134 static function factory( $code ) {
135 if ( !isset( self
::$mLangObjCache[$code] ) ) {
136 if ( count( self
::$mLangObjCache ) > 10 ) {
137 // Don't keep a billion objects around, that's stupid.
138 self
::$mLangObjCache = array();
140 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
142 return self
::$mLangObjCache[$code];
146 * Create a language object for a given language code
148 protected static function newFromCode( $code ) {
150 static $recursionLevel = 0;
151 if ( $code == 'en' ) {
154 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
155 // Preload base classes to work around APC/PHP5 bug
156 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
157 include_once( "$IP/languages/classes/$class.deps.php" );
159 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
160 include_once( "$IP/languages/classes/$class.php" );
164 if ( $recursionLevel > 5 ) {
165 throw new MWException( "Language fallback loop detected when creating class $class\n" );
168 if ( !class_exists( $class ) ) {
169 $fallback = Language
::getFallbackFor( $code );
171 $lang = Language
::newFromCode( $fallback );
173 $lang->setCode( $code );
181 * Get the LocalisationCache instance
183 public static function getLocalisationCache() {
184 if ( is_null( self
::$dataCache ) ) {
185 global $wgLocalisationCacheConf;
186 $class = $wgLocalisationCacheConf['class'];
187 self
::$dataCache = new $class( $wgLocalisationCacheConf );
189 return self
::$dataCache;
192 function __construct() {
193 $this->mConverter
= new FakeConverter( $this );
194 // Set the code to the name of the descendant
195 if ( get_class( $this ) == 'Language' ) {
198 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
200 self
::getLocalisationCache();
204 * Reduce memory usage
206 function __destruct() {
207 foreach ( $this as $name => $value ) {
208 unset( $this->$name );
213 * Hook which will be called if this is the content language.
214 * Descendants can use this to register hook functions or modify globals
216 function initContLang() { }
219 * @deprecated Use User::getDefaultOptions()
222 function getDefaultUserOptions() {
223 wfDeprecated( __METHOD__
);
224 return User
::getDefaultOptions();
227 function getFallbackLanguageCode() {
228 if ( $this->mCode
=== 'en' ) {
231 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
236 * Exports $wgBookstoreListEn
239 function getBookstoreList() {
240 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
246 function getNamespaces() {
247 if ( is_null( $this->namespaceNames
) ) {
248 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
250 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
251 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
253 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
255 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
256 if ( $wgMetaNamespaceTalk ) {
257 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
259 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
260 $this->namespaceNames
[NS_PROJECT_TALK
] =
261 $this->fixVariableInNamespace( $talk );
264 # Sometimes a language will be localised but not actually exist on this wiki.
265 global $wgCanonicalNamespaceNames;
266 $validNamespaces = array_keys(MWNamespace
::getCanonicalNamespaces());
267 foreach( $this->namespaceNames
as $key => $text ) {
268 if ( !isset( $validNamespaces[$key] ) ) {
269 unset( $this->namespaceNames
[$key] );
273 # The above mixing may leave namespaces out of canonical order.
274 # Re-order by namespace ID number...
275 ksort( $this->namespaceNames
);
277 return $this->namespaceNames
;
281 * A convenience function that returns the same thing as
282 * getNamespaces() except with the array values changed to ' '
283 * where it found '_', useful for producing output to be displayed
284 * e.g. in <select> forms.
288 function getFormattedNamespaces() {
289 $ns = $this->getNamespaces();
290 foreach ( $ns as $k => $v ) {
291 $ns[$k] = strtr( $v, '_', ' ' );
297 * Get a namespace value by key
299 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
300 * echo $mw_ns; // prints 'MediaWiki'
303 * @param $index Int: the array key of the namespace to return
304 * @return mixed, string if the namespace value exists, otherwise false
306 function getNsText( $index ) {
307 $ns = $this->getNamespaces();
308 return isset( $ns[$index] ) ?
$ns[$index] : false;
312 * A convenience function that returns the same thing as
313 * getNsText() except with '_' changed to ' ', useful for
318 function getFormattedNsText( $index ) {
319 $ns = $this->getNsText( $index );
320 return strtr( $ns, '_', ' ' );
324 * Get a namespace key by value, case insensitive.
325 * Only matches namespace names for the current language, not the
326 * canonical ones defined in Namespace.php.
328 * @param $text String
329 * @return mixed An integer if $text is a valid value otherwise false
331 function getLocalNsIndex( $text ) {
332 $lctext = $this->lc( $text );
333 $ids = $this->getNamespaceIds();
334 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
337 function getNamespaceAliases() {
338 if ( is_null( $this->namespaceAliases
) ) {
339 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
343 foreach ( $aliases as $name => $index ) {
344 if ( $index === NS_PROJECT_TALK
) {
345 unset( $aliases[$name] );
346 $name = $this->fixVariableInNamespace( $name );
347 $aliases[$name] = $index;
351 $this->namespaceAliases
= $aliases;
353 return $this->namespaceAliases
;
356 function getNamespaceIds() {
357 if ( is_null( $this->mNamespaceIds
) ) {
358 global $wgNamespaceAliases;
359 # Put namespace names and aliases into a hashtable.
360 # If this is too slow, then we should arrange it so that it is done
361 # before caching. The catch is that at pre-cache time, the above
362 # class-specific fixup hasn't been done.
363 $this->mNamespaceIds
= array();
364 foreach ( $this->getNamespaces() as $index => $name ) {
365 $this->mNamespaceIds
[$this->lc( $name )] = $index;
367 foreach ( $this->getNamespaceAliases() as $name => $index ) {
368 $this->mNamespaceIds
[$this->lc( $name )] = $index;
370 if ( $wgNamespaceAliases ) {
371 foreach ( $wgNamespaceAliases as $name => $index ) {
372 $this->mNamespaceIds
[$this->lc( $name )] = $index;
376 return $this->mNamespaceIds
;
381 * Get a namespace key by value, case insensitive. Canonical namespace
382 * names override custom ones defined for the current language.
384 * @param $text String
385 * @return mixed An integer if $text is a valid value otherwise false
387 function getNsIndex( $text ) {
388 $lctext = $this->lc( $text );
389 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
392 $ids = $this->getNamespaceIds();
393 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
397 * short names for language variants used for language conversion links.
399 * @param $code String
402 function getVariantname( $code ) {
403 return $this->getMessageFromDB( "variantname-$code" );
406 function specialPage( $name ) {
407 $aliases = $this->getSpecialPageAliases();
408 if ( isset( $aliases[$name][0] ) ) {
409 $name = $aliases[$name][0];
411 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
414 function getQuickbarSettings() {
416 $this->getMessage( 'qbsettings-none' ),
417 $this->getMessage( 'qbsettings-fixedleft' ),
418 $this->getMessage( 'qbsettings-fixedright' ),
419 $this->getMessage( 'qbsettings-floatingleft' ),
420 $this->getMessage( 'qbsettings-floatingright' )
424 function getMathNames() {
425 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
428 function getDatePreferences() {
429 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
432 function getDateFormats() {
433 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
436 function getDefaultDateFormat() {
437 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
438 if ( $df === 'dmy or mdy' ) {
439 global $wgAmericanDates;
440 return $wgAmericanDates ?
'mdy' : 'dmy';
446 function getDatePreferenceMigrationMap() {
447 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
450 function getImageFile( $image ) {
451 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
454 function getDefaultUserOptionOverrides() {
455 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
458 function getExtraUserToggles() {
459 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
462 function getUserToggle( $tog ) {
463 return $this->getMessageFromDB( "tog-$tog" );
467 * Get language names, indexed by code.
468 * If $customisedOnly is true, only returns codes with a messages file
470 public static function getLanguageNames( $customisedOnly = false ) {
471 global $wgLanguageNames, $wgExtraLanguageNames;
472 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
473 if ( !$customisedOnly ) {
479 $dir = opendir( "$IP/languages/messages" );
480 while ( false !== ( $file = readdir( $dir ) ) ) {
481 $code = self
::getCodeFromFileName( $file, 'Messages' );
482 if ( $code && isset( $allNames[$code] ) ) {
483 $names[$code] = $allNames[$code];
491 * Get a message from the MediaWiki namespace.
493 * @param $msg String: message name
496 function getMessageFromDB( $msg ) {
497 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
500 function getLanguageName( $code ) {
501 $names = self
::getLanguageNames();
502 if ( !array_key_exists( $code, $names ) ) {
505 return $names[$code];
508 function getMonthName( $key ) {
509 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
512 function getMonthNameGen( $key ) {
513 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
516 function getMonthAbbreviation( $key ) {
517 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
520 function getWeekdayName( $key ) {
521 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
524 function getWeekdayAbbreviation( $key ) {
525 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
528 function getIranianCalendarMonthName( $key ) {
529 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
532 function getHebrewCalendarMonthName( $key ) {
533 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
536 function getHebrewCalendarMonthNameGen( $key ) {
537 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
540 function getHijriCalendarMonthName( $key ) {
541 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
545 * Used by date() and time() to adjust the time output.
547 * @param $ts Int the time in date('YmdHis') format
548 * @param $tz Mixed: adjust the time by this amount (default false, mean we
549 * get user timecorrection setting)
552 function userAdjust( $ts, $tz = false ) {
553 global $wgUser, $wgLocalTZoffset;
555 if ( $tz === false ) {
556 $tz = $wgUser->getOption( 'timecorrection' );
559 $data = explode( '|', $tz, 3 );
561 if ( $data[0] == 'ZoneInfo' ) {
562 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
563 $date = date_create( $ts, timezone_open( 'UTC' ) );
564 date_timezone_set( $date, timezone_open( $data[2] ) );
565 $date = date_format( $date, 'YmdHis' );
568 # Unrecognized timezone, default to 'Offset' with the stored offset.
573 if ( $data[0] == 'System' ||
$tz == '' ) {
574 # Global offset in minutes.
575 if ( isset( $wgLocalTZoffset ) ) {
576 $minDiff = $wgLocalTZoffset;
578 } else if ( $data[0] == 'Offset' ) {
579 $minDiff = intval( $data[1] );
581 $data = explode( ':', $tz );
582 if ( count( $data ) == 2 ) {
583 $data[0] = intval( $data[0] );
584 $data[1] = intval( $data[1] );
585 $minDiff = abs( $data[0] ) * 60 +
$data[1];
586 if ( $data[0] < 0 ) {
587 $minDiff = -$minDiff;
590 $minDiff = intval( $data[0] ) * 60;
594 # No difference ? Return time unchanged
595 if ( 0 == $minDiff ) {
599 wfSuppressWarnings(); // E_STRICT system time bitching
600 # Generate an adjusted date; take advantage of the fact that mktime
601 # will normalize out-of-range values so we don't have to split $minDiff
602 # into hours and minutes.
604 (int)substr( $ts, 8, 2 ) ), # Hours
605 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
606 (int)substr( $ts, 12, 2 ), # Seconds
607 (int)substr( $ts, 4, 2 ), # Month
608 (int)substr( $ts, 6, 2 ), # Day
609 (int)substr( $ts, 0, 4 ) ); # Year
611 $date = date( 'YmdHis', $t );
618 * This is a workalike of PHP's date() function, but with better
619 * internationalisation, a reduced set of format characters, and a better
622 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
623 * PHP manual for definitions. "o" format character is supported since
624 * PHP 5.1.0, previous versions return literal o.
625 * There are a number of extensions, which start with "x":
627 * xn Do not translate digits of the next numeric format character
628 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
629 * xr Use roman numerals for the next numeric format character
630 * xh Use hebrew numerals for the next numeric format character
632 * xg Genitive month name
634 * xij j (day number) in Iranian calendar
635 * xiF F (month name) in Iranian calendar
636 * xin n (month number) in Iranian calendar
637 * xiY Y (full year) in Iranian calendar
639 * xjj j (day number) in Hebrew calendar
640 * xjF F (month name) in Hebrew calendar
641 * xjt t (days in month) in Hebrew calendar
642 * xjx xg (genitive month name) in Hebrew calendar
643 * xjn n (month number) in Hebrew calendar
644 * xjY Y (full year) in Hebrew calendar
646 * xmj j (day number) in Hijri calendar
647 * xmF F (month name) in Hijri calendar
648 * xmn n (month number) in Hijri calendar
649 * xmY Y (full year) in Hijri calendar
651 * xkY Y (full year) in Thai solar calendar. Months and days are
652 * identical to the Gregorian calendar
653 * xoY Y (full year) in Minguo calendar or Juche year.
654 * Months and days are identical to the
656 * xtY Y (full year) in Japanese nengo. Months and days are
657 * identical to the Gregorian calendar
659 * Characters enclosed in double quotes will be considered literal (with
660 * the quotes themselves removed). Unmatched quotes will be considered
661 * literal quotes. Example:
663 * "The month is" F => The month is January
666 * Backslash escaping is also supported.
668 * Input timestamp is assumed to be pre-normalized to the desired local
671 * @param $format String
672 * @param $ts String: 14-character timestamp
675 * @todo emulation of "o" format character for PHP pre 5.1.0
676 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
678 function sprintfDate( $format, $ts ) {
691 for ( $p = 0; $p < strlen( $format ); $p++
) {
694 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
695 $code .= $format[++
$p];
698 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
699 $code .= $format[++
$p];
710 $rawToggle = !$rawToggle;
719 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
722 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
723 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
726 $num = substr( $ts, 6, 2 );
729 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
730 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
733 $num = intval( substr( $ts, 6, 2 ) );
737 $iranian = self
::tsToIranian( $ts );
743 $hijri = self
::tsToHijri( $ts );
749 $hebrew = self
::tsToHebrew( $ts );
755 $unix = wfTimestamp( TS_UNIX
, $ts );
757 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
761 $unix = wfTimestamp( TS_UNIX
, $ts );
763 $w = gmdate( 'w', $unix );
768 $unix = wfTimestamp( TS_UNIX
, $ts );
770 $num = gmdate( 'w', $unix );
774 $unix = wfTimestamp( TS_UNIX
, $ts );
776 $num = gmdate( 'z', $unix );
780 $unix = wfTimestamp( TS_UNIX
, $ts );
782 $num = gmdate( 'W', $unix );
785 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
789 $iranian = self
::tsToIranian( $ts );
791 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
795 $hijri = self
::tsToHijri( $ts );
797 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
801 $hebrew = self
::tsToHebrew( $ts );
803 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
806 $num = substr( $ts, 4, 2 );
809 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
812 $num = intval( substr( $ts, 4, 2 ) );
816 $iranian = self
::tsToIranian( $ts );
822 $hijri = self
::tsToHijri ( $ts );
828 $hebrew = self
::tsToHebrew( $ts );
834 $unix = wfTimestamp( TS_UNIX
, $ts );
836 $num = gmdate( 't', $unix );
840 $hebrew = self
::tsToHebrew( $ts );
846 $unix = wfTimestamp( TS_UNIX
, $ts );
848 $num = gmdate( 'L', $unix );
850 # 'o' is supported since PHP 5.1.0
851 # return literal if not supported
852 # TODO: emulation for pre 5.1.0 versions
855 $unix = wfTimestamp( TS_UNIX
, $ts );
857 if ( version_compare( PHP_VERSION
, '5.1.0' ) === 1 ) {
858 $num = date( 'o', $unix );
864 $num = substr( $ts, 0, 4 );
868 $iranian = self
::tsToIranian( $ts );
874 $hijri = self
::tsToHijri( $ts );
880 $hebrew = self
::tsToHebrew( $ts );
886 $thai = self
::tsToYear( $ts, 'thai' );
892 $minguo = self
::tsToYear( $ts, 'minguo' );
898 $tenno = self
::tsToYear( $ts, 'tenno' );
903 $num = substr( $ts, 2, 2 );
906 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
909 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
912 $h = substr( $ts, 8, 2 );
913 $num = $h %
12 ?
$h %
12 : 12;
916 $num = intval( substr( $ts, 8, 2 ) );
919 $h = substr( $ts, 8, 2 );
920 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
923 $num = substr( $ts, 8, 2 );
926 $num = substr( $ts, 10, 2 );
929 $num = substr( $ts, 12, 2 );
933 $unix = wfTimestamp( TS_UNIX
, $ts );
935 $s .= gmdate( 'c', $unix );
939 $unix = wfTimestamp( TS_UNIX
, $ts );
941 $s .= gmdate( 'r', $unix );
945 $unix = wfTimestamp( TS_UNIX
, $ts );
951 if ( $p < strlen( $format ) - 1 ) {
959 if ( $p < strlen( $format ) - 1 ) {
960 $endQuote = strpos( $format, '"', $p +
1 );
961 if ( $endQuote === false ) {
962 # No terminating quote, assume literal "
965 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
969 # Quote at end of string, assume literal "
976 if ( $num !== false ) {
977 if ( $rawToggle ||
$raw ) {
980 } elseif ( $roman ) {
981 $s .= self
::romanNumeral( $num );
983 } elseif ( $hebrewNum ) {
984 $s .= self
::hebrewNumeral( $num );
987 $s .= $this->formatNum( $num, true );
995 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
996 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
998 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
999 * Gregorian dates to Iranian dates. Originally written in C, it
1000 * is released under the terms of GNU Lesser General Public
1001 * License. Conversion to PHP was performed by Niklas Laxström.
1003 * Link: http://www.farsiweb.info/jalali/jalali.c
1005 private static function tsToIranian( $ts ) {
1006 $gy = substr( $ts, 0, 4 ) -1600;
1007 $gm = substr( $ts, 4, 2 ) -1;
1008 $gd = substr( $ts, 6, 2 ) -1;
1010 # Days passed from the beginning (including leap years)
1012 +
floor( ( $gy +
3 ) / 4 )
1013 - floor( ( $gy +
99 ) / 100 )
1014 +
floor( ( $gy +
399 ) / 400 );
1017 // Add days of the past months of this year
1018 for ( $i = 0; $i < $gm; $i++
) {
1019 $gDayNo +
= self
::$GREG_DAYS[$i];
1023 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1027 // Days passed in current month
1030 $jDayNo = $gDayNo - 79;
1032 $jNp = floor( $jDayNo / 12053 );
1035 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1038 if ( $jDayNo >= 366 ) {
1039 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1040 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1043 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1044 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1050 return array( $jy, $jm, $jd );
1054 * Converting Gregorian dates to Hijri dates.
1056 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1058 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1060 private static function tsToHijri( $ts ) {
1061 $year = substr( $ts, 0, 4 );
1062 $month = substr( $ts, 4, 2 );
1063 $day = substr( $ts, 6, 2 );
1071 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1072 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1075 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1076 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1077 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1080 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1081 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1084 $zl = $zjd -1948440 +
10632;
1085 $zn = (int)( ( $zl - 1 ) / 10631 );
1086 $zl = $zl - 10631 * $zn +
354;
1087 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1088 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1089 $zm = (int)( ( 24 * $zl ) / 709 );
1090 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1091 $zy = 30 * $zn +
$zj - 30;
1093 return array( $zy, $zm, $zd );
1097 * Converting Gregorian dates to Hebrew dates.
1099 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1100 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1101 * to translate the relevant functions into PHP and release them under
1104 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1105 * and Adar II is 14. In a non-leap year, Adar is 6.
1107 private static function tsToHebrew( $ts ) {
1109 $year = substr( $ts, 0, 4 );
1110 $month = substr( $ts, 4, 2 );
1111 $day = substr( $ts, 6, 2 );
1113 # Calculate Hebrew year
1114 $hebrewYear = $year +
3760;
1116 # Month number when September = 1, August = 12
1118 if ( $month > 12 ) {
1125 # Calculate day of year from 1 September
1127 for ( $i = 1; $i < $month; $i++
) {
1131 # Check if the year is leap
1132 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1135 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1142 # Calculate the start of the Hebrew year
1143 $start = self
::hebrewYearStart( $hebrewYear );
1145 # Calculate next year's start
1146 if ( $dayOfYear <= $start ) {
1147 # Day is before the start of the year - it is the previous year
1149 $nextStart = $start;
1153 # Add days since previous year's 1 September
1155 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1159 # Start of the new (previous) year
1160 $start = self
::hebrewYearStart( $hebrewYear );
1163 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1166 # Calculate Hebrew day of year
1167 $hebrewDayOfYear = $dayOfYear - $start;
1169 # Difference between year's days
1170 $diff = $nextStart - $start;
1171 # Add 12 (or 13 for leap years) days to ignore the difference between
1172 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1173 # difference is only about the year type
1174 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1180 # Check the year pattern, and is leap year
1181 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1182 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1183 # and non-leap years
1184 $yearPattern = $diff %
30;
1185 # Check if leap year
1186 $isLeap = $diff >= 30;
1188 # Calculate day in the month from number of day in the Hebrew year
1189 # Don't check Adar - if the day is not in Adar, we will stop before;
1190 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1191 $hebrewDay = $hebrewDayOfYear;
1194 while ( $hebrewMonth <= 12 ) {
1195 # Calculate days in this month
1196 if ( $isLeap && $hebrewMonth == 6 ) {
1197 # Adar in a leap year
1199 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1201 if ( $hebrewDay <= $days ) {
1205 # Subtract the days of Adar I
1206 $hebrewDay -= $days;
1209 if ( $hebrewDay <= $days ) {
1215 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1216 # Cheshvan in a complete year (otherwise as the rule below)
1218 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1219 # Kislev in an incomplete year (otherwise as the rule below)
1222 # Odd months have 30 days, even have 29
1223 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1225 if ( $hebrewDay <= $days ) {
1226 # In the current month
1229 # Subtract the days of the current month
1230 $hebrewDay -= $days;
1231 # Try in the next month
1236 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1240 * This calculates the Hebrew year start, as days since 1 September.
1241 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1242 * Used for Hebrew date.
1244 private static function hebrewYearStart( $year ) {
1245 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1246 $b = intval( ( $year - 1 ) %
4 );
1247 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1251 $Mar = intval( $m );
1257 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1258 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1260 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1262 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1266 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1271 * Algorithm to convert Gregorian dates to Thai solar dates,
1272 * Minguo dates or Minguo dates.
1274 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1275 * http://en.wikipedia.org/wiki/Minguo_calendar
1276 * http://en.wikipedia.org/wiki/Japanese_era_name
1278 * @param $ts String: 14-character timestamp
1279 * @param $cName String: calender name
1280 * @return Array: converted year, month, day
1282 private static function tsToYear( $ts, $cName ) {
1283 $gy = substr( $ts, 0, 4 );
1284 $gm = substr( $ts, 4, 2 );
1285 $gd = substr( $ts, 6, 2 );
1287 if ( !strcmp( $cName, 'thai' ) ) {
1289 # Add 543 years to the Gregorian calendar
1290 # Months and days are identical
1291 $gy_offset = $gy +
543;
1292 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1294 # Deduct 1911 years from the Gregorian calendar
1295 # Months and days are identical
1296 $gy_offset = $gy - 1911;
1297 } else if ( !strcmp( $cName, 'tenno' ) ) {
1298 # Nengō dates up to Meiji period
1299 # Deduct years from the Gregorian calendar
1300 # depending on the nengo periods
1301 # Months and days are identical
1302 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1304 $gy_gannen = $gy - 1868 +
1;
1305 $gy_offset = $gy_gannen;
1306 if ( $gy_gannen == 1 ) {
1309 $gy_offset = '明治' . $gy_offset;
1311 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1312 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1313 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1314 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1315 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1319 $gy_gannen = $gy - 1912 +
1;
1320 $gy_offset = $gy_gannen;
1321 if ( $gy_gannen == 1 ) {
1324 $gy_offset = '大正' . $gy_offset;
1326 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1327 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1328 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1332 $gy_gannen = $gy - 1926 +
1;
1333 $gy_offset = $gy_gannen;
1334 if ( $gy_gannen == 1 ) {
1337 $gy_offset = '昭和' . $gy_offset;
1340 $gy_gannen = $gy - 1989 +
1;
1341 $gy_offset = $gy_gannen;
1342 if ( $gy_gannen == 1 ) {
1345 $gy_offset = '平成' . $gy_offset;
1351 return array( $gy_offset, $gm, $gd );
1355 * Roman number formatting up to 3000
1357 static function romanNumeral( $num ) {
1358 static $table = array(
1359 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1360 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1361 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1362 array( '', 'M', 'MM', 'MMM' )
1365 $num = intval( $num );
1366 if ( $num > 3000 ||
$num <= 0 ) {
1371 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1372 if ( $num >= $pow10 ) {
1373 $s .= $table[$i][floor( $num / $pow10 )];
1375 $num = $num %
$pow10;
1381 * Hebrew Gematria number formatting up to 9999
1383 static function hebrewNumeral( $num ) {
1384 static $table = array(
1385 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1386 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1387 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1388 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1391 $num = intval( $num );
1392 if ( $num > 9999 ||
$num <= 0 ) {
1397 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1398 if ( $num >= $pow10 ) {
1399 if ( $num == 15 ||
$num == 16 ) {
1400 $s .= $table[0][9] . $table[0][$num - 9];
1403 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1404 if ( $pow10 == 1000 ) {
1409 $num = $num %
$pow10;
1411 if ( strlen( $s ) == 2 ) {
1414 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1415 $str .= substr( $s, strlen( $s ) - 2, 2 );
1417 $start = substr( $str, 0, strlen( $str ) - 2 );
1418 $end = substr( $str, strlen( $str ) - 2 );
1421 $str = $start . 'ך';
1424 $str = $start . 'ם';
1427 $str = $start . 'ן';
1430 $str = $start . 'ף';
1433 $str = $start . 'ץ';
1440 * This is meant to be used by time(), date(), and timeanddate() to get
1441 * the date preference they're supposed to use, it should be used in
1445 * function timeanddate([...], $format = true) {
1446 * $datePreference = $this->dateFormat($format);
1451 * @param $usePrefs Mixed: if true, the user's preference is used
1452 * if false, the site/language default is used
1453 * if int/string, assumed to be a format.
1456 function dateFormat( $usePrefs = true ) {
1459 if ( is_bool( $usePrefs ) ) {
1461 $datePreference = $wgUser->getDatePreference();
1463 $datePreference = (string)User
::getDefaultOption( 'date' );
1466 $datePreference = (string)$usePrefs;
1470 if ( $datePreference == '' ) {
1474 return $datePreference;
1478 * Get a format string for a given type and preference
1479 * @param $type May be date, time or both
1480 * @param $pref The format name as it appears in Messages*.php
1482 function getDateFormatString( $type, $pref ) {
1483 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1484 if ( $pref == 'default' ) {
1485 $pref = $this->getDefaultDateFormat();
1486 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1488 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1489 if ( is_null( $df ) ) {
1490 $pref = $this->getDefaultDateFormat();
1491 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1494 $this->dateFormatStrings
[$type][$pref] = $df;
1496 return $this->dateFormatStrings
[$type][$pref];
1500 * @param $ts Mixed: the time format which needs to be turned into a
1501 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1502 * @param $adj Bool: whether to adjust the time output according to the
1503 * user configured offset ($timecorrection)
1504 * @param $format Mixed: true to use user's date format preference
1505 * @param $timecorrection String: the time offset as returned by
1506 * validateTimeZone() in Special:Preferences
1509 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1511 $ts = $this->userAdjust( $ts, $timecorrection );
1513 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1514 return $this->sprintfDate( $df, $ts );
1518 * @param $ts Mixed: the time format which needs to be turned into a
1519 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1520 * @param $adj Bool: whether to adjust the time output according to the
1521 * user configured offset ($timecorrection)
1522 * @param $format Mixed: true to use user's date format preference
1523 * @param $timecorrection String: the time offset as returned by
1524 * validateTimeZone() in Special:Preferences
1527 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1529 $ts = $this->userAdjust( $ts, $timecorrection );
1531 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1532 return $this->sprintfDate( $df, $ts );
1536 * @param $ts Mixed: the time format which needs to be turned into a
1537 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1538 * @param $adj Bool: whether to adjust the time output according to the
1539 * user configured offset ($timecorrection)
1540 * @param $format Mixed: what format to return, if it's false output the
1541 * default one (default true)
1542 * @param $timecorrection String: the time offset as returned by
1543 * validateTimeZone() in Special:Preferences
1546 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1547 $ts = wfTimestamp( TS_MW
, $ts );
1549 $ts = $this->userAdjust( $ts, $timecorrection );
1551 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1552 return $this->sprintfDate( $df, $ts );
1555 function getMessage( $key ) {
1556 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1559 function getAllMessages() {
1560 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1563 function iconv( $in, $out, $string ) {
1564 # This is a wrapper for iconv in all languages except esperanto,
1565 # which does some nasty x-conversions beforehand
1567 # Even with //IGNORE iconv can whine about illegal characters in
1568 # *input* string. We just ignore those too.
1569 # REF: http://bugs.php.net/bug.php?id=37166
1570 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1571 wfSuppressWarnings();
1572 $text = iconv( $in, $out . '//IGNORE', $string );
1573 wfRestoreWarnings();
1577 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1578 function ucwordbreaksCallbackAscii( $matches ) {
1579 return $this->ucfirst( $matches[1] );
1582 function ucwordbreaksCallbackMB( $matches ) {
1583 return mb_strtoupper( $matches[0] );
1586 function ucCallback( $matches ) {
1587 list( $wikiUpperChars ) = self
::getCaseMaps();
1588 return strtr( $matches[1], $wikiUpperChars );
1591 function lcCallback( $matches ) {
1592 list( , $wikiLowerChars ) = self
::getCaseMaps();
1593 return strtr( $matches[1], $wikiLowerChars );
1596 function ucwordsCallbackMB( $matches ) {
1597 return mb_strtoupper( $matches[0] );
1600 function ucwordsCallbackWiki( $matches ) {
1601 list( $wikiUpperChars ) = self
::getCaseMaps();
1602 return strtr( $matches[0], $wikiUpperChars );
1605 function ucfirst( $str ) {
1609 } elseif ( $o < 128 ) {
1610 return ucfirst( $str );
1612 // fall back to more complex logic in case of multibyte strings
1613 return $this->uc( $str, true );
1617 function uc( $str, $first = false ) {
1618 if ( function_exists( 'mb_strtoupper' ) ) {
1620 if ( $this->isMultibyte( $str ) ) {
1621 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1623 return ucfirst( $str );
1626 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1629 if ( $this->isMultibyte( $str ) ) {
1630 $x = $first ?
'^' : '';
1631 return preg_replace_callback(
1632 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1633 array( $this, 'ucCallback' ),
1637 return $first ?
ucfirst( $str ) : strtoupper( $str );
1642 function lcfirst( $str ) {
1645 return strval( $str );
1646 } elseif ( $o >= 128 ) {
1647 return $this->lc( $str, true );
1648 } elseif ( $o > 96 ) {
1651 $str[0] = strtolower( $str[0] );
1656 function lc( $str, $first = false ) {
1657 if ( function_exists( 'mb_strtolower' ) ) {
1659 if ( $this->isMultibyte( $str ) ) {
1660 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1662 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1665 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1668 if ( $this->isMultibyte( $str ) ) {
1669 $x = $first ?
'^' : '';
1670 return preg_replace_callback(
1671 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1672 array( $this, 'lcCallback' ),
1676 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1681 function isMultibyte( $str ) {
1682 return (bool)preg_match( '/[\x80-\xff]/', $str );
1685 function ucwords( $str ) {
1686 if ( $this->isMultibyte( $str ) ) {
1687 $str = $this->lc( $str );
1689 // regexp to find first letter in each word (i.e. after each space)
1690 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1692 // function to use to capitalize a single char
1693 if ( function_exists( 'mb_strtoupper' ) ) {
1694 return preg_replace_callback(
1696 array( $this, 'ucwordsCallbackMB' ),
1700 return preg_replace_callback(
1702 array( $this, 'ucwordsCallbackWiki' ),
1707 return ucwords( strtolower( $str ) );
1711 # capitalize words at word breaks
1712 function ucwordbreaks( $str ) {
1713 if ( $this->isMultibyte( $str ) ) {
1714 $str = $this->lc( $str );
1716 // since \b doesn't work for UTF-8, we explicitely define word break chars
1717 $breaks = "[ \-\(\)\}\{\.,\?!]";
1719 // find first letter after word break
1720 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1722 if ( function_exists( 'mb_strtoupper' ) ) {
1723 return preg_replace_callback(
1725 array( $this, 'ucwordbreaksCallbackMB' ),
1729 return preg_replace_callback(
1731 array( $this, 'ucwordsCallbackWiki' ),
1736 return preg_replace_callback(
1737 '/\b([\w\x80-\xff]+)\b/',
1738 array( $this, 'ucwordbreaksCallbackAscii' ),
1745 * Return a case-folded representation of $s
1747 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1748 * and $s2 are the same except for the case of their characters. It is not
1749 * necessary for the value returned to make sense when displayed.
1751 * Do *not* perform any other normalisation in this function. If a caller
1752 * uses this function when it should be using a more general normalisation
1753 * function, then fix the caller.
1755 function caseFold( $s ) {
1756 return $this->uc( $s );
1759 function checkTitleEncoding( $s ) {
1760 if ( is_array( $s ) ) {
1761 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1763 # Check for non-UTF-8 URLs
1764 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1769 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1770 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1775 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1778 function fallback8bitEncoding() {
1779 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1783 * Most writing systems use whitespace to break up words.
1784 * Some languages such as Chinese don't conventionally do this,
1785 * which requires special handling when breaking up words for
1788 function hasWordBreaks() {
1793 * Some languages such as Chinese require word segmentation,
1794 * Specify such segmentation when overridden in derived class.
1796 * @param $string String
1799 function segmentByWord( $string ) {
1804 * Some languages have special punctuation need to be normalized.
1805 * Make such changes here.
1807 * @param $string String
1810 function normalizeForSearch( $string ) {
1811 return self
::convertDoubleWidth( $string );
1815 * convert double-width roman characters to single-width.
1816 * range: ff00-ff5f ~= 0020-007f
1818 protected static function convertDoubleWidth( $string ) {
1819 static $full = null;
1820 static $half = null;
1822 if ( $full === null ) {
1823 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1824 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1825 $full = str_split( $fullWidth, 3 );
1826 $half = str_split( $halfWidth );
1829 $string = str_replace( $full, $half, $string );
1833 protected static function insertSpace( $string, $pattern ) {
1834 $string = preg_replace( $pattern, " $1 ", $string );
1835 $string = preg_replace( '/ +/', ' ', $string );
1839 function convertForSearchResult( $termsArray ) {
1840 # some languages, e.g. Chinese, need to do a conversion
1841 # in order for search results to be displayed correctly
1846 * Get the first character of a string.
1851 function firstChar( $s ) {
1854 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1855 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1860 if ( isset( $matches[1] ) ) {
1861 if ( strlen( $matches[1] ) != 3 ) {
1865 // Break down Hangul syllables to grab the first jamo
1866 $code = utf8ToCodepoint( $matches[1] );
1867 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1869 } elseif ( $code < 0xb098 ) {
1870 return "\xe3\x84\xb1";
1871 } elseif ( $code < 0xb2e4 ) {
1872 return "\xe3\x84\xb4";
1873 } elseif ( $code < 0xb77c ) {
1874 return "\xe3\x84\xb7";
1875 } elseif ( $code < 0xb9c8 ) {
1876 return "\xe3\x84\xb9";
1877 } elseif ( $code < 0xbc14 ) {
1878 return "\xe3\x85\x81";
1879 } elseif ( $code < 0xc0ac ) {
1880 return "\xe3\x85\x82";
1881 } elseif ( $code < 0xc544 ) {
1882 return "\xe3\x85\x85";
1883 } elseif ( $code < 0xc790 ) {
1884 return "\xe3\x85\x87";
1885 } elseif ( $code < 0xcc28 ) {
1886 return "\xe3\x85\x88";
1887 } elseif ( $code < 0xce74 ) {
1888 return "\xe3\x85\x8a";
1889 } elseif ( $code < 0xd0c0 ) {
1890 return "\xe3\x85\x8b";
1891 } elseif ( $code < 0xd30c ) {
1892 return "\xe3\x85\x8c";
1893 } elseif ( $code < 0xd558 ) {
1894 return "\xe3\x85\x8d";
1896 return "\xe3\x85\x8e";
1903 function initEncoding() {
1904 # Some languages may have an alternate char encoding option
1905 # (Esperanto X-coding, Japanese furigana conversion, etc)
1906 # If this language is used as the primary content language,
1907 # an override to the defaults can be set here on startup.
1910 function recodeForEdit( $s ) {
1911 # For some languages we'll want to explicitly specify
1912 # which characters make it into the edit box raw
1913 # or are converted in some way or another.
1914 # Note that if wgOutputEncoding is different from
1915 # wgInputEncoding, this text will be further converted
1916 # to wgOutputEncoding.
1917 global $wgEditEncoding;
1918 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1921 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1925 function recodeInput( $s ) {
1926 # Take the previous into account.
1927 global $wgEditEncoding;
1928 if ( $wgEditEncoding != '' ) {
1929 $enc = $wgEditEncoding;
1933 if ( $enc == 'UTF-8' ) {
1936 return $this->iconv( $enc, 'UTF-8', $s );
1941 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1942 * also cleans up certain backwards-compatible sequences, converting them
1943 * to the modern Unicode equivalent.
1945 * This is language-specific for performance reasons only.
1947 function normalize( $s ) {
1948 global $wgAllUnicodeFixes;
1949 $s = UtfNormal
::cleanUp( $s );
1950 if ( $wgAllUnicodeFixes ) {
1951 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1952 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1959 * Transform a string using serialized data stored in the given file (which
1960 * must be in the serialized subdirectory of $IP). The file contains pairs
1961 * mapping source characters to destination characters.
1963 * The data is cached in process memory. This will go faster if you have the
1964 * FastStringSearch extension.
1966 function transformUsingPairFile( $file, $string ) {
1967 if ( !isset( $this->transformData
[$file] ) ) {
1968 $data = wfGetPrecompiledData( $file );
1969 if ( $data === false ) {
1970 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1972 $this->transformData
[$file] = new ReplacementArray( $data );
1974 return $this->transformData
[$file]->replace( $string );
1978 * For right-to-left language support
1983 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1987 * Return the correct HTML 'dir' attribute value for this language.
1991 return $this->isRTL() ?
'rtl' : 'ltr';
1995 * Return 'left' or 'right' as appropriate alignment for line-start
1996 * for this language's text direction.
1998 * Should be equivalent to CSS3 'start' text-align value....
2002 function alignStart() {
2003 return $this->isRTL() ?
'right' : 'left';
2007 * Return 'right' or 'left' as appropriate alignment for line-end
2008 * for this language's text direction.
2010 * Should be equivalent to CSS3 'end' text-align value....
2014 function alignEnd() {
2015 return $this->isRTL() ?
'left' : 'right';
2019 * A hidden direction mark (LRM or RLM), depending on the language direction
2023 function getDirMark() {
2024 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2027 function capitalizeAllNouns() {
2028 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2032 * An arrow, depending on the language direction
2036 function getArrow() {
2037 return $this->isRTL() ?
'←' : '→';
2041 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2045 function linkPrefixExtension() {
2046 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2049 function getMagicWords() {
2050 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2053 # Fill a MagicWord object with data from here
2054 function getMagic( $mw ) {
2055 if ( !$this->mMagicHookDone
) {
2056 $this->mMagicHookDone
= true;
2057 wfProfileIn( 'LanguageGetMagic' );
2058 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2059 wfProfileOut( 'LanguageGetMagic' );
2061 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2062 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2064 $magicWords = $this->getMagicWords();
2065 if ( isset( $magicWords[$mw->mId
] ) ) {
2066 $rawEntry = $magicWords[$mw->mId
];
2072 if ( !is_array( $rawEntry ) ) {
2073 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2075 $mw->mCaseSensitive
= $rawEntry[0];
2076 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2081 * Add magic words to the extension array
2083 function addMagicWordsByLang( $newWords ) {
2084 $code = $this->getCode();
2085 $fallbackChain = array();
2086 while ( $code && !in_array( $code, $fallbackChain ) ) {
2087 $fallbackChain[] = $code;
2088 $code = self
::getFallbackFor( $code );
2090 if ( !in_array( 'en', $fallbackChain ) ) {
2091 $fallbackChain[] = 'en';
2093 $fallbackChain = array_reverse( $fallbackChain );
2094 foreach ( $fallbackChain as $code ) {
2095 if ( isset( $newWords[$code] ) ) {
2096 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2102 * Get special page names, as an associative array
2103 * case folded alias => real name
2105 function getSpecialPageAliases() {
2106 // Cache aliases because it may be slow to load them
2107 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2109 $this->mExtendedSpecialPageAliases
=
2110 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2111 wfRunHooks( 'LanguageGetSpecialPageAliases',
2112 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2115 return $this->mExtendedSpecialPageAliases
;
2119 * Italic is unsuitable for some languages
2121 * @param $text String: the text to be emphasized.
2124 function emphasize( $text ) {
2125 return "<em>$text</em>";
2129 * Normally we output all numbers in plain en_US style, that is
2130 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2131 * point twohundredthirtyfive. However this is not sutable for all
2132 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2133 * Icelandic just want to use commas instead of dots, and dots instead
2134 * of commas like "293.291,235".
2136 * An example of this function being called:
2138 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2141 * See LanguageGu.php for the Gujarati implementation and
2142 * $separatorTransformTable on MessageIs.php for
2143 * the , => . and . => , implementation.
2145 * @todo check if it's viable to use localeconv() for the decimal
2147 * @param $number Mixed: the string to be formatted, should be an integer
2148 * or a floating point number.
2149 * @param $nocommafy Bool: set to true for special numbers like dates
2152 function formatNum( $number, $nocommafy = false ) {
2153 global $wgTranslateNumerals;
2154 if ( !$nocommafy ) {
2155 $number = $this->commafy( $number );
2156 $s = $this->separatorTransformTable();
2158 $number = strtr( $number, $s );
2162 if ( $wgTranslateNumerals ) {
2163 $s = $this->digitTransformTable();
2165 $number = strtr( $number, $s );
2172 function parseFormattedNumber( $number ) {
2173 $s = $this->digitTransformTable();
2175 $number = strtr( $number, array_flip( $s ) );
2178 $s = $this->separatorTransformTable();
2180 $number = strtr( $number, array_flip( $s ) );
2183 $number = strtr( $number, array( ',' => '' ) );
2188 * Adds commas to a given number
2193 function commafy( $_ ) {
2194 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2197 function digitTransformTable() {
2198 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2201 function separatorTransformTable() {
2202 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2206 * Take a list of strings and build a locale-friendly comma-separated
2207 * list, using the local comma-separator message.
2208 * The last two strings are chained with an "and".
2213 function listToText( $l ) {
2215 $m = count( $l ) - 1;
2217 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2219 for ( $i = $m; $i >= 0; $i-- ) {
2222 } else if ( $i == $m - 1 ) {
2223 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2225 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2233 * Take a list of strings and build a locale-friendly comma-separated
2234 * list, using the local comma-separator message.
2235 * @param $list array of strings to put in a comma list
2238 function commaList( $list ) {
2243 array( 'parsemag', 'escapenoentities', 'language' => $this )
2249 * Take a list of strings and build a locale-friendly semicolon-separated
2250 * list, using the local semicolon-separator message.
2251 * @param $list array of strings to put in a semicolon list
2254 function semicolonList( $list ) {
2258 'semicolon-separator',
2259 array( 'parsemag', 'escapenoentities', 'language' => $this )
2265 * Same as commaList, but separate it with the pipe instead.
2266 * @param $list array of strings to put in a pipe list
2269 function pipeList( $list ) {
2274 array( 'escapenoentities', 'language' => $this )
2280 * Truncate a string to a specified length in bytes, appending an optional
2281 * string (e.g. for ellipses)
2283 * The database offers limited byte lengths for some columns in the database;
2284 * multi-byte character sets mean we need to ensure that only whole characters
2285 * are included, otherwise broken characters can be passed to the user
2287 * If $length is negative, the string will be truncated from the beginning
2289 * @param $string String to truncate
2290 * @param $length Int: maximum length (excluding ellipses)
2291 * @param $ellipsis String to append to the truncated text
2294 function truncate( $string, $length, $ellipsis = '...' ) {
2295 # Use the localized ellipsis character
2296 if ( $ellipsis == '...' ) {
2297 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2299 # Check if there is no need to truncate
2300 if ( $length == 0 ) {
2302 } elseif ( strlen( $string ) <= abs( $length ) ) {
2305 $stringOriginal = $string;
2306 if ( $length > 0 ) {
2307 $string = substr( $string, 0, $length ); // xyz...
2308 $string = $this->removeBadCharLast( $string );
2309 $string = $string . $ellipsis;
2311 $string = substr( $string, $length ); // ...xyz
2312 $string = $this->removeBadCharFirst( $string );
2313 $string = $ellipsis . $string;
2315 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2316 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2319 return $stringOriginal;
2324 * Remove bytes that represent an incomplete Unicode character
2325 * at the end of string (e.g. bytes of the char are missing)
2327 * @param $string String
2330 protected function removeBadCharLast( $string ) {
2331 $char = ord( $string[strlen( $string ) - 1] );
2333 if ( $char >= 0xc0 ) {
2334 # We got the first byte only of a multibyte char; remove it.
2335 $string = substr( $string, 0, -1 );
2336 } elseif ( $char >= 0x80 &&
2337 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2338 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2340 # We chopped in the middle of a character; remove it
2347 * Remove bytes that represent an incomplete Unicode character
2348 * at the start of string (e.g. bytes of the char are missing)
2350 * @param $string String
2353 protected function removeBadCharFirst( $string ) {
2354 $char = ord( $string[0] );
2355 if ( $char >= 0x80 && $char < 0xc0 ) {
2356 # We chopped in the middle of a character; remove the whole thing
2357 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2363 * Truncate a string of valid HTML to a specified length in bytes,
2364 * appending an optional string (e.g. for ellipses), and return valid HTML
2366 * This is only intended for styled/linked text, such as HTML with
2367 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2369 * Note: tries to fix broken HTML with MWTidy
2371 * @param string $text String to truncate
2372 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2373 * @param string $ellipsis String to append to the truncated text
2376 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2377 # Use the localized ellipsis character
2378 if ( $ellipsis == '...' ) {
2379 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2381 # Check if there is no need to truncate
2382 if ( $length <= 0 ) {
2383 return $ellipsis; // no text shown, nothing to format
2384 } elseif ( strlen( $text ) <= $length ) {
2385 return $text; // string short enough even *with* HTML
2387 $text = MWTidy
::tidy( $text ); // fix tags
2388 $displayLen = 0; // innerHTML legth so far
2389 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2390 $tagType = 0; // 0-open, 1-close
2391 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2392 $entityState = 0; // 0-not entity, 1-entity
2393 $tag = $ret = $ch = '';
2394 $openTags = array();
2395 $textLen = strlen( $text );
2396 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2398 $lastCh = $pos ?
$text[$pos - 1] : '';
2399 $ret .= $ch; // add to result string
2401 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2402 $entityState = 0; // for bad HTML
2403 $bracketState = 1; // tag started (checking for backslash)
2404 } elseif ( $ch == '>' ) {
2405 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2406 $entityState = 0; // for bad HTML
2407 $bracketState = 0; // out of brackets
2408 } elseif ( $bracketState == 1 ) {
2410 $tagType = 1; // close tag (e.g. "</span>")
2412 $tagType = 0; // open tag (e.g. "<span>")
2415 $bracketState = 2; // building tag name
2416 } elseif ( $bracketState == 2 ) {
2420 // Name found (e.g. "<a href=..."), add on tag attributes...
2421 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2423 } elseif ( $bracketState == 0 ) {
2424 if ( $entityState ) {
2427 $displayLen++
; // entity is one displayed char
2431 $entityState = 1; // entity found, (e.g. " ")
2433 $displayLen++
; // this char is displayed
2434 // Add on the other display text after this...
2435 $skipped = $this->truncate_skip(
2436 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2437 $displayLen +
= $skipped;
2442 # Consider truncation once the display length has reached the maximim.
2443 # Double-check that we're not in the middle of a bracket/entity...
2444 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2445 if ( !$testingEllipsis ) {
2446 $testingEllipsis = true;
2447 # Save where we are; we will truncate here unless
2448 # the ellipsis actually makes the string longer.
2449 $pOpenTags = $openTags; // save state
2450 $pRet = $ret; // save state
2451 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2452 # Ellipsis won't make string longer/equal, the truncation point was OK.
2453 $openTags = $pOpenTags; // reload state
2454 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2455 $ret .= $ellipsis; // add ellipsis
2460 if ( $displayLen == 0 ) {
2461 return ''; // no text shown, nothing to format
2463 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
2464 while ( count( $openTags ) > 0 ) {
2465 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2470 // truncateHtml() helper function
2471 // like strcspn() but adds the skipped chars to $ret
2472 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2474 if ( $start < strlen( $text ) ) {
2475 $skipCount = strcspn( $text, $search, $start, $len );
2476 $ret .= substr( $text, $start, $skipCount );
2481 // truncateHtml() helper function
2482 // (a) push or pop $tag from $openTags as needed
2483 // (b) clear $tag value
2484 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2485 $tag = ltrim( $tag );
2487 if ( $tagType == 0 && $lastCh != '/' ) {
2488 $openTags[] = $tag; // tag opened (didn't close itself)
2489 } else if ( $tagType == 1 ) {
2490 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2491 array_pop( $openTags ); // tag closed
2499 * Grammatical transformations, needed for inflected languages
2500 * Invoked by putting {{grammar:case|word}} in a message
2502 * @param $word string
2503 * @param $case string
2506 function convertGrammar( $word, $case ) {
2507 global $wgGrammarForms;
2508 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2509 return $wgGrammarForms[$this->getCode()][$case][$word];
2515 * Provides an alternative text depending on specified gender.
2516 * Usage {{gender:username|masculine|feminine|neutral}}.
2517 * username is optional, in which case the gender of current user is used,
2518 * but only in (some) interface messages; otherwise default gender is used.
2519 * If second or third parameter are not specified, masculine is used.
2520 * These details may be overriden per language.
2522 function gender( $gender, $forms ) {
2523 if ( !count( $forms ) ) {
2526 $forms = $this->preConvertPlural( $forms, 2 );
2527 if ( $gender === 'male' ) {
2530 if ( $gender === 'female' ) {
2533 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2537 * Plural form transformations, needed for some languages.
2538 * For example, there are 3 form of plural in Russian and Polish,
2539 * depending on "count mod 10". See [[w:Plural]]
2540 * For English it is pretty simple.
2542 * Invoked by putting {{plural:count|wordform1|wordform2}}
2543 * or {{plural:count|wordform1|wordform2|wordform3}}
2545 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2547 * @param $count Integer: non-localized number
2548 * @param $forms Array: different plural forms
2549 * @return string Correct form of plural for $count in this language
2551 function convertPlural( $count, $forms ) {
2552 if ( !count( $forms ) ) {
2555 $forms = $this->preConvertPlural( $forms, 2 );
2557 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2561 * Checks that convertPlural was given an array and pads it to requested
2562 * amound of forms by copying the last one.
2564 * @param $count Integer: How many forms should there be at least
2565 * @param $forms Array of forms given to convertPlural
2566 * @return array Padded array of forms or an exception if not an array
2568 protected function preConvertPlural( /* Array */ $forms, $count ) {
2569 while ( count( $forms ) < $count ) {
2570 $forms[] = $forms[count( $forms ) - 1];
2576 * For translating of expiry times
2577 * @param $str String: the validated block time in English
2578 * @return Somehow translated block time
2579 * @see LanguageFi.php for example implementation
2581 function translateBlockExpiry( $str ) {
2582 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2584 if ( $scBlockExpiryOptions == '-' ) {
2588 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2589 if ( strpos( $option, ':' ) === false ) {
2592 list( $show, $value ) = explode( ':', $option );
2593 if ( strcmp( $str, $value ) == 0 ) {
2594 return htmlspecialchars( trim( $show ) );
2602 * languages like Chinese need to be segmented in order for the diff
2605 * @param $text String
2608 function segmentForDiff( $text ) {
2613 * and unsegment to show the result
2615 * @param $text String
2618 function unsegmentForDiff( $text ) {
2622 # convert text to all supported variants
2623 function autoConvertToAllVariants( $text ) {
2624 return $this->mConverter
->autoConvertToAllVariants( $text );
2627 # convert text to different variants of a language.
2628 function convert( $text ) {
2629 return $this->mConverter
->convert( $text );
2632 # Convert a Title object to a string in the preferred variant
2633 function convertTitle( $title ) {
2634 return $this->mConverter
->convertTitle( $title );
2637 # Check if this is a language with variants
2638 function hasVariants() {
2639 return sizeof( $this->getVariants() ) > 1;
2642 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2643 function armourMath( $text ) {
2644 return $this->mConverter
->armourMath( $text );
2648 * Perform output conversion on a string, and encode for safe HTML output.
2649 * @param $text String text to be converted
2650 * @param $isTitle Bool whether this conversion is for the article title
2652 * @todo this should get integrated somewhere sane
2654 function convertHtml( $text, $isTitle = false ) {
2655 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2658 function convertCategoryKey( $key ) {
2659 return $this->mConverter
->convertCategoryKey( $key );
2663 * Get the list of variants supported by this langauge
2664 * see sample implementation in LanguageZh.php
2666 * @return array an array of language codes
2668 function getVariants() {
2669 return $this->mConverter
->getVariants();
2672 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2673 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2677 * If a language supports multiple variants, it is
2678 * possible that non-existing link in one variant
2679 * actually exists in another variant. this function
2680 * tries to find it. See e.g. LanguageZh.php
2682 * @param $link String: the name of the link
2683 * @param $nt Mixed: the title object of the link
2684 * @param $ignoreOtherCond Boolean: to disable other conditions when
2685 * we need to transclude a template or update a category's link
2686 * @return null the input parameters may be modified upon return
2688 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2689 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2693 * If a language supports multiple variants, converts text
2694 * into an array of all possible variants of the text:
2695 * 'variant' => text in that variant
2697 function convertLinkToAllVariants( $text ) {
2698 return $this->mConverter
->convertLinkToAllVariants( $text );
2702 * returns language specific options used by User::getPageRenderHash()
2703 * for example, the preferred language variant
2707 function getExtraHashOptions() {
2708 return $this->mConverter
->getExtraHashOptions();
2712 * For languages that support multiple variants, the title of an
2713 * article may be displayed differently in different variants. this
2714 * function returns the apporiate title defined in the body of the article.
2718 function getParsedTitle() {
2719 return $this->mConverter
->getParsedTitle();
2723 * Enclose a string with the "no conversion" tag. This is used by
2724 * various functions in the Parser
2726 * @param $text String: text to be tagged for no conversion
2728 * @return string the tagged text
2730 function markNoConversion( $text, $noParse = false ) {
2731 return $this->mConverter
->markNoConversion( $text, $noParse );
2735 * A regular expression to match legal word-trailing characters
2736 * which should be merged onto a link of the form [[foo]]bar.
2740 function linkTrail() {
2741 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2744 function getLangObj() {
2749 * Get the RFC 3066 code for this language object
2751 function getCode() {
2752 return $this->mCode
;
2755 function setCode( $code ) {
2756 $this->mCode
= $code;
2760 * Get the name of a file for a certain language code
2761 * @param $prefix string Prepend this to the filename
2762 * @param $code string Language code
2763 * @param $suffix string Append this to the filename
2764 * @return string $prefix . $mangledCode . $suffix
2766 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2767 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2771 * Get the language code from a file name. Inverse of getFileName()
2772 * @param $filename string $prefix . $languageCode . $suffix
2773 * @param $prefix string Prefix before the language code
2774 * @param $suffix string Suffix after the language code
2775 * @return Language code, or false if $prefix or $suffix isn't found
2777 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2779 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2780 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2781 if ( !count( $m ) ) {
2784 return str_replace( '_', '-', strtolower( $m[1] ) );
2787 static function getMessagesFileName( $code ) {
2789 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2792 static function getClassFileName( $code ) {
2794 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2798 * Get the fallback for a given language
2800 static function getFallbackFor( $code ) {
2801 if ( $code === 'en' ) {
2805 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2810 * Get all messages for a given language
2811 * WARNING: this may take a long time
2813 static function getMessagesFor( $code ) {
2814 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2818 * Get a message for a given language
2820 static function getMessageFor( $key, $code ) {
2821 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2824 function fixVariableInNamespace( $talk ) {
2825 if ( strpos( $talk, '$1' ) === false ) {
2829 global $wgMetaNamespace;
2830 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2832 # Allow grammar transformations
2833 # Allowing full message-style parsing would make simple requests
2834 # such as action=raw much more expensive than they need to be.
2835 # This will hopefully cover most cases.
2836 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2837 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2838 return str_replace( ' ', '_', $talk );
2841 function replaceGrammarInNamespace( $m ) {
2842 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2845 static function getCaseMaps() {
2846 static $wikiUpperChars, $wikiLowerChars;
2847 if ( isset( $wikiUpperChars ) ) {
2848 return array( $wikiUpperChars, $wikiLowerChars );
2851 wfProfileIn( __METHOD__
);
2852 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2853 if ( $arr === false ) {
2854 throw new MWException(
2855 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2858 wfProfileOut( __METHOD__
);
2859 return array( $wikiUpperChars, $wikiLowerChars );
2862 function formatTimePeriod( $seconds ) {
2863 if ( $seconds < 10 ) {
2864 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2865 } elseif ( $seconds < 60 ) {
2866 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2867 } elseif ( $seconds < 3600 ) {
2868 $minutes = floor( $seconds / 60 );
2869 $secondsPart = round( fmod( $seconds, 60 ) );
2870 if ( $secondsPart == 60 ) {
2874 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2875 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2877 $hours = floor( $seconds / 3600 );
2878 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2879 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2880 if ( $secondsPart == 60 ) {
2884 if ( $minutes == 60 ) {
2888 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2889 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2890 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2894 function formatBitrate( $bps ) {
2895 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2897 return $this->formatNum( $bps ) . $units[0];
2899 $unitIndex = floor( log10( $bps ) / 3 );
2900 $mantissa = $bps / pow( 1000, $unitIndex );
2901 if ( $mantissa < 10 ) {
2902 $mantissa = round( $mantissa, 1 );
2904 $mantissa = round( $mantissa );
2906 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2910 * Format a size in bytes for output, using an appropriate
2911 * unit (B, KB, MB or GB) according to the magnitude in question
2913 * @param $size Size to format
2914 * @return string Plain text (not HTML)
2916 function formatSize( $size ) {
2917 // For small sizes no decimal places necessary
2919 if ( $size > 1024 ) {
2920 $size = $size / 1024;
2921 if ( $size > 1024 ) {
2922 $size = $size / 1024;
2923 // For MB and bigger two decimal places are smarter
2925 if ( $size > 1024 ) {
2926 $size = $size / 1024;
2927 $msg = 'size-gigabytes';
2929 $msg = 'size-megabytes';
2932 $msg = 'size-kilobytes';
2935 $msg = 'size-bytes';
2937 $size = round( $size, $round );
2938 $text = $this->getMessageFromDB( $msg );
2939 return str_replace( '$1', $this->formatNum( $size ), $text );
2943 * Get the conversion rule title, if any.
2945 function getConvRuleTitle() {
2946 return $this->mConverter
->getConvRuleTitle();
2950 * Given a string, convert it to a (hopefully short) key that can be used
2951 * for efficient sorting. A binary sort according to the sortkeys
2952 * corresponds to a logical sort of the corresponding strings. Current
2953 * code expects that a null character should sort before all others, but
2954 * has no other particular expectations (and that one can be changed if
2957 * @param string $string UTF-8 string
2958 * @return string Binary sortkey
2960 public function convertToSortkey( $string ) {
2961 # Fake function for now
2962 return strtoupper( $string );
2966 * Does it make sense for lists to be split up into sections based on their
2967 * first letter? Logogram-based scripts probably want to return false.
2969 * TODO: Use this in CategoryPage.php.
2973 public function usesFirstLettersInLists() {
2978 * Given a string, return the logical "first letter" to be used for
2979 * grouping on category pages and so on. This has to be coordinated
2980 * carefully with convertToSortkey(), or else the sorted list might jump
2981 * back and forth between the same "initial letters" or other pathological
2982 * behavior. For instance, if you just return the first character, but "a"
2983 * sorts the same as "A" based on convertToSortkey(), then you might get a
2995 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2996 * Obviously, this is ignored if usesFirstLettersInLists() is false.
2998 * @param string $string UTF-8 string
2999 * @return string UTF-8 string corresponding to the first letter of input
3001 public function firstLetterForLists( $string ) {
3002 if ( $string[0] == "\0" ) {
3003 $string = substr( $string, 1 );
3005 return strtoupper( $this->firstChar( $string ) );