Fixed r76560: one more caller of now-private toUnsigned6
[mediawiki.git] / languages / Language.php
blob2829153fda6ffe71669ddfb9d38a0f71be99ed00
1 <?php
2 /**
3 * Internationalisation code
5 * @file
6 * @ingroup Language
7 */
9 /**
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
22 global $wgInputEncoding, $wgOutputEncoding;
24 /**
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' );
34 /**
35 * a fake language converter
37 * @ingroup Language
39 class FakeConverter {
40 var $mLang;
41 function __construct( $langobj ) { $this->mLang = $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang->getCode() ); }
46 function getPreferredVariant() { return $this->mLang->getCode(); }
47 function getDefaultVariant() { return $this->mLang->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
59 /**
60 * Internationalisation code
61 * @ingroup Language
63 class Language {
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
71 /**
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
81 'friday', 'saturday'
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
91 'december'
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
96 'december-gen'
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
136 static function factory( $code ) {
137 if ( !isset( self::$mLangObjCache[$code] ) ) {
138 if ( count( self::$mLangObjCache ) > 10 ) {
139 // Don't keep a billion objects around, that's stupid.
140 self::$mLangObjCache = array();
142 self::$mLangObjCache[$code] = self::newFromCode( $code );
144 return self::$mLangObjCache[$code];
148 * Create a language object for a given language code
150 protected static function newFromCode( $code ) {
151 global $IP;
152 static $recursionLevel = 0;
153 if ( $code == 'en' ) {
154 $class = 'Language';
155 } else {
156 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
157 // Preload base classes to work around APC/PHP5 bug
158 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
159 include_once( "$IP/languages/classes/$class.deps.php" );
161 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
162 include_once( "$IP/languages/classes/$class.php" );
166 if ( $recursionLevel > 5 ) {
167 throw new MWException( "Language fallback loop detected when creating class $class\n" );
170 if ( !class_exists( $class ) ) {
171 $fallback = Language::getFallbackFor( $code );
172 ++$recursionLevel;
173 $lang = Language::newFromCode( $fallback );
174 --$recursionLevel;
175 $lang->setCode( $code );
176 } else {
177 $lang = new $class;
179 return $lang;
183 * Get the LocalisationCache instance
185 public static function getLocalisationCache() {
186 if ( is_null( self::$dataCache ) ) {
187 global $wgLocalisationCacheConf;
188 $class = $wgLocalisationCacheConf['class'];
189 self::$dataCache = new $class( $wgLocalisationCacheConf );
191 return self::$dataCache;
194 function __construct() {
195 $this->mConverter = new FakeConverter( $this );
196 // Set the code to the name of the descendant
197 if ( get_class( $this ) == 'Language' ) {
198 $this->mCode = 'en';
199 } else {
200 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
202 self::getLocalisationCache();
206 * Reduce memory usage
208 function __destruct() {
209 foreach ( $this as $name => $value ) {
210 unset( $this->$name );
215 * Hook which will be called if this is the content language.
216 * Descendants can use this to register hook functions or modify globals
218 function initContLang() { }
221 * @deprecated Use User::getDefaultOptions()
222 * @return array
224 function getDefaultUserOptions() {
225 wfDeprecated( __METHOD__ );
226 return User::getDefaultOptions();
229 function getFallbackLanguageCode() {
230 if ( $this->mCode === 'en' ) {
231 return false;
232 } else {
233 return self::$dataCache->getItem( $this->mCode, 'fallback' );
238 * Exports $wgBookstoreListEn
239 * @return array
241 function getBookstoreList() {
242 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
246 * @return array
248 function getNamespaces() {
249 if ( is_null( $this->namespaceNames ) ) {
250 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
252 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
253 $validNamespaces = MWNamespace::getCanonicalNamespaces();
255 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
257 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
258 if ( $wgMetaNamespaceTalk ) {
259 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
260 } else {
261 $talk = $this->namespaceNames[NS_PROJECT_TALK];
262 $this->namespaceNames[NS_PROJECT_TALK] =
263 $this->fixVariableInNamespace( $talk );
266 # Sometimes a language will be localised but not actually exist on this wiki.
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.
286 * @return array
288 function getFormattedNamespaces() {
289 $ns = $this->getNamespaces();
290 foreach ( $ns as $k => $v ) {
291 $ns[$k] = strtr( $v, '_', ' ' );
293 return $ns;
297 * Get a namespace value by key
298 * <code>
299 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
300 * echo $mw_ns; // prints 'MediaWiki'
301 * </code>
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
314 * producing output.
316 * @return array
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' );
340 if ( !$aliases ) {
341 $aliases = array();
342 } else {
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 ) {
390 return $ns;
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
400 * @return 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() {
415 return array(
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';
441 } else {
442 return $df;
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 ) {
474 return $allNames;
477 global $IP;
478 $names = array();
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];
486 closedir( $dir );
487 return $names;
491 * Get a message from the MediaWiki namespace.
493 * @param $msg String: message name
494 * @return string
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 ) ) {
503 return '';
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)
550 * @return int
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' );
566 return $date;
568 # Unrecognized timezone, default to 'Offset' with the stored offset.
569 $data[0] = 'Offset';
572 $minDiff = 0;
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] );
580 } else {
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;
589 } else {
590 $minDiff = intval( $data[0] ) * 60;
594 # No difference ? Return time unchanged
595 if ( 0 == $minDiff ) {
596 return $ts;
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.
603 $t = mktime( (
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 );
612 wfRestoreWarnings();
614 return $date;
618 * This is a workalike of PHP's date() function, but with better
619 * internationalisation, a reduced set of format characters, and a better
620 * escaping format.
622 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
623 * PHP manual for definitions. There are a number of extensions, which
624 * start with "x":
626 * xn Do not translate digits of the next numeric format character
627 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
628 * xr Use roman numerals for the next numeric format character
629 * xh Use hebrew numerals for the next numeric format character
630 * xx Literal x
631 * xg Genitive month name
633 * xij j (day number) in Iranian calendar
634 * xiF F (month name) in Iranian calendar
635 * xin n (month number) in Iranian calendar
636 * xiY Y (full year) in Iranian calendar
638 * xjj j (day number) in Hebrew calendar
639 * xjF F (month name) in Hebrew calendar
640 * xjt t (days in month) in Hebrew calendar
641 * xjx xg (genitive month name) in Hebrew calendar
642 * xjn n (month number) in Hebrew calendar
643 * xjY Y (full year) in Hebrew calendar
645 * xmj j (day number) in Hijri calendar
646 * xmF F (month name) in Hijri calendar
647 * xmn n (month number) in Hijri calendar
648 * xmY Y (full year) in Hijri calendar
650 * xkY Y (full year) in Thai solar calendar. Months and days are
651 * identical to the Gregorian calendar
652 * xoY Y (full year) in Minguo calendar or Juche year.
653 * Months and days are identical to the
654 * Gregorian calendar
655 * xtY Y (full year) in Japanese nengo. Months and days are
656 * identical to the Gregorian calendar
658 * Characters enclosed in double quotes will be considered literal (with
659 * the quotes themselves removed). Unmatched quotes will be considered
660 * literal quotes. Example:
662 * "The month is" F => The month is January
663 * i's" => 20'11"
665 * Backslash escaping is also supported.
667 * Input timestamp is assumed to be pre-normalized to the desired local
668 * time zone, if any.
670 * @param $format String
671 * @param $ts String: 14-character timestamp
672 * YYYYMMDDHHMMSS
673 * 01234567890123
674 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
676 function sprintfDate( $format, $ts ) {
677 $s = '';
678 $raw = false;
679 $roman = false;
680 $hebrewNum = false;
681 $unix = false;
682 $rawToggle = false;
683 $iranian = false;
684 $hebrew = false;
685 $hijri = false;
686 $thai = false;
687 $minguo = false;
688 $tenno = false;
689 for ( $p = 0; $p < strlen( $format ); $p++ ) {
690 $num = false;
691 $code = $format[$p];
692 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
693 $code .= $format[++$p];
696 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
697 $code .= $format[++$p];
700 switch ( $code ) {
701 case 'xx':
702 $s .= 'x';
703 break;
704 case 'xn':
705 $raw = true;
706 break;
707 case 'xN':
708 $rawToggle = !$rawToggle;
709 break;
710 case 'xr':
711 $roman = true;
712 break;
713 case 'xh':
714 $hebrewNum = true;
715 break;
716 case 'xg':
717 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
718 break;
719 case 'xjx':
720 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
721 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
722 break;
723 case 'd':
724 $num = substr( $ts, 6, 2 );
725 break;
726 case 'D':
727 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
728 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
729 break;
730 case 'j':
731 $num = intval( substr( $ts, 6, 2 ) );
732 break;
733 case 'xij':
734 if ( !$iranian ) {
735 $iranian = self::tsToIranian( $ts );
737 $num = $iranian[2];
738 break;
739 case 'xmj':
740 if ( !$hijri ) {
741 $hijri = self::tsToHijri( $ts );
743 $num = $hijri[2];
744 break;
745 case 'xjj':
746 if ( !$hebrew ) {
747 $hebrew = self::tsToHebrew( $ts );
749 $num = $hebrew[2];
750 break;
751 case 'l':
752 if ( !$unix ) {
753 $unix = wfTimestamp( TS_UNIX, $ts );
755 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
756 break;
757 case 'N':
758 if ( !$unix ) {
759 $unix = wfTimestamp( TS_UNIX, $ts );
761 $w = gmdate( 'w', $unix );
762 $num = $w ? $w : 7;
763 break;
764 case 'w':
765 if ( !$unix ) {
766 $unix = wfTimestamp( TS_UNIX, $ts );
768 $num = gmdate( 'w', $unix );
769 break;
770 case 'z':
771 if ( !$unix ) {
772 $unix = wfTimestamp( TS_UNIX, $ts );
774 $num = gmdate( 'z', $unix );
775 break;
776 case 'W':
777 if ( !$unix ) {
778 $unix = wfTimestamp( TS_UNIX, $ts );
780 $num = gmdate( 'W', $unix );
781 break;
782 case 'F':
783 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
784 break;
785 case 'xiF':
786 if ( !$iranian ) {
787 $iranian = self::tsToIranian( $ts );
789 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
790 break;
791 case 'xmF':
792 if ( !$hijri ) {
793 $hijri = self::tsToHijri( $ts );
795 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
796 break;
797 case 'xjF':
798 if ( !$hebrew ) {
799 $hebrew = self::tsToHebrew( $ts );
801 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
802 break;
803 case 'm':
804 $num = substr( $ts, 4, 2 );
805 break;
806 case 'M':
807 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
808 break;
809 case 'n':
810 $num = intval( substr( $ts, 4, 2 ) );
811 break;
812 case 'xin':
813 if ( !$iranian ) {
814 $iranian = self::tsToIranian( $ts );
816 $num = $iranian[1];
817 break;
818 case 'xmn':
819 if ( !$hijri ) {
820 $hijri = self::tsToHijri ( $ts );
822 $num = $hijri[1];
823 break;
824 case 'xjn':
825 if ( !$hebrew ) {
826 $hebrew = self::tsToHebrew( $ts );
828 $num = $hebrew[1];
829 break;
830 case 't':
831 if ( !$unix ) {
832 $unix = wfTimestamp( TS_UNIX, $ts );
834 $num = gmdate( 't', $unix );
835 break;
836 case 'xjt':
837 if ( !$hebrew ) {
838 $hebrew = self::tsToHebrew( $ts );
840 $num = $hebrew[3];
841 break;
842 case 'L':
843 if ( !$unix ) {
844 $unix = wfTimestamp( TS_UNIX, $ts );
846 $num = gmdate( 'L', $unix );
847 break;
848 case 'o':
849 if ( !$unix ) {
850 $unix = wfTimestamp( TS_UNIX, $ts );
852 $num = date( 'o', $unix );
853 break;
854 case 'Y':
855 $num = substr( $ts, 0, 4 );
856 break;
857 case 'xiY':
858 if ( !$iranian ) {
859 $iranian = self::tsToIranian( $ts );
861 $num = $iranian[0];
862 break;
863 case 'xmY':
864 if ( !$hijri ) {
865 $hijri = self::tsToHijri( $ts );
867 $num = $hijri[0];
868 break;
869 case 'xjY':
870 if ( !$hebrew ) {
871 $hebrew = self::tsToHebrew( $ts );
873 $num = $hebrew[0];
874 break;
875 case 'xkY':
876 if ( !$thai ) {
877 $thai = self::tsToYear( $ts, 'thai' );
879 $num = $thai[0];
880 break;
881 case 'xoY':
882 if ( !$minguo ) {
883 $minguo = self::tsToYear( $ts, 'minguo' );
885 $num = $minguo[0];
886 break;
887 case 'xtY':
888 if ( !$tenno ) {
889 $tenno = self::tsToYear( $ts, 'tenno' );
891 $num = $tenno[0];
892 break;
893 case 'y':
894 $num = substr( $ts, 2, 2 );
895 break;
896 case 'a':
897 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
898 break;
899 case 'A':
900 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
901 break;
902 case 'g':
903 $h = substr( $ts, 8, 2 );
904 $num = $h % 12 ? $h % 12 : 12;
905 break;
906 case 'G':
907 $num = intval( substr( $ts, 8, 2 ) );
908 break;
909 case 'h':
910 $h = substr( $ts, 8, 2 );
911 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
912 break;
913 case 'H':
914 $num = substr( $ts, 8, 2 );
915 break;
916 case 'i':
917 $num = substr( $ts, 10, 2 );
918 break;
919 case 's':
920 $num = substr( $ts, 12, 2 );
921 break;
922 case 'c':
923 if ( !$unix ) {
924 $unix = wfTimestamp( TS_UNIX, $ts );
926 $s .= gmdate( 'c', $unix );
927 break;
928 case 'r':
929 if ( !$unix ) {
930 $unix = wfTimestamp( TS_UNIX, $ts );
932 $s .= gmdate( 'r', $unix );
933 break;
934 case 'U':
935 if ( !$unix ) {
936 $unix = wfTimestamp( TS_UNIX, $ts );
938 $num = $unix;
939 break;
940 case '\\':
941 # Backslash escaping
942 if ( $p < strlen( $format ) - 1 ) {
943 $s .= $format[++$p];
944 } else {
945 $s .= '\\';
947 break;
948 case '"':
949 # Quoted literal
950 if ( $p < strlen( $format ) - 1 ) {
951 $endQuote = strpos( $format, '"', $p + 1 );
952 if ( $endQuote === false ) {
953 # No terminating quote, assume literal "
954 $s .= '"';
955 } else {
956 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
957 $p = $endQuote;
959 } else {
960 # Quote at end of string, assume literal "
961 $s .= '"';
963 break;
964 default:
965 $s .= $format[$p];
967 if ( $num !== false ) {
968 if ( $rawToggle || $raw ) {
969 $s .= $num;
970 $raw = false;
971 } elseif ( $roman ) {
972 $s .= self::romanNumeral( $num );
973 $roman = false;
974 } elseif ( $hebrewNum ) {
975 $s .= self::hebrewNumeral( $num );
976 $hebrewNum = false;
977 } else {
978 $s .= $this->formatNum( $num, true );
982 return $s;
985 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
986 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
988 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
989 * Gregorian dates to Iranian dates. Originally written in C, it
990 * is released under the terms of GNU Lesser General Public
991 * License. Conversion to PHP was performed by Niklas Laxström.
993 * Link: http://www.farsiweb.info/jalali/jalali.c
995 private static function tsToIranian( $ts ) {
996 $gy = substr( $ts, 0, 4 ) -1600;
997 $gm = substr( $ts, 4, 2 ) -1;
998 $gd = substr( $ts, 6, 2 ) -1;
1000 # Days passed from the beginning (including leap years)
1001 $gDayNo = 365 * $gy
1002 + floor( ( $gy + 3 ) / 4 )
1003 - floor( ( $gy + 99 ) / 100 )
1004 + floor( ( $gy + 399 ) / 400 );
1007 // Add days of the past months of this year
1008 for ( $i = 0; $i < $gm; $i++ ) {
1009 $gDayNo += self::$GREG_DAYS[$i];
1012 // Leap years
1013 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1014 $gDayNo++;
1017 // Days passed in current month
1018 $gDayNo += $gd;
1020 $jDayNo = $gDayNo - 79;
1022 $jNp = floor( $jDayNo / 12053 );
1023 $jDayNo %= 12053;
1025 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1026 $jDayNo %= 1461;
1028 if ( $jDayNo >= 366 ) {
1029 $jy += floor( ( $jDayNo - 1 ) / 365 );
1030 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1033 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1034 $jDayNo -= self::$IRANIAN_DAYS[$i];
1037 $jm = $i + 1;
1038 $jd = $jDayNo + 1;
1040 return array( $jy, $jm, $jd );
1044 * Converting Gregorian dates to Hijri dates.
1046 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1048 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1050 private static function tsToHijri( $ts ) {
1051 $year = substr( $ts, 0, 4 );
1052 $month = substr( $ts, 4, 2 );
1053 $day = substr( $ts, 6, 2 );
1055 $zyr = $year;
1056 $zd = $day;
1057 $zm = $month;
1058 $zy = $zyr;
1060 if (
1061 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1062 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1065 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1066 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1067 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1068 $zd - 32075;
1069 } else {
1070 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1071 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1074 $zl = $zjd -1948440 + 10632;
1075 $zn = (int)( ( $zl - 1 ) / 10631 );
1076 $zl = $zl - 10631 * $zn + 354;
1077 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1078 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1079 $zm = (int)( ( 24 * $zl ) / 709 );
1080 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1081 $zy = 30 * $zn + $zj - 30;
1083 return array( $zy, $zm, $zd );
1087 * Converting Gregorian dates to Hebrew dates.
1089 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1090 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1091 * to translate the relevant functions into PHP and release them under
1092 * GNU GPL.
1094 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1095 * and Adar II is 14. In a non-leap year, Adar is 6.
1097 private static function tsToHebrew( $ts ) {
1098 # Parse date
1099 $year = substr( $ts, 0, 4 );
1100 $month = substr( $ts, 4, 2 );
1101 $day = substr( $ts, 6, 2 );
1103 # Calculate Hebrew year
1104 $hebrewYear = $year + 3760;
1106 # Month number when September = 1, August = 12
1107 $month += 4;
1108 if ( $month > 12 ) {
1109 # Next year
1110 $month -= 12;
1111 $year++;
1112 $hebrewYear++;
1115 # Calculate day of year from 1 September
1116 $dayOfYear = $day;
1117 for ( $i = 1; $i < $month; $i++ ) {
1118 if ( $i == 6 ) {
1119 # February
1120 $dayOfYear += 28;
1121 # Check if the year is leap
1122 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1123 $dayOfYear++;
1125 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1126 $dayOfYear += 30;
1127 } else {
1128 $dayOfYear += 31;
1132 # Calculate the start of the Hebrew year
1133 $start = self::hebrewYearStart( $hebrewYear );
1135 # Calculate next year's start
1136 if ( $dayOfYear <= $start ) {
1137 # Day is before the start of the year - it is the previous year
1138 # Next year's start
1139 $nextStart = $start;
1140 # Previous year
1141 $year--;
1142 $hebrewYear--;
1143 # Add days since previous year's 1 September
1144 $dayOfYear += 365;
1145 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1146 # Leap year
1147 $dayOfYear++;
1149 # Start of the new (previous) year
1150 $start = self::hebrewYearStart( $hebrewYear );
1151 } else {
1152 # Next year's start
1153 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1156 # Calculate Hebrew day of year
1157 $hebrewDayOfYear = $dayOfYear - $start;
1159 # Difference between year's days
1160 $diff = $nextStart - $start;
1161 # Add 12 (or 13 for leap years) days to ignore the difference between
1162 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1163 # difference is only about the year type
1164 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1165 $diff += 13;
1166 } else {
1167 $diff += 12;
1170 # Check the year pattern, and is leap year
1171 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1172 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1173 # and non-leap years
1174 $yearPattern = $diff % 30;
1175 # Check if leap year
1176 $isLeap = $diff >= 30;
1178 # Calculate day in the month from number of day in the Hebrew year
1179 # Don't check Adar - if the day is not in Adar, we will stop before;
1180 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1181 $hebrewDay = $hebrewDayOfYear;
1182 $hebrewMonth = 1;
1183 $days = 0;
1184 while ( $hebrewMonth <= 12 ) {
1185 # Calculate days in this month
1186 if ( $isLeap && $hebrewMonth == 6 ) {
1187 # Adar in a leap year
1188 if ( $isLeap ) {
1189 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1190 $days = 30;
1191 if ( $hebrewDay <= $days ) {
1192 # Day in Adar I
1193 $hebrewMonth = 13;
1194 } else {
1195 # Subtract the days of Adar I
1196 $hebrewDay -= $days;
1197 # Try Adar II
1198 $days = 29;
1199 if ( $hebrewDay <= $days ) {
1200 # Day in Adar II
1201 $hebrewMonth = 14;
1205 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1206 # Cheshvan in a complete year (otherwise as the rule below)
1207 $days = 30;
1208 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1209 # Kislev in an incomplete year (otherwise as the rule below)
1210 $days = 29;
1211 } else {
1212 # Odd months have 30 days, even have 29
1213 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1215 if ( $hebrewDay <= $days ) {
1216 # In the current month
1217 break;
1218 } else {
1219 # Subtract the days of the current month
1220 $hebrewDay -= $days;
1221 # Try in the next month
1222 $hebrewMonth++;
1226 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1230 * This calculates the Hebrew year start, as days since 1 September.
1231 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1232 * Used for Hebrew date.
1234 private static function hebrewYearStart( $year ) {
1235 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1236 $b = intval( ( $year - 1 ) % 4 );
1237 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1238 if ( $m < 0 ) {
1239 $m--;
1241 $Mar = intval( $m );
1242 if ( $m < 0 ) {
1243 $m++;
1245 $m -= $Mar;
1247 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1248 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1249 $Mar++;
1250 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1251 $Mar += 2;
1252 } else if ( $c == 2 || $c == 4 || $c == 6 ) {
1253 $Mar++;
1256 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1257 return $Mar;
1261 * Algorithm to convert Gregorian dates to Thai solar dates,
1262 * Minguo dates or Minguo dates.
1264 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1265 * http://en.wikipedia.org/wiki/Minguo_calendar
1266 * http://en.wikipedia.org/wiki/Japanese_era_name
1268 * @param $ts String: 14-character timestamp
1269 * @param $cName String: calender name
1270 * @return Array: converted year, month, day
1272 private static function tsToYear( $ts, $cName ) {
1273 $gy = substr( $ts, 0, 4 );
1274 $gm = substr( $ts, 4, 2 );
1275 $gd = substr( $ts, 6, 2 );
1277 if ( !strcmp( $cName, 'thai' ) ) {
1278 # Thai solar dates
1279 # Add 543 years to the Gregorian calendar
1280 # Months and days are identical
1281 $gy_offset = $gy + 543;
1282 } else if ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1283 # Minguo dates
1284 # Deduct 1911 years from the Gregorian calendar
1285 # Months and days are identical
1286 $gy_offset = $gy - 1911;
1287 } else if ( !strcmp( $cName, 'tenno' ) ) {
1288 # Nengō dates up to Meiji period
1289 # Deduct years from the Gregorian calendar
1290 # depending on the nengo periods
1291 # Months and days are identical
1292 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1293 # Meiji period
1294 $gy_gannen = $gy - 1868 + 1;
1295 $gy_offset = $gy_gannen;
1296 if ( $gy_gannen == 1 ) {
1297 $gy_offset = '元';
1299 $gy_offset = '明治' . $gy_offset;
1300 } else if (
1301 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1302 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1303 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1304 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1305 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1308 # Taishō period
1309 $gy_gannen = $gy - 1912 + 1;
1310 $gy_offset = $gy_gannen;
1311 if ( $gy_gannen == 1 ) {
1312 $gy_offset = '元';
1314 $gy_offset = '大正' . $gy_offset;
1315 } else if (
1316 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1317 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1318 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1321 # Shōwa period
1322 $gy_gannen = $gy - 1926 + 1;
1323 $gy_offset = $gy_gannen;
1324 if ( $gy_gannen == 1 ) {
1325 $gy_offset = '元';
1327 $gy_offset = '昭和' . $gy_offset;
1328 } else {
1329 # Heisei period
1330 $gy_gannen = $gy - 1989 + 1;
1331 $gy_offset = $gy_gannen;
1332 if ( $gy_gannen == 1 ) {
1333 $gy_offset = '元';
1335 $gy_offset = '平成' . $gy_offset;
1337 } else {
1338 $gy_offset = $gy;
1341 return array( $gy_offset, $gm, $gd );
1345 * Roman number formatting up to 3000
1347 static function romanNumeral( $num ) {
1348 static $table = array(
1349 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1350 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1351 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1352 array( '', 'M', 'MM', 'MMM' )
1355 $num = intval( $num );
1356 if ( $num > 3000 || $num <= 0 ) {
1357 return $num;
1360 $s = '';
1361 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1362 if ( $num >= $pow10 ) {
1363 $s .= $table[$i][floor( $num / $pow10 )];
1365 $num = $num % $pow10;
1367 return $s;
1371 * Hebrew Gematria number formatting up to 9999
1373 static function hebrewNumeral( $num ) {
1374 static $table = array(
1375 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1376 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1377 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1378 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1381 $num = intval( $num );
1382 if ( $num > 9999 || $num <= 0 ) {
1383 return $num;
1386 $s = '';
1387 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1388 if ( $num >= $pow10 ) {
1389 if ( $num == 15 || $num == 16 ) {
1390 $s .= $table[0][9] . $table[0][$num - 9];
1391 $num = 0;
1392 } else {
1393 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1394 if ( $pow10 == 1000 ) {
1395 $s .= "'";
1399 $num = $num % $pow10;
1401 if ( strlen( $s ) == 2 ) {
1402 $str = $s . "'";
1403 } else {
1404 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1405 $str .= substr( $s, strlen( $s ) - 2, 2 );
1407 $start = substr( $str, 0, strlen( $str ) - 2 );
1408 $end = substr( $str, strlen( $str ) - 2 );
1409 switch( $end ) {
1410 case 'כ':
1411 $str = $start . 'ך';
1412 break;
1413 case 'מ':
1414 $str = $start . 'ם';
1415 break;
1416 case 'נ':
1417 $str = $start . 'ן';
1418 break;
1419 case 'פ':
1420 $str = $start . 'ף';
1421 break;
1422 case 'צ':
1423 $str = $start . 'ץ';
1424 break;
1426 return $str;
1430 * This is meant to be used by time(), date(), and timeanddate() to get
1431 * the date preference they're supposed to use, it should be used in
1432 * all children.
1434 *<code>
1435 * function timeanddate([...], $format = true) {
1436 * $datePreference = $this->dateFormat($format);
1437 * [...]
1439 *</code>
1441 * @param $usePrefs Mixed: if true, the user's preference is used
1442 * if false, the site/language default is used
1443 * if int/string, assumed to be a format.
1444 * @return string
1446 function dateFormat( $usePrefs = true ) {
1447 global $wgUser;
1449 if ( is_bool( $usePrefs ) ) {
1450 if ( $usePrefs ) {
1451 $datePreference = $wgUser->getDatePreference();
1452 } else {
1453 $datePreference = (string)User::getDefaultOption( 'date' );
1455 } else {
1456 $datePreference = (string)$usePrefs;
1459 // return int
1460 if ( $datePreference == '' ) {
1461 return 'default';
1464 return $datePreference;
1468 * Get a format string for a given type and preference
1469 * @param $type May be date, time or both
1470 * @param $pref The format name as it appears in Messages*.php
1472 function getDateFormatString( $type, $pref ) {
1473 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1474 if ( $pref == 'default' ) {
1475 $pref = $this->getDefaultDateFormat();
1476 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1477 } else {
1478 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1479 if ( is_null( $df ) ) {
1480 $pref = $this->getDefaultDateFormat();
1481 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1484 $this->dateFormatStrings[$type][$pref] = $df;
1486 return $this->dateFormatStrings[$type][$pref];
1490 * @param $ts Mixed: the time format which needs to be turned into a
1491 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1492 * @param $adj Bool: whether to adjust the time output according to the
1493 * user configured offset ($timecorrection)
1494 * @param $format Mixed: true to use user's date format preference
1495 * @param $timecorrection String: the time offset as returned by
1496 * validateTimeZone() in Special:Preferences
1497 * @return string
1499 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1500 $ts = wfTimestamp( TS_MW, $ts );
1501 if ( $adj ) {
1502 $ts = $this->userAdjust( $ts, $timecorrection );
1504 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1505 return $this->sprintfDate( $df, $ts );
1509 * @param $ts Mixed: the time format which needs to be turned into a
1510 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1511 * @param $adj Bool: whether to adjust the time output according to the
1512 * user configured offset ($timecorrection)
1513 * @param $format Mixed: true to use user's date format preference
1514 * @param $timecorrection String: the time offset as returned by
1515 * validateTimeZone() in Special:Preferences
1516 * @return string
1518 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1519 $ts = wfTimestamp( TS_MW, $ts );
1520 if ( $adj ) {
1521 $ts = $this->userAdjust( $ts, $timecorrection );
1523 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1524 return $this->sprintfDate( $df, $ts );
1528 * @param $ts Mixed: the time format which needs to be turned into a
1529 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1530 * @param $adj Bool: whether to adjust the time output according to the
1531 * user configured offset ($timecorrection)
1532 * @param $format Mixed: what format to return, if it's false output the
1533 * default one (default true)
1534 * @param $timecorrection String: the time offset as returned by
1535 * validateTimeZone() in Special:Preferences
1536 * @return string
1538 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1539 $ts = wfTimestamp( TS_MW, $ts );
1540 if ( $adj ) {
1541 $ts = $this->userAdjust( $ts, $timecorrection );
1543 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1544 return $this->sprintfDate( $df, $ts );
1547 function getMessage( $key ) {
1548 return self::$dataCache->getSubitem( $this->getCodeForMessage(), 'messages', $key );
1551 function getAllMessages() {
1552 return self::$dataCache->getItem( $this->getCodeForMessage(), 'messages' );
1555 function iconv( $in, $out, $string ) {
1556 # This is a wrapper for iconv in all languages except esperanto,
1557 # which does some nasty x-conversions beforehand
1559 # Even with //IGNORE iconv can whine about illegal characters in
1560 # *input* string. We just ignore those too.
1561 # REF: http://bugs.php.net/bug.php?id=37166
1562 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1563 wfSuppressWarnings();
1564 $text = iconv( $in, $out . '//IGNORE', $string );
1565 wfRestoreWarnings();
1566 return $text;
1569 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1570 function ucwordbreaksCallbackAscii( $matches ) {
1571 return $this->ucfirst( $matches[1] );
1574 function ucwordbreaksCallbackMB( $matches ) {
1575 return mb_strtoupper( $matches[0] );
1578 function ucCallback( $matches ) {
1579 list( $wikiUpperChars ) = self::getCaseMaps();
1580 return strtr( $matches[1], $wikiUpperChars );
1583 function lcCallback( $matches ) {
1584 list( , $wikiLowerChars ) = self::getCaseMaps();
1585 return strtr( $matches[1], $wikiLowerChars );
1588 function ucwordsCallbackMB( $matches ) {
1589 return mb_strtoupper( $matches[0] );
1592 function ucwordsCallbackWiki( $matches ) {
1593 list( $wikiUpperChars ) = self::getCaseMaps();
1594 return strtr( $matches[0], $wikiUpperChars );
1598 * Make a string's first character uppercase
1600 function ucfirst( $str ) {
1601 $o = ord( $str );
1602 if ( $o < 96 ) { // if already uppercase...
1603 return $str;
1604 } elseif ( $o < 128 ) {
1605 return ucfirst( $str ); // use PHP's ucfirst()
1606 } else {
1607 // fall back to more complex logic in case of multibyte strings
1608 return $this->uc( $str, true );
1613 * Convert a string to uppercase
1615 function uc( $str, $first = false ) {
1616 if ( function_exists( 'mb_strtoupper' ) ) {
1617 if ( $first ) {
1618 if ( $this->isMultibyte( $str ) ) {
1619 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1620 } else {
1621 return ucfirst( $str );
1623 } else {
1624 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1626 } else {
1627 if ( $this->isMultibyte( $str ) ) {
1628 $x = $first ? '^' : '';
1629 return preg_replace_callback(
1630 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1631 array( $this, 'ucCallback' ),
1632 $str
1634 } else {
1635 return $first ? ucfirst( $str ) : strtoupper( $str );
1640 function lcfirst( $str ) {
1641 $o = ord( $str );
1642 if ( !$o ) {
1643 return strval( $str );
1644 } elseif ( $o >= 128 ) {
1645 return $this->lc( $str, true );
1646 } elseif ( $o > 96 ) {
1647 return $str;
1648 } else {
1649 $str[0] = strtolower( $str[0] );
1650 return $str;
1654 function lc( $str, $first = false ) {
1655 if ( function_exists( 'mb_strtolower' ) ) {
1656 if ( $first ) {
1657 if ( $this->isMultibyte( $str ) ) {
1658 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1659 } else {
1660 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1662 } else {
1663 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1665 } else {
1666 if ( $this->isMultibyte( $str ) ) {
1667 $x = $first ? '^' : '';
1668 return preg_replace_callback(
1669 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1670 array( $this, 'lcCallback' ),
1671 $str
1673 } else {
1674 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1679 function isMultibyte( $str ) {
1680 return (bool)preg_match( '/[\x80-\xff]/', $str );
1683 function ucwords( $str ) {
1684 if ( $this->isMultibyte( $str ) ) {
1685 $str = $this->lc( $str );
1687 // regexp to find first letter in each word (i.e. after each space)
1688 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1690 // function to use to capitalize a single char
1691 if ( function_exists( 'mb_strtoupper' ) ) {
1692 return preg_replace_callback(
1693 $replaceRegexp,
1694 array( $this, 'ucwordsCallbackMB' ),
1695 $str
1697 } else {
1698 return preg_replace_callback(
1699 $replaceRegexp,
1700 array( $this, 'ucwordsCallbackWiki' ),
1701 $str
1704 } else {
1705 return ucwords( strtolower( $str ) );
1709 # capitalize words at word breaks
1710 function ucwordbreaks( $str ) {
1711 if ( $this->isMultibyte( $str ) ) {
1712 $str = $this->lc( $str );
1714 // since \b doesn't work for UTF-8, we explicitely define word break chars
1715 $breaks = "[ \-\(\)\}\{\.,\?!]";
1717 // find first letter after word break
1718 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1720 if ( function_exists( 'mb_strtoupper' ) ) {
1721 return preg_replace_callback(
1722 $replaceRegexp,
1723 array( $this, 'ucwordbreaksCallbackMB' ),
1724 $str
1726 } else {
1727 return preg_replace_callback(
1728 $replaceRegexp,
1729 array( $this, 'ucwordsCallbackWiki' ),
1730 $str
1733 } else {
1734 return preg_replace_callback(
1735 '/\b([\w\x80-\xff]+)\b/',
1736 array( $this, 'ucwordbreaksCallbackAscii' ),
1737 $str
1743 * Return a case-folded representation of $s
1745 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1746 * and $s2 are the same except for the case of their characters. It is not
1747 * necessary for the value returned to make sense when displayed.
1749 * Do *not* perform any other normalisation in this function. If a caller
1750 * uses this function when it should be using a more general normalisation
1751 * function, then fix the caller.
1753 function caseFold( $s ) {
1754 return $this->uc( $s );
1757 function checkTitleEncoding( $s ) {
1758 if ( is_array( $s ) ) {
1759 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1761 # Check for non-UTF-8 URLs
1762 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1763 if ( !$ishigh ) {
1764 return $s;
1767 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1768 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1769 if ( $isutf8 ) {
1770 return $s;
1773 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1776 function fallback8bitEncoding() {
1777 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
1781 * Most writing systems use whitespace to break up words.
1782 * Some languages such as Chinese don't conventionally do this,
1783 * which requires special handling when breaking up words for
1784 * searching etc.
1786 function hasWordBreaks() {
1787 return true;
1791 * Some languages such as Chinese require word segmentation,
1792 * Specify such segmentation when overridden in derived class.
1794 * @param $string String
1795 * @return String
1797 function segmentByWord( $string ) {
1798 return $string;
1802 * Some languages have special punctuation need to be normalized.
1803 * Make such changes here.
1805 * @param $string String
1806 * @return String
1808 function normalizeForSearch( $string ) {
1809 return self::convertDoubleWidth( $string );
1813 * convert double-width roman characters to single-width.
1814 * range: ff00-ff5f ~= 0020-007f
1816 protected static function convertDoubleWidth( $string ) {
1817 static $full = null;
1818 static $half = null;
1820 if ( $full === null ) {
1821 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1822 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1823 $full = str_split( $fullWidth, 3 );
1824 $half = str_split( $halfWidth );
1827 $string = str_replace( $full, $half, $string );
1828 return $string;
1831 protected static function insertSpace( $string, $pattern ) {
1832 $string = preg_replace( $pattern, " $1 ", $string );
1833 $string = preg_replace( '/ +/', ' ', $string );
1834 return $string;
1837 function convertForSearchResult( $termsArray ) {
1838 # some languages, e.g. Chinese, need to do a conversion
1839 # in order for search results to be displayed correctly
1840 return $termsArray;
1844 * Get the first character of a string.
1846 * @param $s string
1847 * @return string
1849 function firstChar( $s ) {
1850 $matches = array();
1851 preg_match(
1852 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1853 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1855 $matches
1858 if ( isset( $matches[1] ) ) {
1859 if ( strlen( $matches[1] ) != 3 ) {
1860 return $matches[1];
1863 // Break down Hangul syllables to grab the first jamo
1864 $code = utf8ToCodepoint( $matches[1] );
1865 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
1866 return $matches[1];
1867 } elseif ( $code < 0xb098 ) {
1868 return "\xe3\x84\xb1";
1869 } elseif ( $code < 0xb2e4 ) {
1870 return "\xe3\x84\xb4";
1871 } elseif ( $code < 0xb77c ) {
1872 return "\xe3\x84\xb7";
1873 } elseif ( $code < 0xb9c8 ) {
1874 return "\xe3\x84\xb9";
1875 } elseif ( $code < 0xbc14 ) {
1876 return "\xe3\x85\x81";
1877 } elseif ( $code < 0xc0ac ) {
1878 return "\xe3\x85\x82";
1879 } elseif ( $code < 0xc544 ) {
1880 return "\xe3\x85\x85";
1881 } elseif ( $code < 0xc790 ) {
1882 return "\xe3\x85\x87";
1883 } elseif ( $code < 0xcc28 ) {
1884 return "\xe3\x85\x88";
1885 } elseif ( $code < 0xce74 ) {
1886 return "\xe3\x85\x8a";
1887 } elseif ( $code < 0xd0c0 ) {
1888 return "\xe3\x85\x8b";
1889 } elseif ( $code < 0xd30c ) {
1890 return "\xe3\x85\x8c";
1891 } elseif ( $code < 0xd558 ) {
1892 return "\xe3\x85\x8d";
1893 } else {
1894 return "\xe3\x85\x8e";
1896 } else {
1897 return '';
1901 function initEncoding() {
1902 # Some languages may have an alternate char encoding option
1903 # (Esperanto X-coding, Japanese furigana conversion, etc)
1904 # If this language is used as the primary content language,
1905 # an override to the defaults can be set here on startup.
1908 function recodeForEdit( $s ) {
1909 # For some languages we'll want to explicitly specify
1910 # which characters make it into the edit box raw
1911 # or are converted in some way or another.
1912 # Note that if wgOutputEncoding is different from
1913 # wgInputEncoding, this text will be further converted
1914 # to wgOutputEncoding.
1915 global $wgEditEncoding;
1916 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
1917 return $s;
1918 } else {
1919 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1923 function recodeInput( $s ) {
1924 # Take the previous into account.
1925 global $wgEditEncoding;
1926 if ( $wgEditEncoding != '' ) {
1927 $enc = $wgEditEncoding;
1928 } else {
1929 $enc = 'UTF-8';
1931 if ( $enc == 'UTF-8' ) {
1932 return $s;
1933 } else {
1934 return $this->iconv( $enc, 'UTF-8', $s );
1939 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1940 * also cleans up certain backwards-compatible sequences, converting them
1941 * to the modern Unicode equivalent.
1943 * This is language-specific for performance reasons only.
1945 function normalize( $s ) {
1946 global $wgAllUnicodeFixes;
1947 $s = UtfNormal::cleanUp( $s );
1948 if ( $wgAllUnicodeFixes ) {
1949 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1950 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1953 return $s;
1957 * Transform a string using serialized data stored in the given file (which
1958 * must be in the serialized subdirectory of $IP). The file contains pairs
1959 * mapping source characters to destination characters.
1961 * The data is cached in process memory. This will go faster if you have the
1962 * FastStringSearch extension.
1964 function transformUsingPairFile( $file, $string ) {
1965 if ( !isset( $this->transformData[$file] ) ) {
1966 $data = wfGetPrecompiledData( $file );
1967 if ( $data === false ) {
1968 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
1970 $this->transformData[$file] = new ReplacementArray( $data );
1972 return $this->transformData[$file]->replace( $string );
1976 * For right-to-left language support
1978 * @return bool
1980 function isRTL() {
1981 return self::$dataCache->getItem( $this->mCode, 'rtl' );
1985 * Return the correct HTML 'dir' attribute value for this language.
1986 * @return String
1988 function getDir() {
1989 return $this->isRTL() ? 'rtl' : 'ltr';
1993 * Return 'left' or 'right' as appropriate alignment for line-start
1994 * for this language's text direction.
1996 * Should be equivalent to CSS3 'start' text-align value....
1998 * @return String
2000 function alignStart() {
2001 return $this->isRTL() ? 'right' : 'left';
2005 * Return 'right' or 'left' as appropriate alignment for line-end
2006 * for this language's text direction.
2008 * Should be equivalent to CSS3 'end' text-align value....
2010 * @return String
2012 function alignEnd() {
2013 return $this->isRTL() ? 'left' : 'right';
2017 * A hidden direction mark (LRM or RLM), depending on the language direction
2019 * @return string
2021 function getDirMark() {
2022 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
2025 function capitalizeAllNouns() {
2026 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2030 * An arrow, depending on the language direction
2032 * @return string
2034 function getArrow() {
2035 return $this->isRTL() ? '←' : '→';
2039 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2041 * @return bool
2043 function linkPrefixExtension() {
2044 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2047 function getMagicWords() {
2048 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2051 # Fill a MagicWord object with data from here
2052 function getMagic( $mw ) {
2053 if ( !$this->mMagicHookDone ) {
2054 $this->mMagicHookDone = true;
2055 wfProfileIn( 'LanguageGetMagic' );
2056 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2057 wfProfileOut( 'LanguageGetMagic' );
2059 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2060 $rawEntry = $this->mMagicExtensions[$mw->mId];
2061 } else {
2062 $magicWords = $this->getMagicWords();
2063 if ( isset( $magicWords[$mw->mId] ) ) {
2064 $rawEntry = $magicWords[$mw->mId];
2065 } else {
2066 $rawEntry = false;
2070 if ( !is_array( $rawEntry ) ) {
2071 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2072 } else {
2073 $mw->mCaseSensitive = $rawEntry[0];
2074 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2079 * Add magic words to the extension array
2081 function addMagicWordsByLang( $newWords ) {
2082 $code = $this->getCode();
2083 $fallbackChain = array();
2084 while ( $code && !in_array( $code, $fallbackChain ) ) {
2085 $fallbackChain[] = $code;
2086 $code = self::getFallbackFor( $code );
2088 if ( !in_array( 'en', $fallbackChain ) ) {
2089 $fallbackChain[] = 'en';
2091 $fallbackChain = array_reverse( $fallbackChain );
2092 foreach ( $fallbackChain as $code ) {
2093 if ( isset( $newWords[$code] ) ) {
2094 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2100 * Get special page names, as an associative array
2101 * case folded alias => real name
2103 function getSpecialPageAliases() {
2104 // Cache aliases because it may be slow to load them
2105 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2106 // Initialise array
2107 $this->mExtendedSpecialPageAliases =
2108 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2109 wfRunHooks( 'LanguageGetSpecialPageAliases',
2110 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2113 return $this->mExtendedSpecialPageAliases;
2117 * Italic is unsuitable for some languages
2119 * @param $text String: the text to be emphasized.
2120 * @return string
2122 function emphasize( $text ) {
2123 return "<em>$text</em>";
2127 * Normally we output all numbers in plain en_US style, that is
2128 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2129 * point twohundredthirtyfive. However this is not sutable for all
2130 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2131 * Icelandic just want to use commas instead of dots, and dots instead
2132 * of commas like "293.291,235".
2134 * An example of this function being called:
2135 * <code>
2136 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2137 * </code>
2139 * See LanguageGu.php for the Gujarati implementation and
2140 * $separatorTransformTable on MessageIs.php for
2141 * the , => . and . => , implementation.
2143 * @todo check if it's viable to use localeconv() for the decimal
2144 * separator thing.
2145 * @param $number Mixed: the string to be formatted, should be an integer
2146 * or a floating point number.
2147 * @param $nocommafy Bool: set to true for special numbers like dates
2148 * @return string
2150 function formatNum( $number, $nocommafy = false ) {
2151 global $wgTranslateNumerals;
2152 if ( !$nocommafy ) {
2153 $number = $this->commafy( $number );
2154 $s = $this->separatorTransformTable();
2155 if ( $s ) {
2156 $number = strtr( $number, $s );
2160 if ( $wgTranslateNumerals ) {
2161 $s = $this->digitTransformTable();
2162 if ( $s ) {
2163 $number = strtr( $number, $s );
2167 return $number;
2170 function parseFormattedNumber( $number ) {
2171 $s = $this->digitTransformTable();
2172 if ( $s ) {
2173 $number = strtr( $number, array_flip( $s ) );
2176 $s = $this->separatorTransformTable();
2177 if ( $s ) {
2178 $number = strtr( $number, array_flip( $s ) );
2181 $number = strtr( $number, array( ',' => '' ) );
2182 return $number;
2186 * Adds commas to a given number
2188 * @param $_ mixed
2189 * @return string
2191 function commafy( $_ ) {
2192 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2195 function digitTransformTable() {
2196 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2199 function separatorTransformTable() {
2200 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2204 * Take a list of strings and build a locale-friendly comma-separated
2205 * list, using the local comma-separator message.
2206 * The last two strings are chained with an "and".
2208 * @param $l Array
2209 * @return string
2211 function listToText( $l ) {
2212 $s = '';
2213 $m = count( $l ) - 1;
2214 if ( $m == 1 ) {
2215 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2216 } else {
2217 for ( $i = $m; $i >= 0; $i-- ) {
2218 if ( $i == $m ) {
2219 $s = $l[$i];
2220 } else if ( $i == $m - 1 ) {
2221 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2222 } else {
2223 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2226 return $s;
2231 * Take a list of strings and build a locale-friendly comma-separated
2232 * list, using the local comma-separator message.
2233 * @param $list array of strings to put in a comma list
2234 * @return string
2236 function commaList( $list ) {
2237 return implode(
2238 $list,
2239 wfMsgExt(
2240 'comma-separator',
2241 array( 'parsemag', 'escapenoentities', 'language' => $this )
2247 * Take a list of strings and build a locale-friendly semicolon-separated
2248 * list, using the local semicolon-separator message.
2249 * @param $list array of strings to put in a semicolon list
2250 * @return string
2252 function semicolonList( $list ) {
2253 return implode(
2254 $list,
2255 wfMsgExt(
2256 'semicolon-separator',
2257 array( 'parsemag', 'escapenoentities', 'language' => $this )
2263 * Same as commaList, but separate it with the pipe instead.
2264 * @param $list array of strings to put in a pipe list
2265 * @return string
2267 function pipeList( $list ) {
2268 return implode(
2269 $list,
2270 wfMsgExt(
2271 'pipe-separator',
2272 array( 'escapenoentities', 'language' => $this )
2278 * Truncate a string to a specified length in bytes, appending an optional
2279 * string (e.g. for ellipses)
2281 * The database offers limited byte lengths for some columns in the database;
2282 * multi-byte character sets mean we need to ensure that only whole characters
2283 * are included, otherwise broken characters can be passed to the user
2285 * If $length is negative, the string will be truncated from the beginning
2287 * @param $string String to truncate
2288 * @param $length Int: maximum length (excluding ellipses)
2289 * @param $ellipsis String to append to the truncated text
2290 * @return string
2292 function truncate( $string, $length, $ellipsis = '...' ) {
2293 # Use the localized ellipsis character
2294 if ( $ellipsis == '...' ) {
2295 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2297 # Check if there is no need to truncate
2298 if ( $length == 0 ) {
2299 return $ellipsis;
2300 } elseif ( strlen( $string ) <= abs( $length ) ) {
2301 return $string;
2303 $stringOriginal = $string;
2304 if ( $length > 0 ) {
2305 $string = substr( $string, 0, $length ); // xyz...
2306 $string = $this->removeBadCharLast( $string );
2307 $string = $string . $ellipsis;
2308 } else {
2309 $string = substr( $string, $length ); // ...xyz
2310 $string = $this->removeBadCharFirst( $string );
2311 $string = $ellipsis . $string;
2313 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2314 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2315 return $string;
2316 } else {
2317 return $stringOriginal;
2322 * Remove bytes that represent an incomplete Unicode character
2323 * at the end of string (e.g. bytes of the char are missing)
2325 * @param $string String
2326 * @return string
2328 protected function removeBadCharLast( $string ) {
2329 $char = ord( $string[strlen( $string ) - 1] );
2330 $m = array();
2331 if ( $char >= 0xc0 ) {
2332 # We got the first byte only of a multibyte char; remove it.
2333 $string = substr( $string, 0, -1 );
2334 } elseif ( $char >= 0x80 &&
2335 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2336 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2338 # We chopped in the middle of a character; remove it
2339 $string = $m[1];
2341 return $string;
2345 * Remove bytes that represent an incomplete Unicode character
2346 * at the start of string (e.g. bytes of the char are missing)
2348 * @param $string String
2349 * @return string
2351 protected function removeBadCharFirst( $string ) {
2352 $char = ord( $string[0] );
2353 if ( $char >= 0x80 && $char < 0xc0 ) {
2354 # We chopped in the middle of a character; remove the whole thing
2355 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2357 return $string;
2361 * Truncate a string of valid HTML to a specified length in bytes,
2362 * appending an optional string (e.g. for ellipses), and return valid HTML
2364 * This is only intended for styled/linked text, such as HTML with
2365 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2367 * Note: tries to fix broken HTML with MWTidy
2369 * @param string $text HTML string to truncate
2370 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2371 * @param string $ellipsis String to append to the truncated text
2372 * @returns string
2374 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2375 # Use the localized ellipsis character
2376 if ( $ellipsis == '...' ) {
2377 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2379 # Check if there is no need to truncate
2380 if ( $length <= 0 ) {
2381 return $ellipsis; // no text shown, nothing to format
2382 } elseif ( strlen( $text ) <= $length ) {
2383 return $text; // string short enough even *with* HTML
2385 $text = MWTidy::tidy( $text ); // fix tags
2386 $displayLen = 0; // innerHTML legth so far
2387 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2388 $tagType = 0; // 0-open, 1-close
2389 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2390 $entityState = 0; // 0-not entity, 1-entity
2391 $tag = $ret = '';
2392 $openTags = array(); // open tag stack
2393 $textLen = strlen( $text );
2394 for ( $pos = 0; $pos < $textLen; ++$pos ) {
2395 $ch = $text[$pos];
2396 $lastCh = $pos ? $text[$pos - 1] : '';
2397 $ret .= $ch; // add to result string
2398 if ( $ch == '<' ) {
2399 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2400 $entityState = 0; // for bad HTML
2401 $bracketState = 1; // tag started (checking for backslash)
2402 } elseif ( $ch == '>' ) {
2403 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2404 $entityState = 0; // for bad HTML
2405 $bracketState = 0; // out of brackets
2406 } elseif ( $bracketState == 1 ) {
2407 if ( $ch == '/' ) {
2408 $tagType = 1; // close tag (e.g. "</span>")
2409 } else {
2410 $tagType = 0; // open tag (e.g. "<span>")
2411 $tag .= $ch;
2413 $bracketState = 2; // building tag name
2414 } elseif ( $bracketState == 2 ) {
2415 if ( $ch != ' ' ) {
2416 $tag .= $ch;
2417 } else {
2418 // Name found (e.g. "<a href=..."), add on tag attributes...
2419 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2421 } elseif ( $bracketState == 0 ) {
2422 if ( $entityState ) {
2423 if ( $ch == ';' ) {
2424 $entityState = 0;
2425 $displayLen++; // entity is one displayed char
2427 } else {
2428 if ( $ch == '&' ) {
2429 $entityState = 1; // entity found, (e.g. "&#160;")
2430 } else {
2431 $displayLen++; // this char is displayed
2432 // Add on the other display text after this...
2433 $skipped = $this->truncate_skip(
2434 $ret, $text, "<>&", $pos + 1, $length - $displayLen );
2435 $displayLen += $skipped;
2436 $pos += $skipped;
2440 # Consider truncation once the display length has reached the maximim.
2441 # Double-check that we're not in the middle of a bracket/entity...
2442 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2443 if ( !$testingEllipsis ) {
2444 $testingEllipsis = true;
2445 # Save where we are; we will truncate here unless
2446 # the ellipsis actually makes the string longer.
2447 $pOpenTags = $openTags; // save state
2448 $pRet = $ret; // save state
2449 } elseif ( $displayLen > ( $length + strlen( $ellipsis ) ) ) {
2450 # Ellipsis won't make string longer/equal, the truncation point was OK.
2451 $openTags = $pOpenTags; // reload state
2452 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2453 $ret .= $ellipsis; // add ellipsis
2454 break;
2458 if ( $displayLen == 0 ) {
2459 return ''; // no text shown, nothing to format
2461 // Close the last tag if left unclosed by bad HTML
2462 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2463 while ( count( $openTags ) > 0 ) {
2464 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2466 return $ret;
2469 // truncateHtml() helper function
2470 // like strcspn() but adds the skipped chars to $ret
2471 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2472 $skipCount = 0;
2473 if ( $start < strlen( $text ) ) {
2474 $skipCount = strcspn( $text, $search, $start, $len );
2475 $ret .= substr( $text, $start, $skipCount );
2477 return $skipCount;
2481 * truncateHtml() helper function
2482 * (a) push or pop $tag from $openTags as needed
2483 * (b) clear $tag value
2484 * @param String &$tag Current HTML tag name we are looking at
2485 * @param int $tagType (0-open tag, 1-close tag)
2486 * @param char $lastCh Character before the '>' that ended this tag
2487 * @param array &$openTags Open tag stack (not accounting for $tag)
2489 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2490 $tag = ltrim( $tag );
2491 if ( $tag != '' ) {
2492 if ( $tagType == 0 && $lastCh != '/' ) {
2493 $openTags[] = $tag; // tag opened (didn't close itself)
2494 } else if ( $tagType == 1 ) {
2495 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2496 array_pop( $openTags ); // tag closed
2499 $tag = '';
2504 * Grammatical transformations, needed for inflected languages
2505 * Invoked by putting {{grammar:case|word}} in a message
2507 * @param $word string
2508 * @param $case string
2509 * @return string
2511 function convertGrammar( $word, $case ) {
2512 global $wgGrammarForms;
2513 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2514 return $wgGrammarForms[$this->getCode()][$case][$word];
2516 return $word;
2520 * Provides an alternative text depending on specified gender.
2521 * Usage {{gender:username|masculine|feminine|neutral}}.
2522 * username is optional, in which case the gender of current user is used,
2523 * but only in (some) interface messages; otherwise default gender is used.
2524 * If second or third parameter are not specified, masculine is used.
2525 * These details may be overriden per language.
2527 function gender( $gender, $forms ) {
2528 if ( !count( $forms ) ) {
2529 return '';
2531 $forms = $this->preConvertPlural( $forms, 2 );
2532 if ( $gender === 'male' ) {
2533 return $forms[0];
2535 if ( $gender === 'female' ) {
2536 return $forms[1];
2538 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2542 * Plural form transformations, needed for some languages.
2543 * For example, there are 3 form of plural in Russian and Polish,
2544 * depending on "count mod 10". See [[w:Plural]]
2545 * For English it is pretty simple.
2547 * Invoked by putting {{plural:count|wordform1|wordform2}}
2548 * or {{plural:count|wordform1|wordform2|wordform3}}
2550 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2552 * @param $count Integer: non-localized number
2553 * @param $forms Array: different plural forms
2554 * @return string Correct form of plural for $count in this language
2556 function convertPlural( $count, $forms ) {
2557 if ( !count( $forms ) ) {
2558 return '';
2560 $forms = $this->preConvertPlural( $forms, 2 );
2562 return ( $count == 1 ) ? $forms[0] : $forms[1];
2566 * Checks that convertPlural was given an array and pads it to requested
2567 * amound of forms by copying the last one.
2569 * @param $count Integer: How many forms should there be at least
2570 * @param $forms Array of forms given to convertPlural
2571 * @return array Padded array of forms or an exception if not an array
2573 protected function preConvertPlural( /* Array */ $forms, $count ) {
2574 while ( count( $forms ) < $count ) {
2575 $forms[] = $forms[count( $forms ) - 1];
2577 return $forms;
2581 * For translating of expiry times
2582 * @param $str String: the validated block time in English
2583 * @return Somehow translated block time
2584 * @see LanguageFi.php for example implementation
2586 function translateBlockExpiry( $str ) {
2587 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2589 if ( $scBlockExpiryOptions == '-' ) {
2590 return $str;
2593 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2594 if ( strpos( $option, ':' ) === false ) {
2595 continue;
2597 list( $show, $value ) = explode( ':', $option );
2598 if ( strcmp( $str, $value ) == 0 ) {
2599 return htmlspecialchars( trim( $show ) );
2603 return $str;
2607 * languages like Chinese need to be segmented in order for the diff
2608 * to be of any use
2610 * @param $text String
2611 * @return String
2613 function segmentForDiff( $text ) {
2614 return $text;
2618 * and unsegment to show the result
2620 * @param $text String
2621 * @return String
2623 function unsegmentForDiff( $text ) {
2624 return $text;
2627 # convert text to all supported variants
2628 function autoConvertToAllVariants( $text ) {
2629 return $this->mConverter->autoConvertToAllVariants( $text );
2632 # convert text to different variants of a language.
2633 function convert( $text ) {
2634 return $this->mConverter->convert( $text );
2637 # Convert a Title object to a string in the preferred variant
2638 function convertTitle( $title ) {
2639 return $this->mConverter->convertTitle( $title );
2642 # Check if this is a language with variants
2643 function hasVariants() {
2644 return sizeof( $this->getVariants() ) > 1;
2647 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2648 function armourMath( $text ) {
2649 return $this->mConverter->armourMath( $text );
2653 * Perform output conversion on a string, and encode for safe HTML output.
2654 * @param $text String text to be converted
2655 * @param $isTitle Bool whether this conversion is for the article title
2656 * @return string
2657 * @todo this should get integrated somewhere sane
2659 function convertHtml( $text, $isTitle = false ) {
2660 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2663 function convertCategoryKey( $key ) {
2664 return $this->mConverter->convertCategoryKey( $key );
2668 * Get the list of variants supported by this langauge
2669 * see sample implementation in LanguageZh.php
2671 * @return array an array of language codes
2673 function getVariants() {
2674 return $this->mConverter->getVariants();
2677 function getPreferredVariant() {
2678 return $this->mConverter->getPreferredVariant();
2681 function getDefaultVariant() {
2682 return $this->mConverter->getDefaultVariant();
2685 function getURLVariant() {
2686 return $this->mConverter->getURLVariant();
2690 * If a language supports multiple variants, it is
2691 * possible that non-existing link in one variant
2692 * actually exists in another variant. this function
2693 * tries to find it. See e.g. LanguageZh.php
2695 * @param $link String: the name of the link
2696 * @param $nt Mixed: the title object of the link
2697 * @param $ignoreOtherCond Boolean: to disable other conditions when
2698 * we need to transclude a template or update a category's link
2699 * @return null the input parameters may be modified upon return
2701 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2702 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
2706 * If a language supports multiple variants, converts text
2707 * into an array of all possible variants of the text:
2708 * 'variant' => text in that variant
2710 * @deprecated Use autoConvertToAllVariants()
2712 function convertLinkToAllVariants( $text ) {
2713 return $this->mConverter->convertLinkToAllVariants( $text );
2717 * returns language specific options used by User::getPageRenderHash()
2718 * for example, the preferred language variant
2720 * @return string
2722 function getExtraHashOptions() {
2723 return $this->mConverter->getExtraHashOptions();
2727 * For languages that support multiple variants, the title of an
2728 * article may be displayed differently in different variants. this
2729 * function returns the apporiate title defined in the body of the article.
2731 * @return string
2733 function getParsedTitle() {
2734 return $this->mConverter->getParsedTitle();
2738 * Enclose a string with the "no conversion" tag. This is used by
2739 * various functions in the Parser
2741 * @param $text String: text to be tagged for no conversion
2742 * @param $noParse
2743 * @return string the tagged text
2745 function markNoConversion( $text, $noParse = false ) {
2746 return $this->mConverter->markNoConversion( $text, $noParse );
2750 * A regular expression to match legal word-trailing characters
2751 * which should be merged onto a link of the form [[foo]]bar.
2753 * @return string
2755 function linkTrail() {
2756 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
2759 function getLangObj() {
2760 return $this;
2764 * Get the RFC 3066 code for this language object
2766 function getCode() {
2767 return $this->mCode;
2771 * Get langcode for message
2772 * Some language, like Chinese (zh, without any suffix), has multiple
2773 * interface languages, we could choose a better one for user.
2774 * Inherit class can override this function if necessary.
2776 * @return string
2778 function getCodeForMessage() {
2779 return $this->getPreferredVariant();
2782 function setCode( $code ) {
2783 $this->mCode = $code;
2787 * Get the name of a file for a certain language code
2788 * @param $prefix string Prepend this to the filename
2789 * @param $code string Language code
2790 * @param $suffix string Append this to the filename
2791 * @return string $prefix . $mangledCode . $suffix
2793 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2794 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2798 * Get the language code from a file name. Inverse of getFileName()
2799 * @param $filename string $prefix . $languageCode . $suffix
2800 * @param $prefix string Prefix before the language code
2801 * @param $suffix string Suffix after the language code
2802 * @return Language code, or false if $prefix or $suffix isn't found
2804 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2805 $m = null;
2806 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2807 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2808 if ( !count( $m ) ) {
2809 return false;
2811 return str_replace( '_', '-', strtolower( $m[1] ) );
2814 static function getMessagesFileName( $code ) {
2815 global $IP;
2816 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2819 static function getClassFileName( $code ) {
2820 global $IP;
2821 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2825 * Get the fallback for a given language
2827 static function getFallbackFor( $code ) {
2828 if ( $code === 'en' ) {
2829 // Shortcut
2830 return false;
2831 } else {
2832 return self::getLocalisationCache()->getItem( $code, 'fallback' );
2837 * Get all messages for a given language
2838 * WARNING: this may take a long time
2840 static function getMessagesFor( $code ) {
2841 return self::getLocalisationCache()->getItem( $code, 'messages' );
2845 * Get a message for a given language
2847 static function getMessageFor( $key, $code ) {
2848 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2851 function fixVariableInNamespace( $talk ) {
2852 if ( strpos( $talk, '$1' ) === false ) {
2853 return $talk;
2856 global $wgMetaNamespace;
2857 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2859 # Allow grammar transformations
2860 # Allowing full message-style parsing would make simple requests
2861 # such as action=raw much more expensive than they need to be.
2862 # This will hopefully cover most cases.
2863 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2864 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2865 return str_replace( ' ', '_', $talk );
2868 function replaceGrammarInNamespace( $m ) {
2869 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2872 static function getCaseMaps() {
2873 static $wikiUpperChars, $wikiLowerChars;
2874 if ( isset( $wikiUpperChars ) ) {
2875 return array( $wikiUpperChars, $wikiLowerChars );
2878 wfProfileIn( __METHOD__ );
2879 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2880 if ( $arr === false ) {
2881 throw new MWException(
2882 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2884 extract( $arr );
2885 wfProfileOut( __METHOD__ );
2886 return array( $wikiUpperChars, $wikiLowerChars );
2889 function formatTimePeriod( $seconds ) {
2890 if ( round( $seconds * 10 ) < 100 ) {
2891 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2892 } elseif ( round( $seconds ) < 60 ) {
2893 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2894 } elseif ( round( $seconds ) < 3600 ) {
2895 $minutes = floor( $seconds / 60 );
2896 $secondsPart = round( fmod( $seconds, 60 ) );
2897 if ( $secondsPart == 60 ) {
2898 $secondsPart = 0;
2899 $minutes++;
2901 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2902 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2903 } else {
2904 $hours = floor( $seconds / 3600 );
2905 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2906 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2907 if ( $secondsPart == 60 ) {
2908 $secondsPart = 0;
2909 $minutes++;
2911 if ( $minutes == 60 ) {
2912 $minutes = 0;
2913 $hours++;
2915 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2916 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2917 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2921 function formatBitrate( $bps ) {
2922 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2923 if ( $bps <= 0 ) {
2924 return $this->formatNum( $bps ) . $units[0];
2926 $unitIndex = floor( log10( $bps ) / 3 );
2927 $mantissa = $bps / pow( 1000, $unitIndex );
2928 if ( $mantissa < 10 ) {
2929 $mantissa = round( $mantissa, 1 );
2930 } else {
2931 $mantissa = round( $mantissa );
2933 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2937 * Format a size in bytes for output, using an appropriate
2938 * unit (B, KB, MB or GB) according to the magnitude in question
2940 * @param $size Size to format
2941 * @return string Plain text (not HTML)
2943 function formatSize( $size ) {
2944 // For small sizes no decimal places necessary
2945 $round = 0;
2946 if ( $size > 1024 ) {
2947 $size = $size / 1024;
2948 if ( $size > 1024 ) {
2949 $size = $size / 1024;
2950 // For MB and bigger two decimal places are smarter
2951 $round = 2;
2952 if ( $size > 1024 ) {
2953 $size = $size / 1024;
2954 $msg = 'size-gigabytes';
2955 } else {
2956 $msg = 'size-megabytes';
2958 } else {
2959 $msg = 'size-kilobytes';
2961 } else {
2962 $msg = 'size-bytes';
2964 $size = round( $size, $round );
2965 $text = $this->getMessageFromDB( $msg );
2966 return str_replace( '$1', $this->formatNum( $size ), $text );
2970 * Get the conversion rule title, if any.
2972 function getConvRuleTitle() {
2973 return $this->mConverter->getConvRuleTitle();
2977 * Given a string, convert it to a (hopefully short) key that can be used
2978 * for efficient sorting. A binary sort according to the sortkeys
2979 * corresponds to a logical sort of the corresponding strings. Current
2980 * code expects that a null character should sort before all others, but
2981 * has no other particular expectations (and that one can be changed if
2982 * necessary).
2984 * @param string $string UTF-8 string
2985 * @return string Binary sortkey
2987 public function convertToSortkey( $string ) {
2988 # Fake function for now
2989 return strtoupper( $string );
2993 * Given a string, return the logical "first letter" to be used for
2994 * grouping on category pages and so on. This has to be coordinated
2995 * carefully with convertToSortkey(), or else the sorted list might jump
2996 * back and forth between the same "initial letters" or other pathological
2997 * behavior. For instance, if you just return the first character, but "a"
2998 * sorts the same as "A" based on convertToSortkey(), then you might get a
2999 * list like
3001 * == A ==
3002 * * [[Aardvark]]
3004 * == a ==
3005 * * [[antelope]]
3007 * == A ==
3008 * * [[Ape]]
3010 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
3012 * @param string $string UTF-8 string
3013 * @return string UTF-8 string corresponding to the first letter of input
3015 public function firstLetterForLists( $string ) {
3016 if ( $string[0] == "\0" ) {
3017 $string = substr( $string, 1 );
3019 return strtoupper( $this->firstChar( $string ) );