Fix for renamed stuff that broke jquery.textSelection.js: $.os.name -> $.client.platform
[mediawiki.git] / languages / Language.php
blob9631ce2fa74551a75f7addb216ea294469af9f5c
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
135 * @param $code String
136 * @return Language
138 static function factory( $code ) {
139 if ( !isset( self::$mLangObjCache[$code] ) ) {
140 if ( count( self::$mLangObjCache ) > 10 ) {
141 // Don't keep a billion objects around, that's stupid.
142 self::$mLangObjCache = array();
144 self::$mLangObjCache[$code] = self::newFromCode( $code );
146 return self::$mLangObjCache[$code];
150 * Create a language object for a given language code
151 * @param $code String
152 * @return Language
154 protected static function newFromCode( $code ) {
155 global $IP;
156 static $recursionLevel = 0;
158 // Protect against path traversal below
159 if ( !Language::isValidCode( $code ) ) {
160 throw new MWException( "Invalid language code \"$code\"" );
163 if ( $code == 'en' ) {
164 $class = 'Language';
165 } else {
166 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
167 // Preload base classes to work around APC/PHP5 bug
168 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
169 include_once( "$IP/languages/classes/$class.deps.php" );
171 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
172 include_once( "$IP/languages/classes/$class.php" );
176 if ( $recursionLevel > 5 ) {
177 throw new MWException( "Language fallback loop detected when creating class $class\n" );
180 if ( !class_exists( $class ) ) {
181 $fallback = Language::getFallbackFor( $code );
182 ++$recursionLevel;
183 $lang = Language::newFromCode( $fallback );
184 --$recursionLevel;
185 $lang->setCode( $code );
186 } else {
187 $lang = new $class;
189 return $lang;
193 * Returns true if a language code string is of a valid form, whether or
194 * not it exists.
196 public static function isValidCode( $code ) {
197 return strcspn( $code, "/\\\000" ) === strlen( $code );
201 * Get the LocalisationCache instance
203 public static function getLocalisationCache() {
204 if ( is_null( self::$dataCache ) ) {
205 global $wgLocalisationCacheConf;
206 $class = $wgLocalisationCacheConf['class'];
207 self::$dataCache = new $class( $wgLocalisationCacheConf );
209 return self::$dataCache;
212 function __construct() {
213 $this->mConverter = new FakeConverter( $this );
214 // Set the code to the name of the descendant
215 if ( get_class( $this ) == 'Language' ) {
216 $this->mCode = 'en';
217 } else {
218 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
220 self::getLocalisationCache();
224 * Reduce memory usage
226 function __destruct() {
227 foreach ( $this as $name => $value ) {
228 unset( $this->$name );
233 * Hook which will be called if this is the content language.
234 * Descendants can use this to register hook functions or modify globals
236 function initContLang() { }
239 * @deprecated Use User::getDefaultOptions()
240 * @return array
242 function getDefaultUserOptions() {
243 wfDeprecated( __METHOD__ );
244 return User::getDefaultOptions();
247 function getFallbackLanguageCode() {
248 if ( $this->mCode === 'en' ) {
249 return false;
250 } else {
251 return self::$dataCache->getItem( $this->mCode, 'fallback' );
256 * Exports $wgBookstoreListEn
257 * @return array
259 function getBookstoreList() {
260 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
264 * @return array
266 function getNamespaces() {
267 if ( is_null( $this->namespaceNames ) ) {
268 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
270 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
271 $validNamespaces = MWNamespace::getCanonicalNamespaces();
273 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
275 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
276 if ( $wgMetaNamespaceTalk ) {
277 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
278 } else {
279 $talk = $this->namespaceNames[NS_PROJECT_TALK];
280 $this->namespaceNames[NS_PROJECT_TALK] =
281 $this->fixVariableInNamespace( $talk );
284 # Sometimes a language will be localised but not actually exist on this wiki.
285 foreach( $this->namespaceNames as $key => $text ) {
286 if ( !isset( $validNamespaces[$key] ) ) {
287 unset( $this->namespaceNames[$key] );
291 # The above mixing may leave namespaces out of canonical order.
292 # Re-order by namespace ID number...
293 ksort( $this->namespaceNames );
295 return $this->namespaceNames;
299 * A convenience function that returns the same thing as
300 * getNamespaces() except with the array values changed to ' '
301 * where it found '_', useful for producing output to be displayed
302 * e.g. in <select> forms.
304 * @return array
306 function getFormattedNamespaces() {
307 $ns = $this->getNamespaces();
308 foreach ( $ns as $k => $v ) {
309 $ns[$k] = strtr( $v, '_', ' ' );
311 return $ns;
315 * Get a namespace value by key
316 * <code>
317 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
318 * echo $mw_ns; // prints 'MediaWiki'
319 * </code>
321 * @param $index Int: the array key of the namespace to return
322 * @return mixed, string if the namespace value exists, otherwise false
324 function getNsText( $index ) {
325 $ns = $this->getNamespaces();
326 return isset( $ns[$index] ) ? $ns[$index] : false;
330 * A convenience function that returns the same thing as
331 * getNsText() except with '_' changed to ' ', useful for
332 * producing output.
334 * @return array
336 function getFormattedNsText( $index ) {
337 $ns = $this->getNsText( $index );
338 return strtr( $ns, '_', ' ' );
342 * Get a namespace key by value, case insensitive.
343 * Only matches namespace names for the current language, not the
344 * canonical ones defined in Namespace.php.
346 * @param $text String
347 * @return mixed An integer if $text is a valid value otherwise false
349 function getLocalNsIndex( $text ) {
350 $lctext = $this->lc( $text );
351 $ids = $this->getNamespaceIds();
352 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
355 function getNamespaceAliases() {
356 if ( is_null( $this->namespaceAliases ) ) {
357 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
358 if ( !$aliases ) {
359 $aliases = array();
360 } else {
361 foreach ( $aliases as $name => $index ) {
362 if ( $index === NS_PROJECT_TALK ) {
363 unset( $aliases[$name] );
364 $name = $this->fixVariableInNamespace( $name );
365 $aliases[$name] = $index;
369 $this->namespaceAliases = $aliases;
371 return $this->namespaceAliases;
374 function getNamespaceIds() {
375 if ( is_null( $this->mNamespaceIds ) ) {
376 global $wgNamespaceAliases;
377 # Put namespace names and aliases into a hashtable.
378 # If this is too slow, then we should arrange it so that it is done
379 # before caching. The catch is that at pre-cache time, the above
380 # class-specific fixup hasn't been done.
381 $this->mNamespaceIds = array();
382 foreach ( $this->getNamespaces() as $index => $name ) {
383 $this->mNamespaceIds[$this->lc( $name )] = $index;
385 foreach ( $this->getNamespaceAliases() as $name => $index ) {
386 $this->mNamespaceIds[$this->lc( $name )] = $index;
388 if ( $wgNamespaceAliases ) {
389 foreach ( $wgNamespaceAliases as $name => $index ) {
390 $this->mNamespaceIds[$this->lc( $name )] = $index;
394 return $this->mNamespaceIds;
399 * Get a namespace key by value, case insensitive. Canonical namespace
400 * names override custom ones defined for the current language.
402 * @param $text String
403 * @return mixed An integer if $text is a valid value otherwise false
405 function getNsIndex( $text ) {
406 $lctext = $this->lc( $text );
407 if ( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) {
408 return $ns;
410 $ids = $this->getNamespaceIds();
411 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
415 * short names for language variants used for language conversion links.
417 * @param $code String
418 * @return string
420 function getVariantname( $code ) {
421 return $this->getMessageFromDB( "variantname-$code" );
424 function specialPage( $name ) {
425 $aliases = $this->getSpecialPageAliases();
426 if ( isset( $aliases[$name][0] ) ) {
427 $name = $aliases[$name][0];
429 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
432 function getQuickbarSettings() {
433 return array(
434 $this->getMessage( 'qbsettings-none' ),
435 $this->getMessage( 'qbsettings-fixedleft' ),
436 $this->getMessage( 'qbsettings-fixedright' ),
437 $this->getMessage( 'qbsettings-floatingleft' ),
438 $this->getMessage( 'qbsettings-floatingright' )
442 function getMathNames() {
443 return self::$dataCache->getItem( $this->mCode, 'mathNames' );
446 function getDatePreferences() {
447 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
450 function getDateFormats() {
451 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
454 function getDefaultDateFormat() {
455 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
456 if ( $df === 'dmy or mdy' ) {
457 global $wgAmericanDates;
458 return $wgAmericanDates ? 'mdy' : 'dmy';
459 } else {
460 return $df;
464 function getDatePreferenceMigrationMap() {
465 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
468 function getImageFile( $image ) {
469 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
472 function getDefaultUserOptionOverrides() {
473 return self::$dataCache->getItem( $this->mCode, 'defaultUserOptionOverrides' );
476 function getExtraUserToggles() {
477 return self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
480 function getUserToggle( $tog ) {
481 return $this->getMessageFromDB( "tog-$tog" );
485 * Get language names, indexed by code.
486 * If $customisedOnly is true, only returns codes with a messages file
488 public static function getLanguageNames( $customisedOnly = false ) {
489 global $wgLanguageNames, $wgExtraLanguageNames;
490 $allNames = $wgExtraLanguageNames + $wgLanguageNames;
491 if ( !$customisedOnly ) {
492 return $allNames;
495 global $IP;
496 $names = array();
497 $dir = opendir( "$IP/languages/messages" );
498 while ( false !== ( $file = readdir( $dir ) ) ) {
499 $code = self::getCodeFromFileName( $file, 'Messages' );
500 if ( $code && isset( $allNames[$code] ) ) {
501 $names[$code] = $allNames[$code];
504 closedir( $dir );
505 return $names;
509 * Get translated language names. This is done on best effort and
510 * by default this is exactly the same as Language::getLanguageNames.
511 * The CLDR extension provides translated names.
512 * @param $code String Language code.
513 * @return Array language code => language name
514 * @since 1.18.0
516 public static function getTranslatedLanguageNames( $code ) {
517 $names = array();
518 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
520 foreach ( self::getLanguageNames() as $code => $name ) {
521 if ( !isset( $names[$code] ) ) $names[$code] = $name;
524 return $names;
528 * Get a message from the MediaWiki namespace.
530 * @param $msg String: message name
531 * @return string
533 function getMessageFromDB( $msg ) {
534 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
537 function getLanguageName( $code ) {
538 $names = self::getLanguageNames();
539 if ( !array_key_exists( $code, $names ) ) {
540 return '';
542 return $names[$code];
545 function getMonthName( $key ) {
546 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
549 function getMonthNameGen( $key ) {
550 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
553 function getMonthAbbreviation( $key ) {
554 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
557 function getWeekdayName( $key ) {
558 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
561 function getWeekdayAbbreviation( $key ) {
562 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
565 function getIranianCalendarMonthName( $key ) {
566 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
569 function getHebrewCalendarMonthName( $key ) {
570 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
573 function getHebrewCalendarMonthNameGen( $key ) {
574 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
577 function getHijriCalendarMonthName( $key ) {
578 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
582 * Used by date() and time() to adjust the time output.
584 * @param $ts Int the time in date('YmdHis') format
585 * @param $tz Mixed: adjust the time by this amount (default false, mean we
586 * get user timecorrection setting)
587 * @return int
589 function userAdjust( $ts, $tz = false ) {
590 global $wgUser, $wgLocalTZoffset;
592 if ( $tz === false ) {
593 $tz = $wgUser->getOption( 'timecorrection' );
596 $data = explode( '|', $tz, 3 );
598 if ( $data[0] == 'ZoneInfo' ) {
599 if ( function_exists( 'timezone_open' ) && @timezone_open( $data[2] ) !== false ) {
600 $date = date_create( $ts, timezone_open( 'UTC' ) );
601 date_timezone_set( $date, timezone_open( $data[2] ) );
602 $date = date_format( $date, 'YmdHis' );
603 return $date;
605 # Unrecognized timezone, default to 'Offset' with the stored offset.
606 $data[0] = 'Offset';
609 $minDiff = 0;
610 if ( $data[0] == 'System' || $tz == '' ) {
611 #  Global offset in minutes.
612 if ( isset( $wgLocalTZoffset ) ) {
613 $minDiff = $wgLocalTZoffset;
615 } else if ( $data[0] == 'Offset' ) {
616 $minDiff = intval( $data[1] );
617 } else {
618 $data = explode( ':', $tz );
619 if ( count( $data ) == 2 ) {
620 $data[0] = intval( $data[0] );
621 $data[1] = intval( $data[1] );
622 $minDiff = abs( $data[0] ) * 60 + $data[1];
623 if ( $data[0] < 0 ) {
624 $minDiff = -$minDiff;
626 } else {
627 $minDiff = intval( $data[0] ) * 60;
631 # No difference ? Return time unchanged
632 if ( 0 == $minDiff ) {
633 return $ts;
636 wfSuppressWarnings(); // E_STRICT system time bitching
637 # Generate an adjusted date; take advantage of the fact that mktime
638 # will normalize out-of-range values so we don't have to split $minDiff
639 # into hours and minutes.
640 $t = mktime( (
641 (int)substr( $ts, 8, 2 ) ), # Hours
642 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
643 (int)substr( $ts, 12, 2 ), # Seconds
644 (int)substr( $ts, 4, 2 ), # Month
645 (int)substr( $ts, 6, 2 ), # Day
646 (int)substr( $ts, 0, 4 ) ); # Year
648 $date = date( 'YmdHis', $t );
649 wfRestoreWarnings();
651 return $date;
655 * This is a workalike of PHP's date() function, but with better
656 * internationalisation, a reduced set of format characters, and a better
657 * escaping format.
659 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
660 * PHP manual for definitions. There are a number of extensions, which
661 * start with "x":
663 * xn Do not translate digits of the next numeric format character
664 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
665 * xr Use roman numerals for the next numeric format character
666 * xh Use hebrew numerals for the next numeric format character
667 * xx Literal x
668 * xg Genitive month name
670 * xij j (day number) in Iranian calendar
671 * xiF F (month name) in Iranian calendar
672 * xin n (month number) in Iranian calendar
673 * xiY Y (full year) in Iranian calendar
675 * xjj j (day number) in Hebrew calendar
676 * xjF F (month name) in Hebrew calendar
677 * xjt t (days in month) in Hebrew calendar
678 * xjx xg (genitive month name) in Hebrew calendar
679 * xjn n (month number) in Hebrew calendar
680 * xjY Y (full year) in Hebrew calendar
682 * xmj j (day number) in Hijri calendar
683 * xmF F (month name) in Hijri calendar
684 * xmn n (month number) in Hijri calendar
685 * xmY Y (full year) in Hijri calendar
687 * xkY Y (full year) in Thai solar calendar. Months and days are
688 * identical to the Gregorian calendar
689 * xoY Y (full year) in Minguo calendar or Juche year.
690 * Months and days are identical to the
691 * Gregorian calendar
692 * xtY Y (full year) in Japanese nengo. Months and days are
693 * identical to the Gregorian calendar
695 * Characters enclosed in double quotes will be considered literal (with
696 * the quotes themselves removed). Unmatched quotes will be considered
697 * literal quotes. Example:
699 * "The month is" F => The month is January
700 * i's" => 20'11"
702 * Backslash escaping is also supported.
704 * Input timestamp is assumed to be pre-normalized to the desired local
705 * time zone, if any.
707 * @param $format String
708 * @param $ts String: 14-character timestamp
709 * YYYYMMDDHHMMSS
710 * 01234567890123
711 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
713 function sprintfDate( $format, $ts ) {
714 $s = '';
715 $raw = false;
716 $roman = false;
717 $hebrewNum = false;
718 $unix = false;
719 $rawToggle = false;
720 $iranian = false;
721 $hebrew = false;
722 $hijri = false;
723 $thai = false;
724 $minguo = false;
725 $tenno = false;
726 for ( $p = 0; $p < strlen( $format ); $p++ ) {
727 $num = false;
728 $code = $format[$p];
729 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
730 $code .= $format[++$p];
733 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
734 $code .= $format[++$p];
737 switch ( $code ) {
738 case 'xx':
739 $s .= 'x';
740 break;
741 case 'xn':
742 $raw = true;
743 break;
744 case 'xN':
745 $rawToggle = !$rawToggle;
746 break;
747 case 'xr':
748 $roman = true;
749 break;
750 case 'xh':
751 $hebrewNum = true;
752 break;
753 case 'xg':
754 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
755 break;
756 case 'xjx':
757 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
758 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
759 break;
760 case 'd':
761 $num = substr( $ts, 6, 2 );
762 break;
763 case 'D':
764 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
765 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
766 break;
767 case 'j':
768 $num = intval( substr( $ts, 6, 2 ) );
769 break;
770 case 'xij':
771 if ( !$iranian ) {
772 $iranian = self::tsToIranian( $ts );
774 $num = $iranian[2];
775 break;
776 case 'xmj':
777 if ( !$hijri ) {
778 $hijri = self::tsToHijri( $ts );
780 $num = $hijri[2];
781 break;
782 case 'xjj':
783 if ( !$hebrew ) {
784 $hebrew = self::tsToHebrew( $ts );
786 $num = $hebrew[2];
787 break;
788 case 'l':
789 if ( !$unix ) {
790 $unix = wfTimestamp( TS_UNIX, $ts );
792 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
793 break;
794 case 'N':
795 if ( !$unix ) {
796 $unix = wfTimestamp( TS_UNIX, $ts );
798 $w = gmdate( 'w', $unix );
799 $num = $w ? $w : 7;
800 break;
801 case 'w':
802 if ( !$unix ) {
803 $unix = wfTimestamp( TS_UNIX, $ts );
805 $num = gmdate( 'w', $unix );
806 break;
807 case 'z':
808 if ( !$unix ) {
809 $unix = wfTimestamp( TS_UNIX, $ts );
811 $num = gmdate( 'z', $unix );
812 break;
813 case 'W':
814 if ( !$unix ) {
815 $unix = wfTimestamp( TS_UNIX, $ts );
817 $num = gmdate( 'W', $unix );
818 break;
819 case 'F':
820 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
821 break;
822 case 'xiF':
823 if ( !$iranian ) {
824 $iranian = self::tsToIranian( $ts );
826 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
827 break;
828 case 'xmF':
829 if ( !$hijri ) {
830 $hijri = self::tsToHijri( $ts );
832 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
833 break;
834 case 'xjF':
835 if ( !$hebrew ) {
836 $hebrew = self::tsToHebrew( $ts );
838 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
839 break;
840 case 'm':
841 $num = substr( $ts, 4, 2 );
842 break;
843 case 'M':
844 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
845 break;
846 case 'n':
847 $num = intval( substr( $ts, 4, 2 ) );
848 break;
849 case 'xin':
850 if ( !$iranian ) {
851 $iranian = self::tsToIranian( $ts );
853 $num = $iranian[1];
854 break;
855 case 'xmn':
856 if ( !$hijri ) {
857 $hijri = self::tsToHijri ( $ts );
859 $num = $hijri[1];
860 break;
861 case 'xjn':
862 if ( !$hebrew ) {
863 $hebrew = self::tsToHebrew( $ts );
865 $num = $hebrew[1];
866 break;
867 case 't':
868 if ( !$unix ) {
869 $unix = wfTimestamp( TS_UNIX, $ts );
871 $num = gmdate( 't', $unix );
872 break;
873 case 'xjt':
874 if ( !$hebrew ) {
875 $hebrew = self::tsToHebrew( $ts );
877 $num = $hebrew[3];
878 break;
879 case 'L':
880 if ( !$unix ) {
881 $unix = wfTimestamp( TS_UNIX, $ts );
883 $num = gmdate( 'L', $unix );
884 break;
885 case 'o':
886 if ( !$unix ) {
887 $unix = wfTimestamp( TS_UNIX, $ts );
889 $num = date( 'o', $unix );
890 break;
891 case 'Y':
892 $num = substr( $ts, 0, 4 );
893 break;
894 case 'xiY':
895 if ( !$iranian ) {
896 $iranian = self::tsToIranian( $ts );
898 $num = $iranian[0];
899 break;
900 case 'xmY':
901 if ( !$hijri ) {
902 $hijri = self::tsToHijri( $ts );
904 $num = $hijri[0];
905 break;
906 case 'xjY':
907 if ( !$hebrew ) {
908 $hebrew = self::tsToHebrew( $ts );
910 $num = $hebrew[0];
911 break;
912 case 'xkY':
913 if ( !$thai ) {
914 $thai = self::tsToYear( $ts, 'thai' );
916 $num = $thai[0];
917 break;
918 case 'xoY':
919 if ( !$minguo ) {
920 $minguo = self::tsToYear( $ts, 'minguo' );
922 $num = $minguo[0];
923 break;
924 case 'xtY':
925 if ( !$tenno ) {
926 $tenno = self::tsToYear( $ts, 'tenno' );
928 $num = $tenno[0];
929 break;
930 case 'y':
931 $num = substr( $ts, 2, 2 );
932 break;
933 case 'a':
934 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
935 break;
936 case 'A':
937 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
938 break;
939 case 'g':
940 $h = substr( $ts, 8, 2 );
941 $num = $h % 12 ? $h % 12 : 12;
942 break;
943 case 'G':
944 $num = intval( substr( $ts, 8, 2 ) );
945 break;
946 case 'h':
947 $h = substr( $ts, 8, 2 );
948 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
949 break;
950 case 'H':
951 $num = substr( $ts, 8, 2 );
952 break;
953 case 'i':
954 $num = substr( $ts, 10, 2 );
955 break;
956 case 's':
957 $num = substr( $ts, 12, 2 );
958 break;
959 case 'c':
960 if ( !$unix ) {
961 $unix = wfTimestamp( TS_UNIX, $ts );
963 $s .= gmdate( 'c', $unix );
964 break;
965 case 'r':
966 if ( !$unix ) {
967 $unix = wfTimestamp( TS_UNIX, $ts );
969 $s .= gmdate( 'r', $unix );
970 break;
971 case 'U':
972 if ( !$unix ) {
973 $unix = wfTimestamp( TS_UNIX, $ts );
975 $num = $unix;
976 break;
977 case '\\':
978 # Backslash escaping
979 if ( $p < strlen( $format ) - 1 ) {
980 $s .= $format[++$p];
981 } else {
982 $s .= '\\';
984 break;
985 case '"':
986 # Quoted literal
987 if ( $p < strlen( $format ) - 1 ) {
988 $endQuote = strpos( $format, '"', $p + 1 );
989 if ( $endQuote === false ) {
990 # No terminating quote, assume literal "
991 $s .= '"';
992 } else {
993 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
994 $p = $endQuote;
996 } else {
997 # Quote at end of string, assume literal "
998 $s .= '"';
1000 break;
1001 default:
1002 $s .= $format[$p];
1004 if ( $num !== false ) {
1005 if ( $rawToggle || $raw ) {
1006 $s .= $num;
1007 $raw = false;
1008 } elseif ( $roman ) {
1009 $s .= self::romanNumeral( $num );
1010 $roman = false;
1011 } elseif ( $hebrewNum ) {
1012 $s .= self::hebrewNumeral( $num );
1013 $hebrewNum = false;
1014 } else {
1015 $s .= $this->formatNum( $num, true );
1019 return $s;
1022 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1023 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1025 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1026 * Gregorian dates to Iranian dates. Originally written in C, it
1027 * is released under the terms of GNU Lesser General Public
1028 * License. Conversion to PHP was performed by Niklas Laxström.
1030 * Link: http://www.farsiweb.info/jalali/jalali.c
1032 private static function tsToIranian( $ts ) {
1033 $gy = substr( $ts, 0, 4 ) -1600;
1034 $gm = substr( $ts, 4, 2 ) -1;
1035 $gd = substr( $ts, 6, 2 ) -1;
1037 # Days passed from the beginning (including leap years)
1038 $gDayNo = 365 * $gy
1039 + floor( ( $gy + 3 ) / 4 )
1040 - floor( ( $gy + 99 ) / 100 )
1041 + floor( ( $gy + 399 ) / 400 );
1044 // Add days of the past months of this year
1045 for ( $i = 0; $i < $gm; $i++ ) {
1046 $gDayNo += self::$GREG_DAYS[$i];
1049 // Leap years
1050 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1051 $gDayNo++;
1054 // Days passed in current month
1055 $gDayNo += $gd;
1057 $jDayNo = $gDayNo - 79;
1059 $jNp = floor( $jDayNo / 12053 );
1060 $jDayNo %= 12053;
1062 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1063 $jDayNo %= 1461;
1065 if ( $jDayNo >= 366 ) {
1066 $jy += floor( ( $jDayNo - 1 ) / 365 );
1067 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1070 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1071 $jDayNo -= self::$IRANIAN_DAYS[$i];
1074 $jm = $i + 1;
1075 $jd = $jDayNo + 1;
1077 return array( $jy, $jm, $jd );
1081 * Converting Gregorian dates to Hijri dates.
1083 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1085 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1087 private static function tsToHijri( $ts ) {
1088 $year = substr( $ts, 0, 4 );
1089 $month = substr( $ts, 4, 2 );
1090 $day = substr( $ts, 6, 2 );
1092 $zyr = $year;
1093 $zd = $day;
1094 $zm = $month;
1095 $zy = $zyr;
1097 if (
1098 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1099 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1102 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1103 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1104 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1105 $zd - 32075;
1106 } else {
1107 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1108 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1111 $zl = $zjd -1948440 + 10632;
1112 $zn = (int)( ( $zl - 1 ) / 10631 );
1113 $zl = $zl - 10631 * $zn + 354;
1114 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1115 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1116 $zm = (int)( ( 24 * $zl ) / 709 );
1117 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1118 $zy = 30 * $zn + $zj - 30;
1120 return array( $zy, $zm, $zd );
1124 * Converting Gregorian dates to Hebrew dates.
1126 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1127 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1128 * to translate the relevant functions into PHP and release them under
1129 * GNU GPL.
1131 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1132 * and Adar II is 14. In a non-leap year, Adar is 6.
1134 private static function tsToHebrew( $ts ) {
1135 # Parse date
1136 $year = substr( $ts, 0, 4 );
1137 $month = substr( $ts, 4, 2 );
1138 $day = substr( $ts, 6, 2 );
1140 # Calculate Hebrew year
1141 $hebrewYear = $year + 3760;
1143 # Month number when September = 1, August = 12
1144 $month += 4;
1145 if ( $month > 12 ) {
1146 # Next year
1147 $month -= 12;
1148 $year++;
1149 $hebrewYear++;
1152 # Calculate day of year from 1 September
1153 $dayOfYear = $day;
1154 for ( $i = 1; $i < $month; $i++ ) {
1155 if ( $i == 6 ) {
1156 # February
1157 $dayOfYear += 28;
1158 # Check if the year is leap
1159 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1160 $dayOfYear++;
1162 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1163 $dayOfYear += 30;
1164 } else {
1165 $dayOfYear += 31;
1169 # Calculate the start of the Hebrew year
1170 $start = self::hebrewYearStart( $hebrewYear );
1172 # Calculate next year's start
1173 if ( $dayOfYear <= $start ) {
1174 # Day is before the start of the year - it is the previous year
1175 # Next year's start
1176 $nextStart = $start;
1177 # Previous year
1178 $year--;
1179 $hebrewYear--;
1180 # Add days since previous year's 1 September
1181 $dayOfYear += 365;
1182 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1183 # Leap year
1184 $dayOfYear++;
1186 # Start of the new (previous) year
1187 $start = self::hebrewYearStart( $hebrewYear );
1188 } else {
1189 # Next year's start
1190 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1193 # Calculate Hebrew day of year
1194 $hebrewDayOfYear = $dayOfYear - $start;
1196 # Difference between year's days
1197 $diff = $nextStart - $start;
1198 # Add 12 (or 13 for leap years) days to ignore the difference between
1199 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1200 # difference is only about the year type
1201 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1202 $diff += 13;
1203 } else {
1204 $diff += 12;
1207 # Check the year pattern, and is leap year
1208 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1209 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1210 # and non-leap years
1211 $yearPattern = $diff % 30;
1212 # Check if leap year
1213 $isLeap = $diff >= 30;
1215 # Calculate day in the month from number of day in the Hebrew year
1216 # Don't check Adar - if the day is not in Adar, we will stop before;
1217 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1218 $hebrewDay = $hebrewDayOfYear;
1219 $hebrewMonth = 1;
1220 $days = 0;
1221 while ( $hebrewMonth <= 12 ) {
1222 # Calculate days in this month
1223 if ( $isLeap && $hebrewMonth == 6 ) {
1224 # Adar in a leap year
1225 if ( $isLeap ) {
1226 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1227 $days = 30;
1228 if ( $hebrewDay <= $days ) {
1229 # Day in Adar I
1230 $hebrewMonth = 13;
1231 } else {
1232 # Subtract the days of Adar I
1233 $hebrewDay -= $days;
1234 # Try Adar II
1235 $days = 29;
1236 if ( $hebrewDay <= $days ) {
1237 # Day in Adar II
1238 $hebrewMonth = 14;
1242 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1243 # Cheshvan in a complete year (otherwise as the rule below)
1244 $days = 30;
1245 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1246 # Kislev in an incomplete year (otherwise as the rule below)
1247 $days = 29;
1248 } else {
1249 # Odd months have 30 days, even have 29
1250 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1252 if ( $hebrewDay <= $days ) {
1253 # In the current month
1254 break;
1255 } else {
1256 # Subtract the days of the current month
1257 $hebrewDay -= $days;
1258 # Try in the next month
1259 $hebrewMonth++;
1263 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1267 * This calculates the Hebrew year start, as days since 1 September.
1268 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1269 * Used for Hebrew date.
1271 private static function hebrewYearStart( $year ) {
1272 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1273 $b = intval( ( $year - 1 ) % 4 );
1274 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1275 if ( $m < 0 ) {
1276 $m--;
1278 $Mar = intval( $m );
1279 if ( $m < 0 ) {
1280 $m++;
1282 $m -= $Mar;
1284 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1285 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1286 $Mar++;
1287 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1288 $Mar += 2;
1289 } else if ( $c == 2 || $c == 4 || $c == 6 ) {
1290 $Mar++;
1293 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1294 return $Mar;
1298 * Algorithm to convert Gregorian dates to Thai solar dates,
1299 * Minguo dates or Minguo dates.
1301 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1302 * http://en.wikipedia.org/wiki/Minguo_calendar
1303 * http://en.wikipedia.org/wiki/Japanese_era_name
1305 * @param $ts String: 14-character timestamp
1306 * @param $cName String: calender name
1307 * @return Array: converted year, month, day
1309 private static function tsToYear( $ts, $cName ) {
1310 $gy = substr( $ts, 0, 4 );
1311 $gm = substr( $ts, 4, 2 );
1312 $gd = substr( $ts, 6, 2 );
1314 if ( !strcmp( $cName, 'thai' ) ) {
1315 # Thai solar dates
1316 # Add 543 years to the Gregorian calendar
1317 # Months and days are identical
1318 $gy_offset = $gy + 543;
1319 } else if ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1320 # Minguo dates
1321 # Deduct 1911 years from the Gregorian calendar
1322 # Months and days are identical
1323 $gy_offset = $gy - 1911;
1324 } else if ( !strcmp( $cName, 'tenno' ) ) {
1325 # Nengō dates up to Meiji period
1326 # Deduct years from the Gregorian calendar
1327 # depending on the nengo periods
1328 # Months and days are identical
1329 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1330 # Meiji period
1331 $gy_gannen = $gy - 1868 + 1;
1332 $gy_offset = $gy_gannen;
1333 if ( $gy_gannen == 1 ) {
1334 $gy_offset = '元';
1336 $gy_offset = '明治' . $gy_offset;
1337 } else if (
1338 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1339 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1340 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1341 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1342 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1345 # Taishō period
1346 $gy_gannen = $gy - 1912 + 1;
1347 $gy_offset = $gy_gannen;
1348 if ( $gy_gannen == 1 ) {
1349 $gy_offset = '元';
1351 $gy_offset = '大正' . $gy_offset;
1352 } else if (
1353 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1354 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1355 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1358 # Shōwa period
1359 $gy_gannen = $gy - 1926 + 1;
1360 $gy_offset = $gy_gannen;
1361 if ( $gy_gannen == 1 ) {
1362 $gy_offset = '元';
1364 $gy_offset = '昭和' . $gy_offset;
1365 } else {
1366 # Heisei period
1367 $gy_gannen = $gy - 1989 + 1;
1368 $gy_offset = $gy_gannen;
1369 if ( $gy_gannen == 1 ) {
1370 $gy_offset = '元';
1372 $gy_offset = '平成' . $gy_offset;
1374 } else {
1375 $gy_offset = $gy;
1378 return array( $gy_offset, $gm, $gd );
1382 * Roman number formatting up to 3000
1384 static function romanNumeral( $num ) {
1385 static $table = array(
1386 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1387 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1388 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1389 array( '', 'M', 'MM', 'MMM' )
1392 $num = intval( $num );
1393 if ( $num > 3000 || $num <= 0 ) {
1394 return $num;
1397 $s = '';
1398 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1399 if ( $num >= $pow10 ) {
1400 $s .= $table[$i][floor( $num / $pow10 )];
1402 $num = $num % $pow10;
1404 return $s;
1408 * Hebrew Gematria number formatting up to 9999
1410 static function hebrewNumeral( $num ) {
1411 static $table = array(
1412 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1413 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1414 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1415 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1418 $num = intval( $num );
1419 if ( $num > 9999 || $num <= 0 ) {
1420 return $num;
1423 $s = '';
1424 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1425 if ( $num >= $pow10 ) {
1426 if ( $num == 15 || $num == 16 ) {
1427 $s .= $table[0][9] . $table[0][$num - 9];
1428 $num = 0;
1429 } else {
1430 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1431 if ( $pow10 == 1000 ) {
1432 $s .= "'";
1436 $num = $num % $pow10;
1438 if ( strlen( $s ) == 2 ) {
1439 $str = $s . "'";
1440 } else {
1441 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1442 $str .= substr( $s, strlen( $s ) - 2, 2 );
1444 $start = substr( $str, 0, strlen( $str ) - 2 );
1445 $end = substr( $str, strlen( $str ) - 2 );
1446 switch( $end ) {
1447 case 'כ':
1448 $str = $start . 'ך';
1449 break;
1450 case 'מ':
1451 $str = $start . 'ם';
1452 break;
1453 case 'נ':
1454 $str = $start . 'ן';
1455 break;
1456 case 'פ':
1457 $str = $start . 'ף';
1458 break;
1459 case 'צ':
1460 $str = $start . 'ץ';
1461 break;
1463 return $str;
1467 * This is meant to be used by time(), date(), and timeanddate() to get
1468 * the date preference they're supposed to use, it should be used in
1469 * all children.
1471 *<code>
1472 * function timeanddate([...], $format = true) {
1473 * $datePreference = $this->dateFormat($format);
1474 * [...]
1476 *</code>
1478 * @param $usePrefs Mixed: if true, the user's preference is used
1479 * if false, the site/language default is used
1480 * if int/string, assumed to be a format.
1481 * @return string
1483 function dateFormat( $usePrefs = true ) {
1484 global $wgUser;
1486 if ( is_bool( $usePrefs ) ) {
1487 if ( $usePrefs ) {
1488 $datePreference = $wgUser->getDatePreference();
1489 } else {
1490 $datePreference = (string)User::getDefaultOption( 'date' );
1492 } else {
1493 $datePreference = (string)$usePrefs;
1496 // return int
1497 if ( $datePreference == '' ) {
1498 return 'default';
1501 return $datePreference;
1505 * Get a format string for a given type and preference
1506 * @param $type May be date, time or both
1507 * @param $pref The format name as it appears in Messages*.php
1509 function getDateFormatString( $type, $pref ) {
1510 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1511 if ( $pref == 'default' ) {
1512 $pref = $this->getDefaultDateFormat();
1513 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1514 } else {
1515 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1516 if ( is_null( $df ) ) {
1517 $pref = $this->getDefaultDateFormat();
1518 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1521 $this->dateFormatStrings[$type][$pref] = $df;
1523 return $this->dateFormatStrings[$type][$pref];
1527 * @param $ts Mixed: the time format which needs to be turned into a
1528 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1529 * @param $adj Bool: whether to adjust the time output according to the
1530 * user configured offset ($timecorrection)
1531 * @param $format Mixed: true to use user's date format preference
1532 * @param $timecorrection String: the time offset as returned by
1533 * validateTimeZone() in Special:Preferences
1534 * @return string
1536 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1537 $ts = wfTimestamp( TS_MW, $ts );
1538 if ( $adj ) {
1539 $ts = $this->userAdjust( $ts, $timecorrection );
1541 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1542 return $this->sprintfDate( $df, $ts );
1546 * @param $ts Mixed: the time format which needs to be turned into a
1547 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1548 * @param $adj Bool: whether to adjust the time output according to the
1549 * user configured offset ($timecorrection)
1550 * @param $format Mixed: true to use user's date format preference
1551 * @param $timecorrection String: the time offset as returned by
1552 * validateTimeZone() in Special:Preferences
1553 * @return string
1555 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1556 $ts = wfTimestamp( TS_MW, $ts );
1557 if ( $adj ) {
1558 $ts = $this->userAdjust( $ts, $timecorrection );
1560 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1561 return $this->sprintfDate( $df, $ts );
1565 * @param $ts Mixed: the time format which needs to be turned into a
1566 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1567 * @param $adj Bool: whether to adjust the time output according to the
1568 * user configured offset ($timecorrection)
1569 * @param $format Mixed: what format to return, if it's false output the
1570 * default one (default true)
1571 * @param $timecorrection String: the time offset as returned by
1572 * validateTimeZone() in Special:Preferences
1573 * @return string
1575 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1576 $ts = wfTimestamp( TS_MW, $ts );
1577 if ( $adj ) {
1578 $ts = $this->userAdjust( $ts, $timecorrection );
1580 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1581 return $this->sprintfDate( $df, $ts );
1584 function getMessage( $key ) {
1585 // Don't change getPreferredVariant() to getCode() / mCode, because:
1587 // 1. Some language like Chinese has multiple variant languages. Only
1588 // getPreferredVariant() (in LanguageConverter) could return a
1589 // sub-language which would be more suitable for the user.
1590 // 2. To languages without multiple variants, getPreferredVariant()
1591 // (in FakeConverter) functions exactly same as getCode() / mCode,
1592 // it won't break anything.
1594 // The same below.
1595 return self::$dataCache->getSubitem( $this->getPreferredVariant(), 'messages', $key );
1598 function getAllMessages() {
1599 return self::$dataCache->getItem( $this->getPreferredVariant(), 'messages' );
1602 function iconv( $in, $out, $string ) {
1603 # This is a wrapper for iconv in all languages except esperanto,
1604 # which does some nasty x-conversions beforehand
1606 # Even with //IGNORE iconv can whine about illegal characters in
1607 # *input* string. We just ignore those too.
1608 # REF: http://bugs.php.net/bug.php?id=37166
1609 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1610 wfSuppressWarnings();
1611 $text = iconv( $in, $out . '//IGNORE', $string );
1612 wfRestoreWarnings();
1613 return $text;
1616 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1617 function ucwordbreaksCallbackAscii( $matches ) {
1618 return $this->ucfirst( $matches[1] );
1621 function ucwordbreaksCallbackMB( $matches ) {
1622 return mb_strtoupper( $matches[0] );
1625 function ucCallback( $matches ) {
1626 list( $wikiUpperChars ) = self::getCaseMaps();
1627 return strtr( $matches[1], $wikiUpperChars );
1630 function lcCallback( $matches ) {
1631 list( , $wikiLowerChars ) = self::getCaseMaps();
1632 return strtr( $matches[1], $wikiLowerChars );
1635 function ucwordsCallbackMB( $matches ) {
1636 return mb_strtoupper( $matches[0] );
1639 function ucwordsCallbackWiki( $matches ) {
1640 list( $wikiUpperChars ) = self::getCaseMaps();
1641 return strtr( $matches[0], $wikiUpperChars );
1645 * Make a string's first character uppercase
1647 function ucfirst( $str ) {
1648 $o = ord( $str );
1649 if ( $o < 96 ) { // if already uppercase...
1650 return $str;
1651 } elseif ( $o < 128 ) {
1652 return ucfirst( $str ); // use PHP's ucfirst()
1653 } else {
1654 // fall back to more complex logic in case of multibyte strings
1655 return $this->uc( $str, true );
1660 * Convert a string to uppercase
1662 function uc( $str, $first = false ) {
1663 if ( function_exists( 'mb_strtoupper' ) ) {
1664 if ( $first ) {
1665 if ( $this->isMultibyte( $str ) ) {
1666 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1667 } else {
1668 return ucfirst( $str );
1670 } else {
1671 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1673 } else {
1674 if ( $this->isMultibyte( $str ) ) {
1675 $x = $first ? '^' : '';
1676 return preg_replace_callback(
1677 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1678 array( $this, 'ucCallback' ),
1679 $str
1681 } else {
1682 return $first ? ucfirst( $str ) : strtoupper( $str );
1687 function lcfirst( $str ) {
1688 $o = ord( $str );
1689 if ( !$o ) {
1690 return strval( $str );
1691 } elseif ( $o >= 128 ) {
1692 return $this->lc( $str, true );
1693 } elseif ( $o > 96 ) {
1694 return $str;
1695 } else {
1696 $str[0] = strtolower( $str[0] );
1697 return $str;
1701 function lc( $str, $first = false ) {
1702 if ( function_exists( 'mb_strtolower' ) ) {
1703 if ( $first ) {
1704 if ( $this->isMultibyte( $str ) ) {
1705 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1706 } else {
1707 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1709 } else {
1710 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1712 } else {
1713 if ( $this->isMultibyte( $str ) ) {
1714 $x = $first ? '^' : '';
1715 return preg_replace_callback(
1716 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1717 array( $this, 'lcCallback' ),
1718 $str
1720 } else {
1721 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1726 function isMultibyte( $str ) {
1727 return (bool)preg_match( '/[\x80-\xff]/', $str );
1730 function ucwords( $str ) {
1731 if ( $this->isMultibyte( $str ) ) {
1732 $str = $this->lc( $str );
1734 // regexp to find first letter in each word (i.e. after each space)
1735 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1737 // function to use to capitalize a single char
1738 if ( function_exists( 'mb_strtoupper' ) ) {
1739 return preg_replace_callback(
1740 $replaceRegexp,
1741 array( $this, 'ucwordsCallbackMB' ),
1742 $str
1744 } else {
1745 return preg_replace_callback(
1746 $replaceRegexp,
1747 array( $this, 'ucwordsCallbackWiki' ),
1748 $str
1751 } else {
1752 return ucwords( strtolower( $str ) );
1756 # capitalize words at word breaks
1757 function ucwordbreaks( $str ) {
1758 if ( $this->isMultibyte( $str ) ) {
1759 $str = $this->lc( $str );
1761 // since \b doesn't work for UTF-8, we explicitely define word break chars
1762 $breaks = "[ \-\(\)\}\{\.,\?!]";
1764 // find first letter after word break
1765 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1767 if ( function_exists( 'mb_strtoupper' ) ) {
1768 return preg_replace_callback(
1769 $replaceRegexp,
1770 array( $this, 'ucwordbreaksCallbackMB' ),
1771 $str
1773 } else {
1774 return preg_replace_callback(
1775 $replaceRegexp,
1776 array( $this, 'ucwordsCallbackWiki' ),
1777 $str
1780 } else {
1781 return preg_replace_callback(
1782 '/\b([\w\x80-\xff]+)\b/',
1783 array( $this, 'ucwordbreaksCallbackAscii' ),
1784 $str
1790 * Return a case-folded representation of $s
1792 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1793 * and $s2 are the same except for the case of their characters. It is not
1794 * necessary for the value returned to make sense when displayed.
1796 * Do *not* perform any other normalisation in this function. If a caller
1797 * uses this function when it should be using a more general normalisation
1798 * function, then fix the caller.
1800 function caseFold( $s ) {
1801 return $this->uc( $s );
1804 function checkTitleEncoding( $s ) {
1805 if ( is_array( $s ) ) {
1806 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1808 # Check for non-UTF-8 URLs
1809 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1810 if ( !$ishigh ) {
1811 return $s;
1814 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1815 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1816 if ( $isutf8 ) {
1817 return $s;
1820 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1823 function fallback8bitEncoding() {
1824 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
1828 * Most writing systems use whitespace to break up words.
1829 * Some languages such as Chinese don't conventionally do this,
1830 * which requires special handling when breaking up words for
1831 * searching etc.
1833 function hasWordBreaks() {
1834 return true;
1838 * Some languages such as Chinese require word segmentation,
1839 * Specify such segmentation when overridden in derived class.
1841 * @param $string String
1842 * @return String
1844 function segmentByWord( $string ) {
1845 return $string;
1849 * Some languages have special punctuation need to be normalized.
1850 * Make such changes here.
1852 * @param $string String
1853 * @return String
1855 function normalizeForSearch( $string ) {
1856 return self::convertDoubleWidth( $string );
1860 * convert double-width roman characters to single-width.
1861 * range: ff00-ff5f ~= 0020-007f
1863 protected static function convertDoubleWidth( $string ) {
1864 static $full = null;
1865 static $half = null;
1867 if ( $full === null ) {
1868 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1869 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1870 $full = str_split( $fullWidth, 3 );
1871 $half = str_split( $halfWidth );
1874 $string = str_replace( $full, $half, $string );
1875 return $string;
1878 protected static function insertSpace( $string, $pattern ) {
1879 $string = preg_replace( $pattern, " $1 ", $string );
1880 $string = preg_replace( '/ +/', ' ', $string );
1881 return $string;
1884 function convertForSearchResult( $termsArray ) {
1885 # some languages, e.g. Chinese, need to do a conversion
1886 # in order for search results to be displayed correctly
1887 return $termsArray;
1891 * Get the first character of a string.
1893 * @param $s string
1894 * @return string
1896 function firstChar( $s ) {
1897 $matches = array();
1898 preg_match(
1899 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1900 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1902 $matches
1905 if ( isset( $matches[1] ) ) {
1906 if ( strlen( $matches[1] ) != 3 ) {
1907 return $matches[1];
1910 // Break down Hangul syllables to grab the first jamo
1911 $code = utf8ToCodepoint( $matches[1] );
1912 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
1913 return $matches[1];
1914 } elseif ( $code < 0xb098 ) {
1915 return "\xe3\x84\xb1";
1916 } elseif ( $code < 0xb2e4 ) {
1917 return "\xe3\x84\xb4";
1918 } elseif ( $code < 0xb77c ) {
1919 return "\xe3\x84\xb7";
1920 } elseif ( $code < 0xb9c8 ) {
1921 return "\xe3\x84\xb9";
1922 } elseif ( $code < 0xbc14 ) {
1923 return "\xe3\x85\x81";
1924 } elseif ( $code < 0xc0ac ) {
1925 return "\xe3\x85\x82";
1926 } elseif ( $code < 0xc544 ) {
1927 return "\xe3\x85\x85";
1928 } elseif ( $code < 0xc790 ) {
1929 return "\xe3\x85\x87";
1930 } elseif ( $code < 0xcc28 ) {
1931 return "\xe3\x85\x88";
1932 } elseif ( $code < 0xce74 ) {
1933 return "\xe3\x85\x8a";
1934 } elseif ( $code < 0xd0c0 ) {
1935 return "\xe3\x85\x8b";
1936 } elseif ( $code < 0xd30c ) {
1937 return "\xe3\x85\x8c";
1938 } elseif ( $code < 0xd558 ) {
1939 return "\xe3\x85\x8d";
1940 } else {
1941 return "\xe3\x85\x8e";
1943 } else {
1944 return '';
1948 function initEncoding() {
1949 # Some languages may have an alternate char encoding option
1950 # (Esperanto X-coding, Japanese furigana conversion, etc)
1951 # If this language is used as the primary content language,
1952 # an override to the defaults can be set here on startup.
1955 function recodeForEdit( $s ) {
1956 # For some languages we'll want to explicitly specify
1957 # which characters make it into the edit box raw
1958 # or are converted in some way or another.
1959 # Note that if wgOutputEncoding is different from
1960 # wgInputEncoding, this text will be further converted
1961 # to wgOutputEncoding.
1962 global $wgEditEncoding;
1963 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
1964 return $s;
1965 } else {
1966 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1970 function recodeInput( $s ) {
1971 # Take the previous into account.
1972 global $wgEditEncoding;
1973 if ( $wgEditEncoding != '' ) {
1974 $enc = $wgEditEncoding;
1975 } else {
1976 $enc = 'UTF-8';
1978 if ( $enc == 'UTF-8' ) {
1979 return $s;
1980 } else {
1981 return $this->iconv( $enc, 'UTF-8', $s );
1986 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1987 * also cleans up certain backwards-compatible sequences, converting them
1988 * to the modern Unicode equivalent.
1990 * This is language-specific for performance reasons only.
1992 function normalize( $s ) {
1993 global $wgAllUnicodeFixes;
1994 $s = UtfNormal::cleanUp( $s );
1995 if ( $wgAllUnicodeFixes ) {
1996 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1997 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2000 return $s;
2004 * Transform a string using serialized data stored in the given file (which
2005 * must be in the serialized subdirectory of $IP). The file contains pairs
2006 * mapping source characters to destination characters.
2008 * The data is cached in process memory. This will go faster if you have the
2009 * FastStringSearch extension.
2011 function transformUsingPairFile( $file, $string ) {
2012 if ( !isset( $this->transformData[$file] ) ) {
2013 $data = wfGetPrecompiledData( $file );
2014 if ( $data === false ) {
2015 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2017 $this->transformData[$file] = new ReplacementArray( $data );
2019 return $this->transformData[$file]->replace( $string );
2023 * For right-to-left language support
2025 * @return bool
2027 function isRTL() {
2028 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2032 * Return the correct HTML 'dir' attribute value for this language.
2033 * @return String
2035 function getDir() {
2036 return $this->isRTL() ? 'rtl' : 'ltr';
2040 * Return 'left' or 'right' as appropriate alignment for line-start
2041 * for this language's text direction.
2043 * Should be equivalent to CSS3 'start' text-align value....
2045 * @return String
2047 function alignStart() {
2048 return $this->isRTL() ? 'right' : 'left';
2052 * Return 'right' or 'left' as appropriate alignment for line-end
2053 * for this language's text direction.
2055 * Should be equivalent to CSS3 'end' text-align value....
2057 * @return String
2059 function alignEnd() {
2060 return $this->isRTL() ? 'left' : 'right';
2064 * A hidden direction mark (LRM or RLM), depending on the language direction
2066 * @return string
2068 function getDirMark() {
2069 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
2072 function capitalizeAllNouns() {
2073 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2077 * An arrow, depending on the language direction
2079 * @return string
2081 function getArrow() {
2082 return $this->isRTL() ? '←' : '→';
2086 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2088 * @return bool
2090 function linkPrefixExtension() {
2091 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2094 function getMagicWords() {
2095 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2098 # Fill a MagicWord object with data from here
2099 function getMagic( $mw ) {
2100 if ( !$this->mMagicHookDone ) {
2101 $this->mMagicHookDone = true;
2102 wfProfileIn( 'LanguageGetMagic' );
2103 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2104 wfProfileOut( 'LanguageGetMagic' );
2106 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2107 $rawEntry = $this->mMagicExtensions[$mw->mId];
2108 } else {
2109 $magicWords = $this->getMagicWords();
2110 if ( isset( $magicWords[$mw->mId] ) ) {
2111 $rawEntry = $magicWords[$mw->mId];
2112 } else {
2113 $rawEntry = false;
2117 if ( !is_array( $rawEntry ) ) {
2118 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2119 } else {
2120 $mw->mCaseSensitive = $rawEntry[0];
2121 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2126 * Add magic words to the extension array
2128 function addMagicWordsByLang( $newWords ) {
2129 $code = $this->getCode();
2130 $fallbackChain = array();
2131 while ( $code && !in_array( $code, $fallbackChain ) ) {
2132 $fallbackChain[] = $code;
2133 $code = self::getFallbackFor( $code );
2135 if ( !in_array( 'en', $fallbackChain ) ) {
2136 $fallbackChain[] = 'en';
2138 $fallbackChain = array_reverse( $fallbackChain );
2139 foreach ( $fallbackChain as $code ) {
2140 if ( isset( $newWords[$code] ) ) {
2141 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2147 * Get special page names, as an associative array
2148 * case folded alias => real name
2150 function getSpecialPageAliases() {
2151 // Cache aliases because it may be slow to load them
2152 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2153 // Initialise array
2154 $this->mExtendedSpecialPageAliases =
2155 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2156 wfRunHooks( 'LanguageGetSpecialPageAliases',
2157 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2160 return $this->mExtendedSpecialPageAliases;
2164 * Italic is unsuitable for some languages
2166 * @param $text String: the text to be emphasized.
2167 * @return string
2169 function emphasize( $text ) {
2170 return "<em>$text</em>";
2174 * Normally we output all numbers in plain en_US style, that is
2175 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2176 * point twohundredthirtyfive. However this is not sutable for all
2177 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2178 * Icelandic just want to use commas instead of dots, and dots instead
2179 * of commas like "293.291,235".
2181 * An example of this function being called:
2182 * <code>
2183 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2184 * </code>
2186 * See LanguageGu.php for the Gujarati implementation and
2187 * $separatorTransformTable on MessageIs.php for
2188 * the , => . and . => , implementation.
2190 * @todo check if it's viable to use localeconv() for the decimal
2191 * separator thing.
2192 * @param $number Mixed: the string to be formatted, should be an integer
2193 * or a floating point number.
2194 * @param $nocommafy Bool: set to true for special numbers like dates
2195 * @return string
2197 function formatNum( $number, $nocommafy = false ) {
2198 global $wgTranslateNumerals;
2199 if ( !$nocommafy ) {
2200 $number = $this->commafy( $number );
2201 $s = $this->separatorTransformTable();
2202 if ( $s ) {
2203 $number = strtr( $number, $s );
2207 if ( $wgTranslateNumerals ) {
2208 $s = $this->digitTransformTable();
2209 if ( $s ) {
2210 $number = strtr( $number, $s );
2214 return $number;
2217 function parseFormattedNumber( $number ) {
2218 $s = $this->digitTransformTable();
2219 if ( $s ) {
2220 $number = strtr( $number, array_flip( $s ) );
2223 $s = $this->separatorTransformTable();
2224 if ( $s ) {
2225 $number = strtr( $number, array_flip( $s ) );
2228 $number = strtr( $number, array( ',' => '' ) );
2229 return $number;
2233 * Adds commas to a given number
2235 * @param $_ mixed
2236 * @return string
2238 function commafy( $_ ) {
2239 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2242 function digitTransformTable() {
2243 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2246 function separatorTransformTable() {
2247 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2251 * Take a list of strings and build a locale-friendly comma-separated
2252 * list, using the local comma-separator message.
2253 * The last two strings are chained with an "and".
2255 * @param $l Array
2256 * @return string
2258 function listToText( $l ) {
2259 $s = '';
2260 $m = count( $l ) - 1;
2261 if ( $m == 1 ) {
2262 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2263 } else {
2264 for ( $i = $m; $i >= 0; $i-- ) {
2265 if ( $i == $m ) {
2266 $s = $l[$i];
2267 } else if ( $i == $m - 1 ) {
2268 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2269 } else {
2270 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2273 return $s;
2278 * Take a list of strings and build a locale-friendly comma-separated
2279 * list, using the local comma-separator message.
2280 * @param $list array of strings to put in a comma list
2281 * @return string
2283 function commaList( $list ) {
2284 return implode(
2285 $list,
2286 wfMsgExt(
2287 'comma-separator',
2288 array( 'parsemag', 'escapenoentities', 'language' => $this )
2294 * Take a list of strings and build a locale-friendly semicolon-separated
2295 * list, using the local semicolon-separator message.
2296 * @param $list array of strings to put in a semicolon list
2297 * @return string
2299 function semicolonList( $list ) {
2300 return implode(
2301 $list,
2302 wfMsgExt(
2303 'semicolon-separator',
2304 array( 'parsemag', 'escapenoentities', 'language' => $this )
2310 * Same as commaList, but separate it with the pipe instead.
2311 * @param $list array of strings to put in a pipe list
2312 * @return string
2314 function pipeList( $list ) {
2315 return implode(
2316 $list,
2317 wfMsgExt(
2318 'pipe-separator',
2319 array( 'escapenoentities', 'language' => $this )
2325 * Truncate a string to a specified length in bytes, appending an optional
2326 * string (e.g. for ellipses)
2328 * The database offers limited byte lengths for some columns in the database;
2329 * multi-byte character sets mean we need to ensure that only whole characters
2330 * are included, otherwise broken characters can be passed to the user
2332 * If $length is negative, the string will be truncated from the beginning
2334 * @param $string String to truncate
2335 * @param $length Int: maximum length (excluding ellipses)
2336 * @param $ellipsis String to append to the truncated text
2337 * @return string
2339 function truncate( $string, $length, $ellipsis = '...' ) {
2340 # Use the localized ellipsis character
2341 if ( $ellipsis == '...' ) {
2342 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2344 # Check if there is no need to truncate
2345 if ( $length == 0 ) {
2346 return $ellipsis;
2347 } elseif ( strlen( $string ) <= abs( $length ) ) {
2348 return $string;
2350 $stringOriginal = $string;
2351 if ( $length > 0 ) {
2352 $string = substr( $string, 0, $length ); // xyz...
2353 $string = $this->removeBadCharLast( $string );
2354 $string = $string . $ellipsis;
2355 } else {
2356 $string = substr( $string, $length ); // ...xyz
2357 $string = $this->removeBadCharFirst( $string );
2358 $string = $ellipsis . $string;
2360 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2361 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2362 return $string;
2363 } else {
2364 return $stringOriginal;
2369 * Remove bytes that represent an incomplete Unicode character
2370 * at the end of string (e.g. bytes of the char are missing)
2372 * @param $string String
2373 * @return string
2375 protected function removeBadCharLast( $string ) {
2376 $char = ord( $string[strlen( $string ) - 1] );
2377 $m = array();
2378 if ( $char >= 0xc0 ) {
2379 # We got the first byte only of a multibyte char; remove it.
2380 $string = substr( $string, 0, -1 );
2381 } elseif ( $char >= 0x80 &&
2382 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2383 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2385 # We chopped in the middle of a character; remove it
2386 $string = $m[1];
2388 return $string;
2392 * Remove bytes that represent an incomplete Unicode character
2393 * at the start of string (e.g. bytes of the char are missing)
2395 * @param $string String
2396 * @return string
2398 protected function removeBadCharFirst( $string ) {
2399 $char = ord( $string[0] );
2400 if ( $char >= 0x80 && $char < 0xc0 ) {
2401 # We chopped in the middle of a character; remove the whole thing
2402 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2404 return $string;
2408 * Truncate a string of valid HTML to a specified length in bytes,
2409 * appending an optional string (e.g. for ellipses), and return valid HTML
2411 * This is only intended for styled/linked text, such as HTML with
2412 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2414 * Note: tries to fix broken HTML with MWTidy
2416 * @param string $text HTML string to truncate
2417 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2418 * @param string $ellipsis String to append to the truncated text
2419 * @returns string
2421 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2422 # Use the localized ellipsis character
2423 if ( $ellipsis == '...' ) {
2424 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2426 # Check if there is no need to truncate
2427 if ( $length <= 0 ) {
2428 return $ellipsis; // no text shown, nothing to format
2429 } elseif ( strlen( $text ) <= $length ) {
2430 return $text; // string short enough even *with* HTML
2432 $text = MWTidy::tidy( $text ); // fix tags
2433 $displayLen = 0; // innerHTML legth so far
2434 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2435 $tagType = 0; // 0-open, 1-close
2436 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2437 $entityState = 0; // 0-not entity, 1-entity
2438 $tag = $ret = '';
2439 $openTags = array(); // open tag stack
2440 $textLen = strlen( $text );
2441 for ( $pos = 0; $pos < $textLen; ++$pos ) {
2442 $ch = $text[$pos];
2443 $lastCh = $pos ? $text[$pos - 1] : '';
2444 $ret .= $ch; // add to result string
2445 if ( $ch == '<' ) {
2446 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2447 $entityState = 0; // for bad HTML
2448 $bracketState = 1; // tag started (checking for backslash)
2449 } elseif ( $ch == '>' ) {
2450 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2451 $entityState = 0; // for bad HTML
2452 $bracketState = 0; // out of brackets
2453 } elseif ( $bracketState == 1 ) {
2454 if ( $ch == '/' ) {
2455 $tagType = 1; // close tag (e.g. "</span>")
2456 } else {
2457 $tagType = 0; // open tag (e.g. "<span>")
2458 $tag .= $ch;
2460 $bracketState = 2; // building tag name
2461 } elseif ( $bracketState == 2 ) {
2462 if ( $ch != ' ' ) {
2463 $tag .= $ch;
2464 } else {
2465 // Name found (e.g. "<a href=..."), add on tag attributes...
2466 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2468 } elseif ( $bracketState == 0 ) {
2469 if ( $entityState ) {
2470 if ( $ch == ';' ) {
2471 $entityState = 0;
2472 $displayLen++; // entity is one displayed char
2474 } else {
2475 if ( $ch == '&' ) {
2476 $entityState = 1; // entity found, (e.g. "&#160;")
2477 } else {
2478 $displayLen++; // this char is displayed
2479 // Add on the other display text after this...
2480 $skipped = $this->truncate_skip(
2481 $ret, $text, "<>&", $pos + 1, $length - $displayLen );
2482 $displayLen += $skipped;
2483 $pos += $skipped;
2487 # Consider truncation once the display length has reached the maximim.
2488 # Double-check that we're not in the middle of a bracket/entity...
2489 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2490 if ( !$testingEllipsis ) {
2491 $testingEllipsis = true;
2492 # Save where we are; we will truncate here unless
2493 # the ellipsis actually makes the string longer.
2494 $pOpenTags = $openTags; // save state
2495 $pRet = $ret; // save state
2496 } elseif ( $displayLen > ( $length + strlen( $ellipsis ) ) ) {
2497 # Ellipsis won't make string longer/equal, the truncation point was OK.
2498 $openTags = $pOpenTags; // reload state
2499 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2500 $ret .= $ellipsis; // add ellipsis
2501 break;
2505 if ( $displayLen == 0 ) {
2506 return ''; // no text shown, nothing to format
2508 // Close the last tag if left unclosed by bad HTML
2509 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2510 while ( count( $openTags ) > 0 ) {
2511 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2513 return $ret;
2516 // truncateHtml() helper function
2517 // like strcspn() but adds the skipped chars to $ret
2518 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2519 $skipCount = 0;
2520 if ( $start < strlen( $text ) ) {
2521 $skipCount = strcspn( $text, $search, $start, $len );
2522 $ret .= substr( $text, $start, $skipCount );
2524 return $skipCount;
2528 * truncateHtml() helper function
2529 * (a) push or pop $tag from $openTags as needed
2530 * (b) clear $tag value
2531 * @param String &$tag Current HTML tag name we are looking at
2532 * @param int $tagType (0-open tag, 1-close tag)
2533 * @param char $lastCh Character before the '>' that ended this tag
2534 * @param array &$openTags Open tag stack (not accounting for $tag)
2536 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2537 $tag = ltrim( $tag );
2538 if ( $tag != '' ) {
2539 if ( $tagType == 0 && $lastCh != '/' ) {
2540 $openTags[] = $tag; // tag opened (didn't close itself)
2541 } else if ( $tagType == 1 ) {
2542 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2543 array_pop( $openTags ); // tag closed
2546 $tag = '';
2551 * Grammatical transformations, needed for inflected languages
2552 * Invoked by putting {{grammar:case|word}} in a message
2554 * @param $word string
2555 * @param $case string
2556 * @return string
2558 function convertGrammar( $word, $case ) {
2559 global $wgGrammarForms;
2560 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2561 return $wgGrammarForms[$this->getCode()][$case][$word];
2563 return $word;
2567 * Provides an alternative text depending on specified gender.
2568 * Usage {{gender:username|masculine|feminine|neutral}}.
2569 * username is optional, in which case the gender of current user is used,
2570 * but only in (some) interface messages; otherwise default gender is used.
2571 * If second or third parameter are not specified, masculine is used.
2572 * These details may be overriden per language.
2574 function gender( $gender, $forms ) {
2575 if ( !count( $forms ) ) {
2576 return '';
2578 $forms = $this->preConvertPlural( $forms, 2 );
2579 if ( $gender === 'male' ) {
2580 return $forms[0];
2582 if ( $gender === 'female' ) {
2583 return $forms[1];
2585 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2589 * Plural form transformations, needed for some languages.
2590 * For example, there are 3 form of plural in Russian and Polish,
2591 * depending on "count mod 10". See [[w:Plural]]
2592 * For English it is pretty simple.
2594 * Invoked by putting {{plural:count|wordform1|wordform2}}
2595 * or {{plural:count|wordform1|wordform2|wordform3}}
2597 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2599 * @param $count Integer: non-localized number
2600 * @param $forms Array: different plural forms
2601 * @return string Correct form of plural for $count in this language
2603 function convertPlural( $count, $forms ) {
2604 if ( !count( $forms ) ) {
2605 return '';
2607 $forms = $this->preConvertPlural( $forms, 2 );
2609 return ( $count == 1 ) ? $forms[0] : $forms[1];
2613 * Checks that convertPlural was given an array and pads it to requested
2614 * amound of forms by copying the last one.
2616 * @param $count Integer: How many forms should there be at least
2617 * @param $forms Array of forms given to convertPlural
2618 * @return array Padded array of forms or an exception if not an array
2620 protected function preConvertPlural( /* Array */ $forms, $count ) {
2621 while ( count( $forms ) < $count ) {
2622 $forms[] = $forms[count( $forms ) - 1];
2624 return $forms;
2628 * For translating of expiry times
2629 * @param $str String: the validated block time in English
2630 * @return Somehow translated block time
2631 * @see LanguageFi.php for example implementation
2633 function translateBlockExpiry( $str ) {
2634 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2636 if ( $scBlockExpiryOptions == '-' ) {
2637 return $str;
2640 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2641 if ( strpos( $option, ':' ) === false ) {
2642 continue;
2644 list( $show, $value ) = explode( ':', $option );
2645 if ( strcmp( $str, $value ) == 0 ) {
2646 return htmlspecialchars( trim( $show ) );
2650 return $str;
2654 * languages like Chinese need to be segmented in order for the diff
2655 * to be of any use
2657 * @param $text String
2658 * @return String
2660 function segmentForDiff( $text ) {
2661 return $text;
2665 * and unsegment to show the result
2667 * @param $text String
2668 * @return String
2670 function unsegmentForDiff( $text ) {
2671 return $text;
2674 # convert text to all supported variants
2675 function autoConvertToAllVariants( $text ) {
2676 return $this->mConverter->autoConvertToAllVariants( $text );
2679 # convert text to different variants of a language.
2680 function convert( $text ) {
2681 return $this->mConverter->convert( $text );
2684 # Convert a Title object to a string in the preferred variant
2685 function convertTitle( $title ) {
2686 return $this->mConverter->convertTitle( $title );
2689 # Check if this is a language with variants
2690 function hasVariants() {
2691 return sizeof( $this->getVariants() ) > 1;
2694 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2695 function armourMath( $text ) {
2696 return $this->mConverter->armourMath( $text );
2700 * Perform output conversion on a string, and encode for safe HTML output.
2701 * @param $text String text to be converted
2702 * @param $isTitle Bool whether this conversion is for the article title
2703 * @return string
2704 * @todo this should get integrated somewhere sane
2706 function convertHtml( $text, $isTitle = false ) {
2707 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2710 function convertCategoryKey( $key ) {
2711 return $this->mConverter->convertCategoryKey( $key );
2715 * Get the list of variants supported by this language
2716 * see sample implementation in LanguageZh.php
2718 * @return array an array of language codes
2720 function getVariants() {
2721 return $this->mConverter->getVariants();
2724 function getPreferredVariant() {
2725 return $this->mConverter->getPreferredVariant();
2728 function getDefaultVariant() {
2729 return $this->mConverter->getDefaultVariant();
2732 function getURLVariant() {
2733 return $this->mConverter->getURLVariant();
2737 * If a language supports multiple variants, it is
2738 * possible that non-existing link in one variant
2739 * actually exists in another variant. this function
2740 * tries to find it. See e.g. LanguageZh.php
2742 * @param $link String: the name of the link
2743 * @param $nt Mixed: the title object of the link
2744 * @param $ignoreOtherCond Boolean: to disable other conditions when
2745 * we need to transclude a template or update a category's link
2746 * @return null the input parameters may be modified upon return
2748 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2749 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
2753 * If a language supports multiple variants, converts text
2754 * into an array of all possible variants of the text:
2755 * 'variant' => text in that variant
2757 * @deprecated Use autoConvertToAllVariants()
2759 function convertLinkToAllVariants( $text ) {
2760 return $this->mConverter->convertLinkToAllVariants( $text );
2764 * returns language specific options used by User::getPageRenderHash()
2765 * for example, the preferred language variant
2767 * @return string
2769 function getExtraHashOptions() {
2770 return $this->mConverter->getExtraHashOptions();
2774 * For languages that support multiple variants, the title of an
2775 * article may be displayed differently in different variants. this
2776 * function returns the apporiate title defined in the body of the article.
2778 * @return string
2780 function getParsedTitle() {
2781 return $this->mConverter->getParsedTitle();
2785 * Enclose a string with the "no conversion" tag. This is used by
2786 * various functions in the Parser
2788 * @param $text String: text to be tagged for no conversion
2789 * @param $noParse
2790 * @return string the tagged text
2792 function markNoConversion( $text, $noParse = false ) {
2793 return $this->mConverter->markNoConversion( $text, $noParse );
2797 * A regular expression to match legal word-trailing characters
2798 * which should be merged onto a link of the form [[foo]]bar.
2800 * @return string
2802 function linkTrail() {
2803 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
2806 function getLangObj() {
2807 return $this;
2811 * Get the RFC 3066 code for this language object
2813 function getCode() {
2814 return $this->mCode;
2817 function setCode( $code ) {
2818 $this->mCode = $code;
2822 * Get the name of a file for a certain language code
2823 * @param $prefix string Prepend this to the filename
2824 * @param $code string Language code
2825 * @param $suffix string Append this to the filename
2826 * @return string $prefix . $mangledCode . $suffix
2828 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2829 // Protect against path traversal
2830 if ( !Language::isValidCode( $code ) ) {
2831 throw new MWException( "Invalid language code \"$code\"" );
2834 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2838 * Get the language code from a file name. Inverse of getFileName()
2839 * @param $filename string $prefix . $languageCode . $suffix
2840 * @param $prefix string Prefix before the language code
2841 * @param $suffix string Suffix after the language code
2842 * @return Language code, or false if $prefix or $suffix isn't found
2844 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2845 $m = null;
2846 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2847 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2848 if ( !count( $m ) ) {
2849 return false;
2851 return str_replace( '_', '-', strtolower( $m[1] ) );
2854 static function getMessagesFileName( $code ) {
2855 global $IP;
2856 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2859 static function getClassFileName( $code ) {
2860 global $IP;
2861 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2865 * Get the fallback for a given language
2867 static function getFallbackFor( $code ) {
2868 if ( $code === 'en' ) {
2869 // Shortcut
2870 return false;
2871 } else {
2872 return self::getLocalisationCache()->getItem( $code, 'fallback' );
2877 * Get all messages for a given language
2878 * WARNING: this may take a long time
2880 static function getMessagesFor( $code ) {
2881 return self::getLocalisationCache()->getItem( $code, 'messages' );
2885 * Get a message for a given language
2887 static function getMessageFor( $key, $code ) {
2888 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2891 function fixVariableInNamespace( $talk ) {
2892 if ( strpos( $talk, '$1' ) === false ) {
2893 return $talk;
2896 global $wgMetaNamespace;
2897 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2899 # Allow grammar transformations
2900 # Allowing full message-style parsing would make simple requests
2901 # such as action=raw much more expensive than they need to be.
2902 # This will hopefully cover most cases.
2903 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2904 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2905 return str_replace( ' ', '_', $talk );
2908 function replaceGrammarInNamespace( $m ) {
2909 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2912 static function getCaseMaps() {
2913 static $wikiUpperChars, $wikiLowerChars;
2914 if ( isset( $wikiUpperChars ) ) {
2915 return array( $wikiUpperChars, $wikiLowerChars );
2918 wfProfileIn( __METHOD__ );
2919 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2920 if ( $arr === false ) {
2921 throw new MWException(
2922 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2924 $wikiUpperChars = $arr['wikiUpperChars'];
2925 $wikiLowerChars = $arr['wikiLowerChars'];
2926 wfProfileOut( __METHOD__ );
2927 return array( $wikiUpperChars, $wikiLowerChars );
2930 function formatTimePeriod( $seconds ) {
2931 if ( round( $seconds * 10 ) < 100 ) {
2932 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2933 } elseif ( round( $seconds ) < 60 ) {
2934 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2935 } elseif ( round( $seconds ) < 3600 ) {
2936 $minutes = floor( $seconds / 60 );
2937 $secondsPart = round( fmod( $seconds, 60 ) );
2938 if ( $secondsPart == 60 ) {
2939 $secondsPart = 0;
2940 $minutes++;
2942 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2943 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2944 } else {
2945 $hours = floor( $seconds / 3600 );
2946 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2947 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2948 if ( $secondsPart == 60 ) {
2949 $secondsPart = 0;
2950 $minutes++;
2952 if ( $minutes == 60 ) {
2953 $minutes = 0;
2954 $hours++;
2956 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2957 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2958 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2962 function formatBitrate( $bps ) {
2963 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2964 if ( $bps <= 0 ) {
2965 return $this->formatNum( $bps ) . $units[0];
2967 $unitIndex = floor( log10( $bps ) / 3 );
2968 $mantissa = $bps / pow( 1000, $unitIndex );
2969 if ( $mantissa < 10 ) {
2970 $mantissa = round( $mantissa, 1 );
2971 } else {
2972 $mantissa = round( $mantissa );
2974 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2978 * Format a size in bytes for output, using an appropriate
2979 * unit (B, KB, MB or GB) according to the magnitude in question
2981 * @param $size Size to format
2982 * @return string Plain text (not HTML)
2984 function formatSize( $size ) {
2985 // For small sizes no decimal places necessary
2986 $round = 0;
2987 if ( $size > 1024 ) {
2988 $size = $size / 1024;
2989 if ( $size > 1024 ) {
2990 $size = $size / 1024;
2991 // For MB and bigger two decimal places are smarter
2992 $round = 2;
2993 if ( $size > 1024 ) {
2994 $size = $size / 1024;
2995 $msg = 'size-gigabytes';
2996 } else {
2997 $msg = 'size-megabytes';
2999 } else {
3000 $msg = 'size-kilobytes';
3002 } else {
3003 $msg = 'size-bytes';
3005 $size = round( $size, $round );
3006 $text = $this->getMessageFromDB( $msg );
3007 return str_replace( '$1', $this->formatNum( $size ), $text );
3011 * Get the conversion rule title, if any.
3013 function getConvRuleTitle() {
3014 return $this->mConverter->getConvRuleTitle();