Merge ".gitignore for generated html doc"
[lhc/web/wiklou.git] / languages / Language.php
index 78d3503..1ef5a74 100644 (file)
@@ -29,10 +29,15 @@ if ( function_exists( 'mb_strtoupper' ) ) {
  * @ingroup Language
  */
 class FakeConverter {
+
+       /**
+        * @var Language
+        */
        var $mLang;
        function __construct( $langobj ) { $this->mLang = $langobj; }
        function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
        function convert( $t ) { return $t; }
+       function convertTo( $text, $variant ) { return $text; }
        function convertTitle( $t ) { return $t->getPrefixedText(); }
        function getVariants() { return array( $this->mLang->getCode() ); }
        function getPreferredVariant() { return $this->mLang->getCode(); }
@@ -61,11 +66,13 @@ class Language {
 
        var $mVariants, $mCode, $mLoaded = false;
        var $mMagicExtensions = array(), $mMagicHookDone = false;
+       private $mHtmlCode = null;
 
-       var $mNamespaceIds, $namespaceNames, $namespaceAliases;
        var $dateFormatStrings = array();
        var $mExtendedSpecialPageAliases;
 
+       protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
+
        /**
         * ReplacementArray object caches
         */
@@ -151,6 +158,7 @@ class Language {
        /**
         * Create a language object for a given language code
         * @param $code String
+        * @throws MWException
         * @return Language
         */
        protected static function newFromCode( $code ) {
@@ -239,7 +247,7 @@ class Language {
        /**
         * Includes language class files
         *
-        * @param $class Name of the language class
+        * @param $class string Name of the language class
         */
        public static function preloadLanguageClass( $class ) {
                global $IP;
@@ -328,7 +336,7 @@ class Language {
        /**
         * @return array
         */
-       function getNamespaces() {
+       public function getNamespaces() {
                if ( is_null( $this->namespaceNames ) ) {
                        global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
 
@@ -362,6 +370,14 @@ class Language {
                return $this->namespaceNames;
        }
 
+       /**
+        * Arbitrarily set all of the namespace names at once. Mainly used for testing
+        * @param $namespaces Array of namespaces (id => name)
+        */
+       public function setNamespaces( array $namespaces ) {
+               $this->namespaceNames = $namespaces;
+       }
+
        /**
         * A convenience function that returns the same thing as
         * getNamespaces() except with the array values changed to ' '
@@ -476,7 +492,7 @@ class Language {
                        }
 
                        global $wgExtraGenderNamespaces;
-                       $genders = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+                       $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
                        foreach ( $genders as $index => $forms ) {
                                foreach ( $forms as $alias ) {
                                        $aliases[$alias] = $index;
@@ -544,7 +560,7 @@ class Language {
                if ( $usemsg && wfMessage( $msg )->exists() ) {
                        return $this->getMessageFromDB( $msg );
                }
-               $name = self::getLanguageName( $code );
+               $name = self::fetchLanguageName( $code );
                if ( $name ) {
                        return $name; # if it's defined as a language name, show that
                } else {
@@ -625,7 +641,7 @@ class Language {
         * @return array
         */
        function getExtraUserToggles() {
-               return self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
+               return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
        }
 
        /**
@@ -637,37 +653,17 @@ class Language {
        }
 
        /**
-        * Get language names, indexed by code.
+        * Get native language names, indexed by code.
+        * Only those defined in MediaWiki, no other data like CLDR.
         * If $customisedOnly is true, only returns codes with a messages file
         *
         * @param $customisedOnly bool
         *
         * @return array
+        * @deprecated in 1.20, use fetchLanguageNames()
         */
        public static function getLanguageNames( $customisedOnly = false ) {
-               global $wgExtraLanguageNames;
-               static $coreLanguageNames;
-
-               if ( $coreLanguageNames === null ) {
-                       include( MWInit::compiledPath( 'languages/Names.php' ) );
-               }
-
-               $allNames = $wgExtraLanguageNames + $coreLanguageNames;
-               if ( !$customisedOnly ) {
-                       return $allNames;
-               }
-
-               global $IP;
-               $names = array();
-               $dir = opendir( "$IP/languages/messages" );
-               while ( false !== ( $file = readdir( $dir ) ) ) {
-                       $code = self::getCodeFromFileName( $file, 'Messages' );
-                       if ( $code && isset( $allNames[$code] ) ) {
-                               $names[$code] = $allNames[$code];
-                       }
-               }
-               closedir( $dir );
-               return $names;
+               return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
        }
 
        /**
@@ -677,16 +673,84 @@ class Language {
         * @param $code String Language code.
         * @return Array language code => language name
         * @since 1.18.0
+        * @deprecated in 1.20, use fetchLanguageNames()
         */
        public static function getTranslatedLanguageNames( $code ) {
+               return self::fetchLanguageNames( $code, 'all' );
+       }
+
+       /**
+        * Get an array of language names, indexed by code.
+        * @param $inLanguage null|string: Code of language in which to return the names
+        *              Use null for autonyms (native names)
+        * @param $include string:
+        *              'all' all available languages
+        *              'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames
+        *              'mwfile' only if the language is in 'mw' *and* has a message file
+        * @return array|bool: language code => language name, false if $include is wrong
+        * @since 1.20
+        */
+       public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
+               global $wgExtraLanguageNames;
+               static $coreLanguageNames;
+
+               if ( $coreLanguageNames === null ) {
+                       include( MWInit::compiledPath( 'languages/Names.php' ) );
+               }
+
                $names = array();
-               wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
 
-               foreach ( self::getLanguageNames() as $code => $name ) {
-                       if ( !isset( $names[$code] ) ) $names[$code] = $name;
+               if( $inLanguage ) {
+                       # TODO: also include when $inLanguage is null, when this code is more efficient
+                       wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
+               }
+
+               $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
+               foreach ( $mwNames as $mwCode => $mwName ) {
+                       # - Prefer own MediaWiki native name when not using the hook
+                       #       TODO: prefer it always to make it consistent, but casing is different in CLDR
+                       # - For other names just add if not added through the hook
+                       if ( ( $mwCode === $inLanguage && !$inLanguage ) || !isset( $names[$mwCode] ) ) {
+                               $names[$mwCode] = $mwName;
+                       }
+               }
+
+               if ( $include === 'all' ) {
+                       return $names;
+               }
+
+               $returnMw = array();
+               $coreCodes = array_keys( $mwNames );
+               foreach( $coreCodes as $coreCode ) {
+                       $returnMw[$coreCode] = $names[$coreCode];
                }
 
-               return $names;
+               if( $include === 'mw' ) {
+                       return $returnMw;
+               } elseif( $include === 'mwfile' ) {
+                       $namesMwFile = array();
+                       # We do this using a foreach over the codes instead of a directory
+                       # loop so that messages files in extensions will work correctly.
+                       foreach ( $returnMw as $code => $value ) {
+                               if ( is_readable( self::getMessagesFileName( $code ) ) ) {
+                                       $namesMwFile[$code] = $names[$code];
+                               }
+                       }
+                       return $namesMwFile;
+               }
+               return false;
+       }
+
+       /**
+        * @param $code string: The code of the language for which to get the name
+        * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
+        * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
+        * @return string: Language name or empty
+        * @since 1.20
+        */
+       public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
+               $array = self::fetchLanguageNames( $inLanguage, $include );
+               return !array_key_exists( $code, $array ) ? '' : $array[$code];
        }
 
        /**
@@ -700,15 +764,14 @@ class Language {
        }
 
        /**
+        * Get the native language name of $code.
+        * Only if defined in MediaWiki, no other data like CLDR.
         * @param $code string
         * @return string
+        * @deprecated in 1.20, use fetchLanguageName()
         */
        function getLanguageName( $code ) {
-               $names = self::getLanguageNames();
-               if ( !array_key_exists( $code, $names ) ) {
-                       return '';
-               }
-               return $names[$code];
+               return self::fetchLanguageName( $code );
        }
 
        /**
@@ -805,82 +868,6 @@ class Language {
                return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
        }
 
-       /**
-        * Used by date() and time() to adjust the time output.
-        *
-        * @param $ts Int the time in date('YmdHis') format
-        * @param $tz Mixed: adjust the time by this amount (default false, mean we
-        *            get user timecorrection setting)
-        * @return int
-        */
-       function userAdjust( $ts, $tz = false ) {
-               global $wgUser, $wgLocalTZoffset;
-
-               if ( $tz === false ) {
-                       $tz = $wgUser->getOption( 'timecorrection' );
-               }
-
-               $data = explode( '|', $tz, 3 );
-
-               if ( $data[0] == 'ZoneInfo' ) {
-                       wfSuppressWarnings();
-                       $userTZ = timezone_open( $data[2] );
-                       wfRestoreWarnings();
-                       if ( $userTZ !== false ) {
-                               $date = date_create( $ts, timezone_open( 'UTC' ) );
-                               date_timezone_set( $date, $userTZ );
-                               $date = date_format( $date, 'YmdHis' );
-                               return $date;
-                       }
-                       # Unrecognized timezone, default to 'Offset' with the stored offset.
-                       $data[0] = 'Offset';
-               }
-
-               $minDiff = 0;
-               if ( $data[0] == 'System' || $tz == '' ) {
-                       #  Global offset in minutes.
-                       if ( isset( $wgLocalTZoffset ) ) {
-                               $minDiff = $wgLocalTZoffset;
-                       }
-               } elseif ( $data[0] == 'Offset' ) {
-                       $minDiff = intval( $data[1] );
-               } else {
-                       $data = explode( ':', $tz );
-                       if ( count( $data ) == 2 ) {
-                               $data[0] = intval( $data[0] );
-                               $data[1] = intval( $data[1] );
-                               $minDiff = abs( $data[0] ) * 60 + $data[1];
-                               if ( $data[0] < 0 ) {
-                                       $minDiff = -$minDiff;
-                               }
-                       } else {
-                               $minDiff = intval( $data[0] ) * 60;
-                       }
-               }
-
-               # No difference ? Return time unchanged
-               if ( 0 == $minDiff ) {
-                       return $ts;
-               }
-
-               wfSuppressWarnings(); // E_STRICT system time bitching
-               # Generate an adjusted date; take advantage of the fact that mktime
-               # will normalize out-of-range values so we don't have to split $minDiff
-               # into hours and minutes.
-               $t = mktime( (
-                 (int)substr( $ts, 8, 2 ) ), # Hours
-                 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
-                 (int)substr( $ts, 12, 2 ), # Seconds
-                 (int)substr( $ts, 4, 2 ), # Month
-                 (int)substr( $ts, 6, 2 ), # Day
-                 (int)substr( $ts, 0, 4 ) ); # Year
-
-               $date = date( 'YmdHis', $t );
-               wfRestoreWarnings();
-
-               return $date;
-       }
-
        /**
         * This is a workalike of PHP's date() function, but with better
         * internationalisation, a reduced set of format characters, and a better
@@ -900,6 +887,7 @@ class Language {
         *    xij  j (day number) in Iranian calendar
         *    xiF  F (month name) in Iranian calendar
         *    xin  n (month number) in Iranian calendar
+        *    xiy  y (two digit year) in Iranian calendar
         *    xiY  Y (full year) in Iranian calendar
         *
         *    xjj  j (day number) in Hebrew calendar
@@ -1118,7 +1106,7 @@ class Language {
                                        if ( !$unix ) {
                                                $unix = wfTimestamp( TS_UNIX, $ts );
                                        }
-                                       $num = date( 'o', $unix );
+                                       $num = gmdate( 'o', $unix );
                                        break;
                                case 'Y':
                                        $num = substr( $ts, 0, 4 );
@@ -1162,6 +1150,12 @@ class Language {
                                case 'y':
                                        $num = substr( $ts, 2, 2 );
                                        break;
+                               case 'xiy':
+                                       if ( !$iranian ) {
+                                               $iranian = self::tsToIranian( $ts );
+                                       }
+                                       $num = substr( $iranian[0], -2 );
+                                       break;
                                case 'a':
                                        $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
                                        break;
@@ -1288,7 +1282,7 @@ class Language {
                }
 
                // Days passed in current month
-               $gDayNo += $gd;
+               $gDayNo += (int)$gd;
 
                $jDayNo = $gDayNo - 79;
 
@@ -1318,7 +1312,7 @@ class Language {
         *
         * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
         *
-        * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
+        * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
         *
         * @param $ts string
         *
@@ -1649,7 +1643,7 @@ class Language {
                $s = '';
                for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
                        if ( $num >= $pow10 ) {
-                               $s .= $table[$i][floor( $num / $pow10 )];
+                               $s .= $table[$i][(int)floor( $num / $pow10 )];
                        }
                        $num = $num % $pow10;
                }
@@ -1719,6 +1713,82 @@ class Language {
                return $str;
        }
 
+       /**
+        * Used by date() and time() to adjust the time output.
+        *
+        * @param $ts Int the time in date('YmdHis') format
+        * @param $tz Mixed: adjust the time by this amount (default false, mean we
+        *            get user timecorrection setting)
+        * @return int
+        */
+       function userAdjust( $ts, $tz = false ) {
+               global $wgUser, $wgLocalTZoffset;
+
+               if ( $tz === false ) {
+                       $tz = $wgUser->getOption( 'timecorrection' );
+               }
+
+               $data = explode( '|', $tz, 3 );
+
+               if ( $data[0] == 'ZoneInfo' ) {
+                       wfSuppressWarnings();
+                       $userTZ = timezone_open( $data[2] );
+                       wfRestoreWarnings();
+                       if ( $userTZ !== false ) {
+                               $date = date_create( $ts, timezone_open( 'UTC' ) );
+                               date_timezone_set( $date, $userTZ );
+                               $date = date_format( $date, 'YmdHis' );
+                               return $date;
+                       }
+                       # Unrecognized timezone, default to 'Offset' with the stored offset.
+                       $data[0] = 'Offset';
+               }
+
+               $minDiff = 0;
+               if ( $data[0] == 'System' || $tz == '' ) {
+                       #  Global offset in minutes.
+                       if ( isset( $wgLocalTZoffset ) ) {
+                               $minDiff = $wgLocalTZoffset;
+                       }
+               } elseif ( $data[0] == 'Offset' ) {
+                       $minDiff = intval( $data[1] );
+               } else {
+                       $data = explode( ':', $tz );
+                       if ( count( $data ) == 2 ) {
+                               $data[0] = intval( $data[0] );
+                               $data[1] = intval( $data[1] );
+                               $minDiff = abs( $data[0] ) * 60 + $data[1];
+                               if ( $data[0] < 0 ) {
+                                       $minDiff = -$minDiff;
+                               }
+                       } else {
+                               $minDiff = intval( $data[0] ) * 60;
+                       }
+               }
+
+               # No difference ? Return time unchanged
+               if ( 0 == $minDiff ) {
+                       return $ts;
+               }
+
+               wfSuppressWarnings(); // E_STRICT system time bitching
+               # Generate an adjusted date; take advantage of the fact that mktime
+               # will normalize out-of-range values so we don't have to split $minDiff
+               # into hours and minutes.
+               $t = mktime( (
+                 (int)substr( $ts, 8, 2 ) ), # Hours
+                 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
+                 (int)substr( $ts, 12, 2 ), # Seconds
+                 (int)substr( $ts, 4, 2 ), # Month
+                 (int)substr( $ts, 6, 2 ), # Day
+                 (int)substr( $ts, 0, 4 ) ); # Year
+
+               $date = date( 'YmdHis', $t );
+               wfRestoreWarnings();
+
+               return $date;
+       }
+
        /**
         * This is meant to be used by time(), date(), and timeanddate() to get
         * the date preference they're supposed to use, it should be used in
@@ -1839,6 +1909,114 @@ class Language {
                return $this->sprintfDate( $df, $ts );
        }
 
+       /**
+        * Internal helper function for userDate(), userTime() and userTimeAndDate()
+        *
+        * @param $type String: can be 'date', 'time' or 'both'
+        * @param $ts Mixed: the time format which needs to be turned into a
+        *            date('YmdHis') format with wfTimestamp(TS_MW,$ts)
+        * @param $user User object used to get preferences for timezone and format
+        * @param $options Array, can contain the following keys:
+        *        - 'timecorrection': time correction, can have the following values:
+        *             - true: use user's preference
+        *             - false: don't use time correction
+        *             - integer: value of time correction in minutes
+        *        - 'format': format to use, can have the following values:
+        *             - true: use user's preference
+        *             - false: use default preference
+        *             - string: format to use
+        * @since 1.19
+        * @return String
+        */
+       private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
+               $ts = wfTimestamp( TS_MW, $ts );
+               $options += array( 'timecorrection' => true, 'format' => true );
+               if ( $options['timecorrection'] !== false ) {
+                       if ( $options['timecorrection'] === true ) {
+                               $offset = $user->getOption( 'timecorrection' );
+                       } else {
+                               $offset = $options['timecorrection'];
+                       }
+                       $ts = $this->userAdjust( $ts, $offset );
+               }
+               if ( $options['format'] === true ) {
+                       $format = $user->getDatePreference();
+               } else {
+                       $format = $options['format'];
+               }
+               $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
+               return $this->sprintfDate( $df, $ts );
+       }
+
+       /**
+        * Get the formatted date for the given timestamp and formatted for
+        * the given user.
+        *
+        * @param $ts Mixed: the time format which needs to be turned into a
+        *            date('YmdHis') format with wfTimestamp(TS_MW,$ts)
+        * @param $user User object used to get preferences for timezone and format
+        * @param $options Array, can contain the following keys:
+        *        - 'timecorrection': time correction, can have the following values:
+        *             - true: use user's preference
+        *             - false: don't use time correction
+        *             - integer: value of time correction in minutes
+        *        - 'format': format to use, can have the following values:
+        *             - true: use user's preference
+        *             - false: use default preference
+        *             - string: format to use
+        * @since 1.19
+        * @return String
+        */
+       public function userDate( $ts, User $user, array $options = array() ) {
+               return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
+       }
+
+       /**
+        * Get the formatted time for the given timestamp and formatted for
+        * the given user.
+        *
+        * @param $ts Mixed: the time format which needs to be turned into a
+        *            date('YmdHis') format with wfTimestamp(TS_MW,$ts)
+        * @param $user User object used to get preferences for timezone and format
+        * @param $options Array, can contain the following keys:
+        *        - 'timecorrection': time correction, can have the following values:
+        *             - true: use user's preference
+        *             - false: don't use time correction
+        *             - integer: value of time correction in minutes
+        *        - 'format': format to use, can have the following values:
+        *             - true: use user's preference
+        *             - false: use default preference
+        *             - string: format to use
+        * @since 1.19
+        * @return String
+        */
+       public function userTime( $ts, User $user, array $options = array() ) {
+               return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
+       }
+
+       /**
+        * Get the formatted date and time for the given timestamp and formatted for
+        * the given user.
+        *
+        * @param $ts Mixed: the time format which needs to be turned into a
+        *            date('YmdHis') format with wfTimestamp(TS_MW,$ts)
+        * @param $user User object used to get preferences for timezone and format
+        * @param $options Array, can contain the following keys:
+        *        - 'timecorrection': time correction, can have the following values:
+        *             - true: use user's preference
+        *             - false: don't use time correction
+        *             - integer: value of time correction in minutes
+        *        - 'format': format to use, can have the following values:
+        *             - true: use user's preference
+        *             - false: use default preference
+        *             - string: format to use
+        * @since 1.19
+        * @return String
+        */
+       public function userTimeAndDate( $ts, User $user, array $options = array() ) {
+               return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
+       }
+
        /**
         * @param $key string
         * @return array|null
@@ -2363,6 +2541,7 @@ class Language {
         * @param $file string
         * @param $string string
         *
+        * @throws MWException
         * @return string
         */
        function transformUsingPairFile( $file, $string ) {
@@ -2418,16 +2597,35 @@ class Language {
        }
 
        /**
-        * A hidden direction mark (LRM or RLM), depending on the language direction
+        * A hidden direction mark (LRM or RLM), depending on the language direction.
+        * Unlike getDirMark(), this function returns the character as an HTML entity.
+        * This function should be used when the output is guaranteed to be HTML,
+        * because it makes the output HTML source code more readable. When
+        * the output is plain text or can be escaped, getDirMark() should be used.
+        *
+        * @param $opposite Boolean Get the direction mark opposite to your language
+        * @return string
+        */
+       function getDirMarkEntity( $opposite = false ) {
+               if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
+               return $this->isRTL() ? '&rlm;' : '&lrm;';
+       }
+
+       /**
+        * A hidden direction mark (LRM or RLM), depending on the language direction.
+        * This function produces them as invisible Unicode characters and
+        * the output may be hard to read and debug, so it should only be used
+        * when the output is plain text or can be escaped. When the output is
+        * HTML, use getDirMarkEntity() instead.
         *
         * @param $opposite Boolean Get the direction mark opposite to your language
         * @return string
         */
        function getDirMark( $opposite = false ) {
-               $rtl = "\xE2\x80\x8F";
-               $ltr = "\xE2\x80\x8E";
-               if ( $opposite ) { return $this->isRTL() ? $ltr : $rtl; }
-               return $this->isRTL() ? $rtl : $ltr;
+               $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
+               $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
+               if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
+               return $this->isRTL() ? $rlm : $lrm;
        }
 
        /**
@@ -2565,7 +2763,7 @@ class Language {
          * @param $nocommafy Bool: set to true for special numbers like dates
          * @return string
          */
-       function formatNum( $number, $nocommafy = false ) {
+       public function formatNum( $number, $nocommafy = false ) {
                global $wgTranslateNumerals;
                if ( !$nocommafy ) {
                        $number = $this->commafy( $number );
@@ -2612,12 +2810,21 @@ class Language {
         */
        function commafy( $_ ) {
                $digitGroupingPattern = $this->digitGroupingPattern();
+               if ( $_ === null ) {
+                       return '';
+               }
 
                if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
                        // default grouping is at thousands,  use the same for ###,###,### pattern too.
                        return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
                } else {
                        // Ref: http://cldr.unicode.org/translation/number-patterns
+                       $sign = "";
+                       if ( intval( $_ ) < 0 ) {
+                               // For negative numbers apply the algorithm like positive number and add sign.
+                               $sign =  "-";
+                               $_ = substr( $_, 1 );
+                       }
                        $numberpart = array();
                        $decimalpart = array();
                        $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
@@ -2626,7 +2833,7 @@ class Language {
                        $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
                        if ( $groupedNumber  === $_ ) {
                                // the string does not have any number part. Eg: .12345
-                               return $groupedNumber;
+                               return $sign . $groupedNumber;
                        }
                        $start = $end = strlen( $numberpart[0] );
                        while ( $start > 0 ) {
@@ -2646,7 +2853,7 @@ class Language {
                                        $groupedNumber = "," . $groupedNumber;
                                }
                        }
-                       return $groupedNumber;
+                       return $sign . $groupedNumber;
                }
        }
        /**
@@ -2678,7 +2885,7 @@ class Language {
         * @param $l Array
         * @return string
         */
-       function listToText( $l ) {
+       function listToText( array $l ) {
                $s = '';
                $m = count( $l ) - 1;
                if ( $m == 1 ) {
@@ -2703,13 +2910,13 @@ class Language {
         * @param $list array of strings to put in a comma list
         * @return string
         */
-       function commaList( $list ) {
+       function commaList( array $list ) {
                return implode(
-                       $list,
                        wfMsgExt(
                                'comma-separator',
                                array( 'parsemag', 'escapenoentities', 'language' => $this )
-                       )
+                       ),
+                       $list
                );
        }
 
@@ -2719,13 +2926,13 @@ class Language {
         * @param $list array of strings to put in a semicolon list
         * @return string
         */
-       function semicolonList( $list ) {
+       function semicolonList( array $list ) {
                return implode(
-                       $list,
                        wfMsgExt(
                                'semicolon-separator',
                                array( 'parsemag', 'escapenoentities', 'language' => $this )
-                       )
+                       ),
+                       $list
                );
        }
 
@@ -2734,13 +2941,13 @@ class Language {
         * @param $list array of strings to put in a pipe list
         * @return string
         */
-       function pipeList( $list ) {
+       function pipeList( array $list ) {
                return implode(
-                       $list,
                        wfMsgExt(
                                'pipe-separator',
                                array( 'escapenoentities', 'language' => $this )
-                       )
+                       ),
+                       $list
                );
        }
 
@@ -2993,10 +3200,10 @@ class Language {
         * truncateHtml() helper function
         * (a) push or pop $tag from $openTags as needed
         * (b) clear $tag value
-        * @param String &$tag Current HTML tag name we are looking at
-        * @param int $tagType (0-open tag, 1-close tag)
-        * @param char $lastCh Character before the '>' that ended this tag
-        * @param array &$openTags Open tag stack (not accounting for $tag)
+        * @param &$tag string Current HTML tag name we are looking at
+        * @param $tagType int (0-open tag, 1-close tag)
+        * @param $lastCh string Character before the '>' that ended this tag
+        * @param &$openTags array Open tag stack (not accounting for $tag)
         */
        private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
                $tag = ltrim( $tag );
@@ -3033,8 +3240,14 @@ class Language {
         * Usage {{gender:username|masculine|feminine|neutral}}.
         * username is optional, in which case the gender of current user is used,
         * but only in (some) interface messages; otherwise default gender is used.
-        * If second or third parameter are not specified, masculine is used.
-        * These details may be overriden per language.
+        *
+        * If no forms are given, an empty string is returned. If only one form is
+        * given, it will be returned unconditionally. These details are implied by
+        * the caller and cannot be overridden in subclasses.
+        *
+        * If more than one form is given, the default is to use the neutral one
+        * if it is specified, and to use the masculine one otherwise. These
+        * details can be overridden in subclasses.
         *
         * @param $gender string
         * @param $forms array
@@ -3102,7 +3315,7 @@ class Language {
         * match up with it.
         *
         * @param $str String: the validated block duration in English
-        * @return Somehow translated block duration
+        * @return string Somehow translated block duration
         * @see LanguageFi.php for example implementation
         */
        function translateBlockExpiry( $str ) {
@@ -3135,7 +3348,7 @@ class Language {
         * @param $text String
         * @return String
         */
-       function segmentForDiff( $text ) {
+       public function segmentForDiff( $text ) {
                return $text;
        }
 
@@ -3145,17 +3358,27 @@ class Language {
         * @param $text String
         * @return String
         */
-       function unsegmentForDiff( $text ) {
+       public function unsegmentForDiff( $text ) {
                return $text;
        }
 
+       /**
+        * Return the LanguageConverter used in the Language
+        *
+        * @since 1.19
+        * @return LanguageConverter
+        */
+       public function getConverter() {
+               return $this->mConverter;
+       }
+
        /**
         * convert text to all supported variants
         *
         * @param $text string
         * @return array
         */
-       function autoConvertToAllVariants( $text ) {
+       public function autoConvertToAllVariants( $text ) {
                return $this->mConverter->autoConvertToAllVariants( $text );
        }
 
@@ -3165,18 +3388,17 @@ class Language {
         * @param $text string
         * @return string
         */
-       function convert( $text ) {
+       public function convert( $text ) {
                return $this->mConverter->convert( $text );
        }
 
-
        /**
         * Convert a Title object to a string in the preferred variant
         *
         * @param $title Title
         * @return string
         */
-       function convertTitle( $title ) {
+       public function convertTitle( $title ) {
                return $this->mConverter->convertTitle( $title );
        }
 
@@ -3185,17 +3407,28 @@ class Language {
         *
         * @return bool
         */
-       function hasVariants() {
+       public function hasVariants() {
                return sizeof( $this->getVariants() ) > 1;
        }
 
+       /**
+        * Check if the language has the specific variant
+        *
+        * @since 1.19
+        * @param $variant string
+        * @return bool
+        */
+       public function hasVariant( $variant ) {
+               return (bool)$this->mConverter->validateVariant( $variant );
+       }
+
        /**
         * Put custom tags (e.g. -{ }-) around math to prevent conversion
         *
         * @param $text string
         * @return string
         */
-       function armourMath( $text ) {
+       public function armourMath( $text ) {
                return $this->mConverter->armourMath( $text );
        }
 
@@ -3206,7 +3439,7 @@ class Language {
         * @return string
         * @todo this should get integrated somewhere sane
         */
-       function convertHtml( $text, $isTitle = false ) {
+       public function convertHtml( $text, $isTitle = false ) {
                return htmlspecialchars( $this->convert( $text, $isTitle ) );
        }
 
@@ -3214,7 +3447,7 @@ class Language {
         * @param $key string
         * @return string
         */
-       function convertCategoryKey( $key ) {
+       public function convertCategoryKey( $key ) {
                return $this->mConverter->convertCategoryKey( $key );
        }
 
@@ -3224,28 +3457,28 @@ class Language {
         *
         * @return array an array of language codes
         */
-       function getVariants() {
+       public function getVariants() {
                return $this->mConverter->getVariants();
        }
 
        /**
         * @return string
         */
-       function getPreferredVariant() {
+       public function getPreferredVariant() {
                return $this->mConverter->getPreferredVariant();
        }
 
        /**
         * @return string
         */
-       function getDefaultVariant() {
+       public function getDefaultVariant() {
                return $this->mConverter->getDefaultVariant();
        }
 
        /**
         * @return string
         */
-       function getURLVariant() {
+       public function getURLVariant() {
                return $this->mConverter->getURLVariant();
        }
 
@@ -3261,7 +3494,7 @@ class Language {
         *      we need to transclude a template or update a category's link
         * @return null the input parameters may be modified upon return
         */
-       function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
+       public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
                $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
        }
 
@@ -3276,7 +3509,7 @@ class Language {
         *
         * @return string
         */
-       function convertLinkToAllVariants( $text ) {
+       public function convertLinkToAllVariants( $text ) {
                return $this->mConverter->convertLinkToAllVariants( $text );
        }
 
@@ -3297,7 +3530,7 @@ class Language {
         *
         * @return string
         */
-       function getParsedTitle() {
+       public function getParsedTitle() {
                return $this->mConverter->getParsedTitle();
        }
 
@@ -3309,7 +3542,7 @@ class Language {
         * @param $noParse bool
         * @return string the tagged text
         */
-       function markNoConversion( $text, $noParse = false ) {
+       public function markNoConversion( $text, $noParse = false ) {
                return $this->mConverter->markNoConversion( $text, $noParse );
        }
 
@@ -3319,7 +3552,7 @@ class Language {
         *
         * @return string
         */
-       function linkTrail() {
+       public function linkTrail() {
                return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
        }
 
@@ -3335,15 +3568,30 @@ class Language {
         *
         * @return string
         */
-       function getCode() {
+       public function getCode() {
                return $this->mCode;
        }
 
+       /**
+        * Get the code in Bcp47 format which we can use
+        * inside of html lang="" tags.
+        * @since 1.19
+        * @return string
+        */
+       public function getHtmlCode() {
+               if ( is_null( $this->mHtmlCode ) ) {
+                       $this->mHtmlCode = wfBCP47( $this->getCode() );
+               }
+               return $this->mHtmlCode;
+       }
+
        /**
         * @param $code string
         */
-       function setCode( $code ) {
+       public function setCode( $code ) {
                $this->mCode = $code;
+               // Ensure we don't leave an incorrect html code lying around
+               $this->mHtmlCode = null;
        }
 
        /**
@@ -3351,9 +3599,10 @@ class Language {
         * @param $prefix string Prepend this to the filename
         * @param $code string Language code
         * @param $suffix string Append this to the filename
+        * @throws MWException
         * @return string $prefix . $mangledCode . $suffix
         */
-       static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
+       public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
                // Protect against path traversal
                if ( !Language::isValidCode( $code )
                        || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
@@ -3371,7 +3620,7 @@ class Language {
         * @param $suffix string Suffix after the language code
         * @return string Language code, or false if $prefix or $suffix isn't found
         */
-       static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
+       public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
                $m = null;
                preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
                        preg_quote( $suffix, '/' ) . '/', $filename, $m );
@@ -3385,16 +3634,18 @@ class Language {
         * @param $code string
         * @return string
         */
-       static function getMessagesFileName( $code ) {
+       public static function getMessagesFileName( $code ) {
                global $IP;
-               return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
+               $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
+               wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
+               return $file;
        }
 
        /**
         * @param $code string
         * @return string
         */
-       static function getClassFileName( $code ) {
+       public static function getClassFileName( $code ) {
                global $IP;
                return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
        }
@@ -3404,9 +3655,9 @@ class Language {
         *
         * @param $code string
         *
-        * @return false|string
+        * @return bool|string
         */
-       static function getFallbackFor( $code ) {
+       public static function getFallbackFor( $code ) {
                if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
                        return false;
                } else {
@@ -3423,7 +3674,7 @@ class Language {
         * @param $code string Language code
         * @return array
         */
-       static function getFallbacksFor( $code ) {
+       public static function getFallbacksFor( $code ) {
                if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
                        return array();
                } else {
@@ -3445,7 +3696,7 @@ class Language {
         *
         * @return array
         */
-       static function getMessagesFor( $code ) {
+       public static function getMessagesFor( $code ) {
                return self::getLocalisationCache()->getItem( $code, 'messages' );
        }
 
@@ -3457,7 +3708,7 @@ class Language {
         *
         * @return string
         */
-       static function getMessageFor( $key, $code ) {
+       public static function getMessageFor( $key, $code ) {
                return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
        }
 
@@ -3469,7 +3720,7 @@ class Language {
         * @param $code string Language code
         * @return array of message keys (strings)
         */
-       static function getMessageKeysFor( $code ) {
+       public static function getMessageKeysFor( $code ) {
                return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
        }
 
@@ -3527,6 +3778,8 @@ class Language {
        /**
         * Decode an expiry (block, protection, etc) which has come from the DB
         *
+        * @FIXME: why are we returnings DBMS-dependent strings???
+        *
         * @param $expiry String: Database expiry String
         * @param $format Bool|Int true to process using language functions, or TS_ constant
         *     to return the expiry in a given timestamp
@@ -3578,7 +3831,7 @@ class Language {
                        $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
                $daysMsg = wfMessage(
                        $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
-               
+
                if ( round( $seconds * 10 ) < 100 ) {
                        $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
                        $s = $secondsMsg->params( $s )->text();
@@ -3650,57 +3903,67 @@ class Language {
        }
 
        /**
+        * Format a bitrate for output, using an appropriate
+        * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
+        *
+        * This use base 1000. For base 1024 use formatSize(), for another base
+        * see formatComputingNumbers()
+        *
         * @param $bps int
         * @return string
         */
        function formatBitrate( $bps ) {
-               $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
-               if ( $bps <= 0 ) {
-                       return $this->formatNum( $bps ) . $units[0];
-               }
-               $unitIndex = floor( log10( $bps ) / 3 );
-               $mantissa = $bps / pow( 1000, $unitIndex );
-               if ( $mantissa < 10 ) {
-                       $mantissa = round( $mantissa, 1 );
-               } else {
-                       $mantissa = round( $mantissa );
-               }
-               return $this->formatNum( $mantissa ) . $units[$unitIndex];
+               return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
        }
 
        /**
-        * Format a size in bytes for output, using an appropriate
-        * unit (B, KB, MB or GB) according to the magnitude in question
-        *
-        * @param $size int Size to format
-        * @return string Plain text (not HTML)
+        * @param $size int Size of the unit
+        * @param $boundary int Size boundary (1000, or 1024 in most cases)
+        * @param $messageKey string Message key to be uesd
+        * @return string
         */
-       function formatSize( $size ) {
+       function formatComputingNumbers( $size, $boundary, $messageKey ) {
+               if ( $size <= 0 ) {
+                       return str_replace( '$1', $this->formatNum( $size ),
+                               $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
+                       );
+               }
+               $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
+               $index = 0;
+
+               $maxIndex = count( $sizes ) - 1;
+               while ( $size >= $boundary && $index < $maxIndex ) {
+                       $index++;
+                       $size /= $boundary;
+               }
+
                // For small sizes no decimal places necessary
                $round = 0;
-               if ( $size > 1024 ) {
-                       $size = $size / 1024;
-                       if ( $size > 1024 ) {
-                               $size = $size / 1024;
-                               // For MB and bigger two decimal places are smarter
-                               $round = 2;
-                               if ( $size > 1024 ) {
-                                       $size = $size / 1024;
-                                       $msg = 'size-gigabytes';
-                               } else {
-                                       $msg = 'size-megabytes';
-                               }
-                       } else {
-                               $msg = 'size-kilobytes';
-                       }
-               } else {
-                       $msg = 'size-bytes';
+               if ( $index > 1 ) {
+                       // For MB and bigger two decimal places are smarter
+                       $round = 2;
                }
+               $msg = str_replace( '$1', $sizes[$index], $messageKey );
+
                $size = round( $size, $round );
                $text = $this->getMessageFromDB( $msg );
                return str_replace( '$1', $this->formatNum( $size ), $text );
        }
 
+       /**
+        * Format a size in bytes for output, using an appropriate
+        * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
+        *
+        * This method use base 1024. For base 1000 use formatBitrate(), for
+        * another base see formatComputingNumbers()
+        *
+        * @param $size int Size to format
+        * @return string Plain text (not HTML)
+        */
+       function formatSize( $size ) {
+               return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
+       }
+
        /**
         * Make a list item, used by various special pages
         *
@@ -3733,7 +3996,7 @@ class Language {
 
                # Make 'previous' link
                $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
-               if( $offset > 0 ) {
+               if ( $offset > 0 ) {
                        $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
                                $query, $prev, 'prevn-title', 'mw-prevlink' );
                } else {
@@ -3742,7 +4005,7 @@ class Language {
 
                # Make 'next' link
                $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
-               if( $atend ) {
+               if ( $atend ) {
                        $nlink = htmlspecialchars( $next );
                } else {
                        $nlink = $this->numLink( $title, $offset + $limit, $limit,
@@ -3751,7 +4014,7 @@ class Language {
 
                # Make links to set number of items per page
                $numLinks = array();
-               foreach( array( 20, 50, 100, 250, 500 ) as $num ) {
+               foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
                        $numLinks[] = $this->numLink( $title, $offset, $num,
                                $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
                }
@@ -3784,7 +4047,7 @@ class Language {
         *
         * @return string
         */
-       function getConvRuleTitle() {
+       public function getConvRuleTitle() {
                return $this->mConverter->getConvRuleTitle();
        }
 }