Localisation updates for core and extension messages from translatewiki.net
[lhc/web/wiklou.git] / languages / Language.php
index ff91124..c313182 100644 (file)
@@ -53,8 +53,15 @@ class FakeConverter {
  * @ingroup Language
  */
 class Language {
-       var $mConverter, $mVariants, $mCode, $mLoaded = false;
+
+       /**
+        * @var LanguageConverter
+        */
+       var $mConverter;
+
+       var $mVariants, $mCode, $mLoaded = false;
        var $mMagicExtensions = array(), $mMagicHookDone = false;
+       private $mHtmlCode = null;
 
        var $mNamespaceIds, $namespaceNames, $namespaceAliases;
        var $dateFormatStrings = array();
@@ -148,72 +155,109 @@ class Language {
         * @return Language
         */
        protected static function newFromCode( $code ) {
-               global $IP;
-               static $recursionLevel = 0;
-
                // Protect against path traversal below
-               if ( !Language::isValidCode( $code ) 
-                       || strcspn( $code, ":/\\\000" ) !== strlen( $code ) ) 
+               if ( !Language::isValidCode( $code )
+                       || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
                {
                        throw new MWException( "Invalid language code \"$code\"" );
                }
 
                if ( !Language::isValidBuiltInCode( $code ) ) {
-                       // It's not possible to customise this code with class files, so 
+                       // It's not possible to customise this code with class files, so
                        // just return a Language object. This is to support uselang= hacks.
                        $lang = new Language;
                        $lang->setCode( $code );
                        return $lang;
                }
 
-               if ( $code == 'en' ) {
-                       $class = 'Language';
-               } else {
-                       $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
-                       if ( !defined( 'MW_COMPILED' ) ) {
-                               // Preload base classes to work around APC/PHP5 bug
-                               if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
-                                       include_once( "$IP/languages/classes/$class.deps.php" );
-                               }
-                               if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
-                                       include_once( "$IP/languages/classes/$class.php" );
-                               }
-                       }
+               // Check if there is a language class for the code
+               $class = self::classFromCode( $code );
+               self::preloadLanguageClass( $class );
+               if ( MWInit::classExists( $class ) ) {
+                       $lang = new $class;
+                       return $lang;
                }
 
-               if ( $recursionLevel > 5 ) {
-                       throw new MWException( "Language fallback loop detected when creating class $class\n" );
-               }
+               // Keep trying the fallback list until we find an existing class
+               $fallbacks = Language::getFallbacksFor( $code );
+               foreach ( $fallbacks as $fallbackCode ) {
+                       if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
+                               throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
+                       }
 
-               if ( !MWInit::classExists( $class ) ) {
-                       $fallback = Language::getFallbackFor( $code );
-                       ++$recursionLevel;
-                       $lang = Language::newFromCode( $fallback );
-                       --$recursionLevel;
-                       $lang->setCode( $code );
-               } else {
-                       $lang = new $class;
+                       $class = self::classFromCode( $fallbackCode );
+                       self::preloadLanguageClass( $class );
+                       if ( MWInit::classExists( $class ) ) {
+                               $lang = Language::newFromCode( $fallbackCode );
+                               $lang->setCode( $code );
+                               return $lang;
+                       }
                }
-               return $lang;
+
+               throw new MWException( "Invalid fallback sequence for language '$code'" );
        }
 
        /**
-        * Returns true if a language code string is of a valid form, whether or 
-        * not it exists. This includes codes which are used solely for 
+        * Returns true if a language code string is of a valid form, whether or
+        * not it exists. This includes codes which are used solely for
         * customisation via the MediaWiki namespace.
+        *
+        * @param $code string
+        *
+        * @return bool
         */
        public static function isValidCode( $code ) {
-               return 
+               return
                        strcspn( $code, ":/\\\000" ) === strlen( $code )
                        && !preg_match( Title::getTitleInvalidRegex(), $code );
        }
 
        /**
-        * Returns true if a language code is of a valid form for the purposes of 
+        * Returns true if a language code is of a valid form for the purposes of
         * internal customisation of MediaWiki, via Messages*.php.
+        *
+        * @param $code string
+        *
+        * @since 1.18
+        * @return bool
         */
        public static function isValidBuiltInCode( $code ) {
-               return preg_match( '/^[a-z0-9-]*$/i', $code );
+               return preg_match( '/^[a-z0-9-]+$/i', $code );
+       }
+
+       /**
+        * @param $code
+        * @return String Name of the language class
+        */
+       public static function classFromCode( $code ) {
+               if ( $code == 'en' ) {
+                       return 'Language';
+               } else {
+                       return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
+               }
+       }
+
+       /**
+        * Includes language class files
+        *
+        * @param $class string Name of the language class
+        */
+       public static function preloadLanguageClass( $class ) {
+               global $IP;
+
+               if ( $class === 'Language' ) {
+                       return;
+               }
+
+               if ( !defined( 'MW_COMPILED' ) ) {
+                       // Preload base classes to work around APC/PHP5 bug
+                       if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
+                               include_once( "$IP/languages/classes/$class.deps.php" );
+                       }
+                       if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
+                               include_once( "$IP/languages/classes/$class.php" );
+                       }
+               }
        }
 
        /**
@@ -256,12 +300,22 @@ class Language {
         */
        function initContLang() { }
 
+       /**
+        * Same as getFallbacksFor for current language.
+        * @return array|bool
+        * @deprecated in 1.19
+        */
        function getFallbackLanguageCode() {
-               if ( $this->mCode === 'en' ) {
-                       return false;
-               } else {
-                       return self::$dataCache->getItem( $this->mCode, 'fallback' );
-               }
+               wfDeprecated( __METHOD__ );
+               return self::getFallbackFor( $this->mCode );
+       }
+
+       /**
+        * @return array
+        * @since 1.19
+        */
+       function getFallbackLanguages() {
+               return self::getFallbacksFor( $this->mCode );
        }
 
        /**
@@ -294,7 +348,7 @@ class Language {
                        }
 
                        # Sometimes a language will be localised but not actually exist on this wiki.
-                       foreach( $this->namespaceNames as $key => $text ) {
+                       foreach ( $this->namespaceNames as $key => $text ) {
                                if ( !isset( $validNamespaces[$key] ) ) {
                                        unset( $this->namespaceNames[$key] );
                                }
@@ -303,6 +357,8 @@ class Language {
                        # The above mixing may leave namespaces out of canonical order.
                        # Re-order by namespace ID number...
                        ksort( $this->namespaceNames );
+
+                       wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
                }
                return $this->namespaceNames;
        }
@@ -343,6 +399,8 @@ class Language {
         * getNsText() except with '_' changed to ' ', useful for
         * producing output.
         *
+        * @param $index string
+        *
         * @return array
         */
        function getFormattedNsText( $index ) {
@@ -358,7 +416,9 @@ class Language {
         * @since 1.18
         */
        function getGenderNsText( $index, $gender ) {
-               $ns = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+               global $wgExtraGenderNamespaces;
+
+               $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
                return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
        }
 
@@ -369,8 +429,19 @@ class Language {
         * @since 1.18
         */
        function needsGenderDistinction() {
-               $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
-               return count( $aliases ) > 0;
+               global $wgExtraGenderNamespaces, $wgExtraNamespaces;
+               if ( count( $wgExtraGenderNamespaces ) > 0 ) {
+                       // $wgExtraGenderNamespaces overrides everything
+                       return true;
+               } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
+                       /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
+                       // $wgExtraNamespaces overrides any gender aliases specified in i18n files
+                       return false;
+               } else {
+                       // Check what is in i18n files
+                       $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+                       return count( $aliases ) > 0;
+               }
        }
 
        /**
@@ -387,6 +458,9 @@ class Language {
                return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
        }
 
+       /**
+        * @return array
+        */
        function getNamespaceAliases() {
                if ( is_null( $this->namespaceAliases ) ) {
                        $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
@@ -402,7 +476,8 @@ class Language {
                                }
                        }
 
-                       $genders = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+                       global $wgExtraGenderNamespaces;
+                       $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
                        foreach ( $genders as $index => $forms ) {
                                foreach ( $forms as $alias ) {
                                        $aliases[$alias] = $index;
@@ -414,6 +489,9 @@ class Language {
                return $this->namespaceAliases;
        }
 
+       /**
+        * @return array
+        */
        function getNamespaceIds() {
                if ( is_null( $this->mNamespaceIds ) ) {
                        global $wgNamespaceAliases;
@@ -437,7 +515,6 @@ class Language {
                return $this->mNamespaceIds;
        }
 
-
        /**
         * Get a namespace key by value, case insensitive.  Canonical namespace
         * names override custom ones defined for the current language.
@@ -447,7 +524,8 @@ class Language {
         */
        function getNsIndex( $text ) {
                $lctext = $this->lc( $text );
-               if ( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) {
+               $ns = MWNamespace::getCanonicalIndex( $lctext );
+               if ( $ns !== null ) {
                        return $ns;
                }
                $ids = $this->getNamespaceIds();
@@ -458,12 +536,28 @@ class Language {
         * short names for language variants used for language conversion links.
         *
         * @param $code String
+        * @param $usemsg bool Use the "variantname-xyz" message if it exists
         * @return string
         */
-       function getVariantname( $code ) {
-               return $this->getMessageFromDB( "variantname-$code" );
+       function getVariantname( $code, $usemsg = true ) {
+               $msg = "variantname-$code";
+               list( $rootCode ) = explode( '-', $code );
+               if ( $usemsg && wfMessage( $msg )->exists() ) {
+                       return $this->getMessageFromDB( $msg );
+               }
+               $name = self::getLanguageName( $code );
+               if ( $name ) {
+                       return $name; # if it's defined as a language name, show that
+               } else {
+                       # otherwise, output the language code
+                       return $code;
+               }
        }
 
+       /**
+        * @param $name string
+        * @return string
+        */
        function specialPage( $name ) {
                $aliases = $this->getSpecialPageAliases();
                if ( isset( $aliases[$name][0] ) ) {
@@ -472,24 +566,37 @@ class Language {
                return $this->getNsText( NS_SPECIAL ) . ':' . $name;
        }
 
+       /**
+        * @return array
+        */
        function getQuickbarSettings() {
                return array(
                        $this->getMessage( 'qbsettings-none' ),
                        $this->getMessage( 'qbsettings-fixedleft' ),
                        $this->getMessage( 'qbsettings-fixedright' ),
                        $this->getMessage( 'qbsettings-floatingleft' ),
-                       $this->getMessage( 'qbsettings-floatingright' )
+                       $this->getMessage( 'qbsettings-floatingright' ),
+                       $this->getMessage( 'qbsettings-directionality' )
                );
        }
 
+       /**
+        * @return array
+        */
        function getDatePreferences() {
                return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
        }
 
+       /**
+        * @return array
+        */
        function getDateFormats() {
                return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
        }
 
+       /**
+        * @return array|string
+        */
        function getDefaultDateFormat() {
                $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
                if ( $df === 'dmy or mdy' ) {
@@ -500,29 +607,44 @@ class Language {
                }
        }
 
+       /**
+        * @return array
+        */
        function getDatePreferenceMigrationMap() {
                return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
        }
 
+       /**
+        * @param  $image
+        * @return array|null
+        */
        function getImageFile( $image ) {
                return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
        }
 
-       function getDefaultUserOptionOverrides() {
-               return self::$dataCache->getItem( $this->mCode, 'defaultUserOptionOverrides' );
-       }
-
+       /**
+        * @return array
+        */
        function getExtraUserToggles() {
-               return self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
+               return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
        }
 
+       /**
+        * @param  $tog
+        * @return string
+        */
        function getUserToggle( $tog ) {
                return $this->getMessageFromDB( "tog-$tog" );
        }
 
        /**
-        * 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
         */
        public static function getLanguageNames( $customisedOnly = false ) {
                global $wgExtraLanguageNames;
@@ -537,16 +659,14 @@ class Language {
                        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] ) ) {
+               // We do this using a foreach over the codes instead of a directory
+               // loop so that messages files in extensions will work correctly.
+               foreach ( $allNames as $code => $value ) {
+                       if ( is_readable( self::getMessagesFileName( $code ) ) ) {
                                $names[$code] = $allNames[$code];
                        }
                }
-               closedir( $dir );
                return $names;
        }
 
@@ -579,6 +699,12 @@ class Language {
                return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
        }
 
+       /**
+        * Get the native language name of $code.
+        * Only if defined in MediaWiki, no other data like CLDR.
+        * @param $code string
+        * @return string
+        */
        function getLanguageName( $code ) {
                $names = self::getLanguageNames();
                if ( !array_key_exists( $code, $names ) ) {
@@ -587,129 +713,98 @@ class Language {
                return $names[$code];
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getMonthName( $key ) {
                return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
        }
-       
+
+       /**
+        * @return array
+        */
        function getMonthNamesArray() {
                $monthNames = array( '' );
-               for ( $i=1; $i < 13; $i++ ) { 
+               for ( $i = 1; $i < 13; $i++ ) {
                        $monthNames[] = $this->getMonthName( $i );
                }
                return $monthNames;
        }
-       
+
+       /**
+        * @param $key string
+        * @return string
+        */
        function getMonthNameGen( $key ) {
                return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getMonthAbbreviation( $key ) {
                return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
        }
-       
+
+       /**
+        * @return array
+        */
        function getMonthAbbreviationsArray() {
-               $monthNames = array('');
-               for ( $i=1; $i < 13; $i++ ) { 
+               $monthNames = array( '' );
+               for ( $i = 1; $i < 13; $i++ ) {
                        $monthNames[] = $this->getMonthAbbreviation( $i );
                }
                return $monthNames;
        }
-       
+
+       /**
+        * @param $key string
+        * @return string
+        */
        function getWeekdayName( $key ) {
                return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getWeekdayAbbreviation( $key ) {
                return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getIranianCalendarMonthName( $key ) {
                return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getHebrewCalendarMonthName( $key ) {
                return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
        }
 
+       /**
+        * @param $key string
+        * @return string
+        */
        function getHebrewCalendarMonthNameGen( $key ) {
                return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
        }
 
-       function getHijriCalendarMonthName( $key ) {
-               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
+        * @param $key string
+        * @return string
         */
-       function userAdjust( $ts, $tz = false ) {
-               global $wgUser, $wgLocalTZoffset;
-
-               if ( $tz === false ) {
-                       $tz = $wgUser->getOption( 'timecorrection' );
-               }
-
-               $data = explode( '|', $tz, 3 );
-
-               if ( $data[0] == 'ZoneInfo' ) {
-                       if ( function_exists( 'timezone_open' ) && @timezone_open( $data[2] ) !== false ) {
-                               $date = date_create( $ts, timezone_open( 'UTC' ) );
-                               date_timezone_set( $date, timezone_open( $data[2] ) );
-                               $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;
-                       }
-               } else if ( $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;
+       function getHijriCalendarMonthName( $key ) {
+               return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
        }
 
        /**
@@ -731,6 +826,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
@@ -770,6 +866,8 @@ class Language {
         *      YYYYMMDDHHMMSS
         *      01234567890123
         * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
+        *
+        * @return string
         */
        function sprintfDate( $format, $ts ) {
                $s = '';
@@ -991,6 +1089,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;
@@ -1082,6 +1186,7 @@ class Language {
 
        private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
        private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
+
        /**
         * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
         * Gregorian dates to Iranian dates. Originally written in C, it
@@ -1089,11 +1194,15 @@ class Language {
         * License. Conversion to PHP was performed by Niklas Laxström.
         *
         * Link: http://www.farsiweb.info/jalali/jalali.c
+        *
+        * @param $ts string
+        *
+        * @return string
         */
        private static function tsToIranian( $ts ) {
                $gy = substr( $ts, 0, 4 ) -1600;
                $gm = substr( $ts, 4, 2 ) -1;
-               $gd = (int)substr( $ts, 6, 2 ) -1;
+               $gd = substr( $ts, 6, 2 ) -1;
 
                # Days passed from the beginning (including leap years)
                $gDayNo = 365 * $gy
@@ -1101,7 +1210,6 @@ class Language {
                        - floor( ( $gy + 99 ) / 100 )
                        + floor( ( $gy + 399 ) / 400 );
 
-
                // Add days of the past months of this year
                for ( $i = 0; $i < $gm; $i++ ) {
                        $gDayNo += self::$GREG_DAYS[$i];
@@ -1113,7 +1221,7 @@ class Language {
                }
 
                // Days passed in current month
-               $gDayNo += $gd;
+               $gDayNo += (int)$gd;
 
                $jDayNo = $gDayNo - 79;
 
@@ -1144,6 +1252,10 @@ 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
+        *
+        * @param $ts string
+        *
+        * @return string
         */
        private static function tsToHijri( $ts ) {
                $year = substr( $ts, 0, 4 );
@@ -1191,6 +1303,10 @@ class Language {
         *
         * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
         * and Adar II is 14. In a non-leap year, Adar is 6.
+        *
+        * @param $ts string
+        *
+        * @return string
         */
        private static function tsToHebrew( $ts ) {
                # Parse date
@@ -1328,6 +1444,10 @@ class Language {
         * This calculates the Hebrew year start, as days since 1 September.
         * Based on Carl Friedrich Gauss algorithm for finding Easter date.
         * Used for Hebrew date.
+        *
+        * @param $year int
+        *
+        * @return string
         */
        private static function hebrewYearStart( $year ) {
                $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
@@ -1345,9 +1465,9 @@ class Language {
                $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
                if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
                        $Mar++;
-               } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
+               } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
                        $Mar += 2;
-               } else if ( $c == 2 || $c == 4 || $c == 6 ) {
+               } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
                        $Mar++;
                }
 
@@ -1377,12 +1497,12 @@ class Language {
                        # Add 543 years to the Gregorian calendar
                        # Months and days are identical
                        $gy_offset = $gy + 543;
-               } else if ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
+               } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
                        # Minguo dates
                        # Deduct 1911 years from the Gregorian calendar
                        # Months and days are identical
                        $gy_offset = $gy - 1911;
-               } else if ( !strcmp( $cName, 'tenno' ) ) {
+               } elseif ( !strcmp( $cName, 'tenno' ) ) {
                        # Nengō dates up to Meiji period
                        # Deduct years from the Gregorian calendar
                        # depending on the nengo periods
@@ -1395,7 +1515,7 @@ class Language {
                                        $gy_offset = '元';
                                }
                                $gy_offset = '明治' . $gy_offset;
-                       } else if (
+                       } elseif (
                                ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
                                ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
                                ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
@@ -1410,7 +1530,7 @@ class Language {
                                        $gy_offset = '元';
                                }
                                $gy_offset = '大正' . $gy_offset;
-                       } else if (
+                       } elseif (
                                ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
                                ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
                                ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
@@ -1441,6 +1561,10 @@ class Language {
 
        /**
         * Roman number formatting up to 3000
+        *
+        * @param $num int
+        *
+        * @return string
         */
        static function romanNumeral( $num ) {
                static $table = array(
@@ -1458,7 +1582,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;
                }
@@ -1467,6 +1591,10 @@ class Language {
 
        /**
         * Hebrew Gematria number formatting up to 9999
+        *
+        * @param $num int
+        *
+        * @return string
         */
        static function hebrewNumeral( $num ) {
                static $table = array(
@@ -1524,6 +1652,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
@@ -1564,8 +1768,10 @@ class Language {
 
        /**
         * Get a format string for a given type and preference
-        * @param $type May be date, time or both
-        * @param $pref The format name as it appears in Messages*.php
+        * @param $type string May be date, time or both
+        * @param $pref string The format name as it appears in Messages*.php
+        *
+        * @return string
         */
        function getDateFormatString( $type, $pref ) {
                if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
@@ -1590,7 +1796,7 @@ class Language {
         * @param $adj Bool: whether to adjust the time output according to the
         *             user configured offset ($timecorrection)
         * @param $format Mixed: true to use user's date format preference
-        * @param $timecorrection String: the time offset as returned by
+        * @param $timecorrection String|bool the time offset as returned by
         *                        validateTimeZone() in Special:Preferences
         * @return string
         */
@@ -1609,7 +1815,7 @@ class Language {
         * @param $adj Bool: whether to adjust the time output according to the
         *             user configured offset ($timecorrection)
         * @param $format Mixed: true to use user's date format preference
-        * @param $timecorrection String: the time offset as returned by
+        * @param $timecorrection String|bool the time offset as returned by
         *                        validateTimeZone() in Special:Preferences
         * @return string
         */
@@ -1629,7 +1835,7 @@ class Language {
         *             user configured offset ($timecorrection)
         * @param $format Mixed: what format to return, if it's false output the
         *                default one (default true)
-        * @param $timecorrection String: the time offset as returned by
+        * @param $timecorrection String|bool the time offset as returned by
         *                        validateTimeZone() in Special:Preferences
         * @return string
         */
@@ -1642,14 +1848,135 @@ 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
+        */
        function getMessage( $key ) {
                return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
        }
 
+       /**
+        * @return array
+        */
        function getAllMessages() {
                return self::$dataCache->getItem( $this->mCode, 'messages' );
        }
 
+       /**
+        * @param $in
+        * @param $out
+        * @param $string
+        * @return string
+        */
        function iconv( $in, $out, $string ) {
                # This is a wrapper for iconv in all languages except esperanto,
                # which does some nasty x-conversions beforehand
@@ -1665,28 +1992,53 @@ class Language {
        }
 
        // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
+
+       /**
+        * @param $matches array
+        * @return mixed|string
+        */
        function ucwordbreaksCallbackAscii( $matches ) {
                return $this->ucfirst( $matches[1] );
        }
 
+       /**
+        * @param $matches array
+        * @return string
+        */
        function ucwordbreaksCallbackMB( $matches ) {
                return mb_strtoupper( $matches[0] );
        }
 
+       /**
+        * @param $matches array
+        * @return string
+        */
        function ucCallback( $matches ) {
                list( $wikiUpperChars ) = self::getCaseMaps();
                return strtr( $matches[1], $wikiUpperChars );
        }
 
+       /**
+        * @param $matches array
+        * @return string
+        */
        function lcCallback( $matches ) {
                list( , $wikiLowerChars ) = self::getCaseMaps();
                return strtr( $matches[1], $wikiLowerChars );
        }
 
+       /**
+        * @param $matches array
+        * @return string
+        */
        function ucwordsCallbackMB( $matches ) {
                return mb_strtoupper( $matches[0] );
        }
 
+       /**
+        * @param $matches array
+        * @return string
+        */
        function ucwordsCallbackWiki( $matches ) {
                list( $wikiUpperChars ) = self::getCaseMaps();
                return strtr( $matches[0], $wikiUpperChars );
@@ -1694,6 +2046,10 @@ class Language {
 
        /**
         * Make a string's first character uppercase
+        *
+        * @param $str string
+        *
+        * @return string
         */
        function ucfirst( $str ) {
                $o = ord( $str );
@@ -1709,6 +2065,11 @@ class Language {
 
        /**
         * Convert a string to uppercase
+        *
+        * @param $str string
+        * @param $first bool
+        *
+        * @return string
         */
        function uc( $str, $first = false ) {
                if ( function_exists( 'mb_strtoupper' ) ) {
@@ -1735,6 +2096,10 @@ class Language {
                }
        }
 
+       /**
+        * @param $str string
+        * @return mixed|string
+        */
        function lcfirst( $str ) {
                $o = ord( $str );
                if ( !$o ) {
@@ -1749,6 +2114,11 @@ class Language {
                }
        }
 
+       /**
+        * @param $str string
+        * @param $first bool
+        * @return mixed|string
+        */
        function lc( $str, $first = false ) {
                if ( function_exists( 'mb_strtolower' ) ) {
                        if ( $first ) {
@@ -1774,10 +2144,18 @@ class Language {
                }
        }
 
+       /**
+        * @param $str string
+        * @return bool
+        */
        function isMultibyte( $str ) {
                return (bool)preg_match( '/[\x80-\xff]/', $str );
        }
 
+       /**
+        * @param $str string
+        * @return mixed|string
+        */
        function ucwords( $str ) {
                if ( $this->isMultibyte( $str ) ) {
                        $str = $this->lc( $str );
@@ -1804,7 +2182,12 @@ class Language {
                }
        }
 
-       # capitalize words at word breaks
+       /**
+        * capitalize words at word breaks
+        *
+        * @param $str string
+        * @return mixed
+        */
        function ucwordbreaks( $str ) {
                if ( $this->isMultibyte( $str ) ) {
                        $str = $this->lc( $str );
@@ -1847,11 +2230,19 @@ class Language {
         * Do *not* perform any other normalisation in this function. If a caller
         * uses this function when it should be using a more general normalisation
         * function, then fix the caller.
+        *
+        * @param $s string
+        *
+        * @return string
         */
        function caseFold( $s ) {
                return $this->uc( $s );
        }
 
+       /**
+        * @param $s string
+        * @return string
+        */
        function checkTitleEncoding( $s ) {
                if ( is_array( $s ) ) {
                        wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
@@ -1871,6 +2262,9 @@ class Language {
                return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
        }
 
+       /**
+        * @return array
+        */
        function fallback8bitEncoding() {
                return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
        }
@@ -1880,6 +2274,8 @@ class Language {
         * Some languages such as Chinese don't conventionally do this,
         * which requires special handling when breaking up words for
         * searching etc.
+        *
+        * @return bool
         */
        function hasWordBreaks() {
                return true;
@@ -1910,6 +2306,10 @@ class Language {
        /**
         * convert double-width roman characters to single-width.
         * range: ff00-ff5f ~= 0020-007f
+        *
+        * @param $string string
+        *
+        * @return string
         */
        protected static function convertDoubleWidth( $string ) {
                static $full = null;
@@ -1926,12 +2326,21 @@ class Language {
                return $string;
        }
 
+       /**
+        * @param $string string
+        * @param $pattern string
+        * @return string
+        */
        protected static function insertSpace( $string, $pattern ) {
                $string = preg_replace( $pattern, " $1 ", $string );
                $string = preg_replace( '/ +/', ' ', $string );
                return $string;
        }
 
+       /**
+        * @param $termsArray array
+        * @return array
+        */
        function convertForSearchResult( $termsArray ) {
                # some languages, e.g. Chinese, need to do a conversion
                # in order for search results to be displayed correctly
@@ -2003,13 +2412,14 @@ class Language {
                # an override to the defaults can be set here on startup.
        }
 
+       /**
+        * @param $s string
+        * @return string
+        */
        function recodeForEdit( $s ) {
                # For some languages we'll want to explicitly specify
                # which characters make it into the edit box raw
                # or are converted in some way or another.
-               # Note that if wgOutputEncoding is different from
-               # wgInputEncoding, this text will be further converted
-               # to wgOutputEncoding.
                global $wgEditEncoding;
                if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
                        return $s;
@@ -2018,6 +2428,10 @@ class Language {
                }
        }
 
+       /**
+        * @param $s string
+        * @return string
+        */
        function recodeInput( $s ) {
                # Take the previous into account.
                global $wgEditEncoding;
@@ -2039,6 +2453,10 @@ class Language {
         * to the modern Unicode equivalent.
         *
         * This is language-specific for performance reasons only.
+        *
+        * @param $s string
+        *
+        * @return string
         */
        function normalize( $s ) {
                global $wgAllUnicodeFixes;
@@ -2058,6 +2476,11 @@ class Language {
         *
         * The data is cached in process memory. This will go faster if you have the
         * FastStringSearch extension.
+        *
+        * @param $file string
+        * @param $string string
+        *
+        * @return string
         */
        function transformUsingPairFile( $file, $string ) {
                if ( !isset( $this->transformData[$file] ) ) {
@@ -2114,12 +2537,19 @@ class Language {
        /**
         * A hidden direction mark (LRM or RLM), depending on the language direction
         *
+        * @param $opposite Boolean Get the direction mark opposite to your language
         * @return string
         */
-       function getDirMark() {
-               return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
+       function getDirMark( $opposite = false ) {
+               $rtl = "\xE2\x80\x8F";
+               $ltr = "\xE2\x80\x8E";
+               if ( $opposite ) { return $this->isRTL() ? $ltr : $rtl; }
+               return $this->isRTL() ? $rtl : $ltr;
        }
 
+       /**
+        * @return array
+        */
        function capitalizeAllNouns() {
                return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
        }
@@ -2142,6 +2572,9 @@ class Language {
                return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
        }
 
+       /**
+        * @return array
+        */
        function getMagicWords() {
                return self::$dataCache->getItem( $this->mCode, 'magicWords' );
        }
@@ -2156,7 +2589,11 @@ class Language {
                wfProfileOut( 'LanguageGetMagic' );
        }
 
-       # Fill a MagicWord object with data from here
+       /**
+        * Fill a MagicWord object with data from here
+        *
+        * @param $mw
+        */
        function getMagic( $mw ) {
                $this->doMagicHook();
 
@@ -2172,7 +2609,7 @@ class Language {
                }
 
                if ( !is_array( $rawEntry ) ) {
-                       error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
+                       error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
                } else {
                        $mw->mCaseSensitive = $rawEntry[0];
                        $mw->mSynonyms = array_slice( $rawEntry, 1 );
@@ -2181,17 +2618,11 @@ class Language {
 
        /**
         * Add magic words to the extension array
+        *
+        * @param $newWords array
         */
        function addMagicWordsByLang( $newWords ) {
-               $code = $this->getCode();
-               $fallbackChain = array();
-               while ( $code && !in_array( $code, $fallbackChain ) ) {
-                       $fallbackChain[] = $code;
-                       $code = self::getFallbackFor( $code );
-               }
-               if ( !in_array( 'en', $fallbackChain ) ) {
-                       $fallbackChain[] = 'en';
-               }
+               $fallbackChain = $this->getFallbackLanguages();
                $fallbackChain = array_reverse( $fallbackChain );
                foreach ( $fallbackChain as $code ) {
                        if ( isset( $newWords[$code] ) ) {
@@ -2230,7 +2661,7 @@ class Language {
         /**
          * Normally we output all numbers in plain en_US style, that is
          * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
-         * point twohundredthirtyfive. However this is not sutable for all
+         * point twohundredthirtyfive. However this is not suitable for all
          * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
          * Icelandic just want to use commas instead of dots, and dots instead
          * of commas like "293.291,235".
@@ -2251,7 +2682,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 );
@@ -2271,6 +2702,10 @@ class Language {
                return $number;
        }
 
+       /**
+        * @param $number string
+        * @return string
+        */
        function parseFormattedNumber( $number ) {
                $s = $this->digitTransformTable();
                if ( $s ) {
@@ -2288,18 +2723,72 @@ class Language {
 
        /**
         * Adds commas to a given number
-        *
+        * @since 1.19
         * @param $_ mixed
         * @return string
         */
        function commafy( $_ ) {
-               return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
+               $digitGroupingPattern = $this->digitGroupingPattern();
+
+               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 );
+                       preg_match( "/\d+/", $_, $numberpart );
+                       preg_match( "/\.\d*/", $_, $decimalpart );
+                       $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
+                       if ( $groupedNumber  === $_ ) {
+                               // the string does not have any number part. Eg: .12345
+                               return $sign . $groupedNumber;
+                       }
+                       $start = $end = strlen( $numberpart[0] );
+                       while ( $start > 0 ) {
+                               $match = $matches[0][$numMatches -1] ;
+                               $matchLen = strlen( $match );
+                               $start = $end - $matchLen;
+                               if ( $start < 0 ) {
+                                       $start = 0;
+                               }
+                               $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
+                               $end = $start;
+                               if ( $numMatches > 1 ) {
+                                       // use the last pattern for the rest of the number
+                                       $numMatches--;
+                               }
+                               if ( $start > 0 ) {
+                                       $groupedNumber = "," . $groupedNumber;
+                               }
+                       }
+                       return $sign . $groupedNumber;
+               }
+       }
+       /**
+        * @return String
+        */
+       function digitGroupingPattern() {
+               return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
        }
 
+       /**
+        * @return array
+        */
        function digitTransformTable() {
                return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
        }
 
+       /**
+        * @return array
+        */
        function separatorTransformTable() {
                return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
        }
@@ -2312,7 +2801,7 @@ class Language {
         * @param $l Array
         * @return string
         */
-       function listToText( $l ) {
+       function listToText( array $l ) {
                $s = '';
                $m = count( $l ) - 1;
                if ( $m == 1 ) {
@@ -2321,7 +2810,7 @@ class Language {
                        for ( $i = $m; $i >= 0; $i-- ) {
                                if ( $i == $m ) {
                                        $s = $l[$i];
-                               } else if ( $i == $m - 1 ) {
+                               } elseif ( $i == $m - 1 ) {
                                        $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
                                } else {
                                        $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
@@ -2337,13 +2826,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
                );
        }
 
@@ -2353,13 +2842,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
                );
        }
 
@@ -2368,13 +2857,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
                );
        }
 
@@ -2427,7 +2916,7 @@ class Language {
                }
                # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
                # This check is *not* redundant if $adjustLength, due to the single case where
-               # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string. 
+               # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
                if ( strlen( $string ) < strlen( $stringOriginal ) ) {
                        return $string;
                } else {
@@ -2478,7 +2967,7 @@ class Language {
                return $string;
        }
 
-       /*
+       /**
         * Truncate a string of valid HTML to a specified length in bytes,
         * appending an optional string (e.g. for ellipses), and return valid HTML
         *
@@ -2491,7 +2980,7 @@ class Language {
         * @param string $text HTML string to truncate
         * @param int $length (zero/positive) Maximum length (including ellipses)
         * @param string $ellipsis String to append to the truncated text
-        * @returns string
+        * @return string
         */
        function truncateHtml( $text, $length, $ellipsis = '...' ) {
                # Use the localized ellipsis character
@@ -2505,31 +2994,33 @@ class Language {
                        return $text; // string short enough even *with* HTML (short-circuit)
                }
 
-               $displayLen = 0; // innerHTML legth so far
+               $dispLen = 0; // innerHTML legth so far
                $testingEllipsis = false; // checking if ellipses will make string longer/equal?
                $tagType = 0; // 0-open, 1-close
                $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
                $entityState = 0; // 0-not entity, 1-entity
-               $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
+               $tag = $ret = ''; // accumulated tag name, accumulated result string
                $openTags = array(); // open tag stack
-               $pOpenTags = array();
+               $maybeState = null; // possible truncation state
 
                $textLen = strlen( $text );
                $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
                for ( $pos = 0; true; ++$pos ) {
                        # Consider truncation once the display length has reached the maximim.
+                       # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
                        # Check that we're not in the middle of a bracket/entity...
-                       if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
+                       if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
                                if ( !$testingEllipsis ) {
                                        $testingEllipsis = true;
                                        # Save where we are; we will truncate here unless there turn out to
                                        # be so few remaining characters that truncation is not necessary.
-                                       $pOpenTags = $openTags; // save state
-                                       $pRet = $ret; // save state
-                               } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
+                                       if ( !$maybeState ) { // already saved? ($neLength = 0 case)
+                                               $maybeState = array( $ret, $openTags ); // save state
+                                       }
+                               } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
                                        # String in fact does need truncation, the truncation point was OK.
-                                       $openTags = $pOpenTags; // reload state
-                                       $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
+                                       list( $ret, $openTags ) = $maybeState; // reload state
+                                       $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
                                        $ret .= $ellipsis; // add ellipsis
                                        break;
                                }
@@ -2567,25 +3058,27 @@ class Language {
                                if ( $entityState ) {
                                        if ( $ch == ';' ) {
                                                $entityState = 0;
-                                               $displayLen++; // entity is one displayed char
+                                               $dispLen++; // entity is one displayed char
                                        }
                                } else {
+                                       if ( $neLength == 0 && !$maybeState ) {
+                                               // Save state without $ch. We want to *hit* the first
+                                               // display char (to get tags) but not *use* it if truncating.
+                                               $maybeState = array( substr( $ret, 0, -1 ), $openTags );
+                                       }
                                        if ( $ch == '&' ) {
                                                $entityState = 1; // entity found, (e.g. "&#160;")
                                        } else {
-                                               $displayLen++; // this char is displayed
+                                               $dispLen++; // this char is displayed
                                                // Add the next $max display text chars after this in one swoop...
-                                               $max = ( $testingEllipsis ? $length : $neLength ) - $displayLen;
+                                               $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
                                                $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
-                                               $displayLen += $skipped;
+                                               $dispLen += $skipped;
                                                $pos += $skipped;
                                        }
                                }
                        }
                }
-               if ( $displayLen == 0 ) {
-                       return ''; // no text shown, nothing to format
-               }
                // Close the last tag if left unclosed by bad HTML
                $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
                while ( count( $openTags ) > 0 ) {
@@ -2594,8 +3087,17 @@ class Language {
                return $ret;
        }
 
-       // truncateHtml() helper function
-       // like strcspn() but adds the skipped chars to $ret
+       /**
+        * truncateHtml() helper function
+        * like strcspn() but adds the skipped chars to $ret
+        *
+        * @param $ret
+        * @param $text
+        * @param $search
+        * @param $start
+        * @param $len
+        * @return int
+        */
        private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
                if ( $len === null ) {
                        $len = -1; // -1 means "no limit" for strcspn
@@ -2610,21 +3112,21 @@ class Language {
                return $skipCount;
        }
 
-       /*
+       /**
         * 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 char|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 );
                if ( $tag != '' ) {
                        if ( $tagType == 0 && $lastCh != '/' ) {
                                $openTags[] = $tag; // tag opened (didn't close itself)
-                       } else if ( $tagType == 1 ) {
+                       } elseif ( $tagType == 1 ) {
                                if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
                                        array_pop( $openTags ); // tag closed
                                }
@@ -2656,6 +3158,11 @@ class Language {
         * 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.
+        *
+        * @param $gender string
+        * @param $forms array
+        *
+        * @return string
         */
        function gender( $gender, $forms ) {
                if ( !count( $forms ) ) {
@@ -2711,16 +3218,19 @@ class Language {
        }
 
        /**
-        * Maybe translate block durations.  Note that this function is somewhat misnamed: it
+        * @todo Maybe translate block durations.  Note that this function is somewhat misnamed: it
         * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
-        * (which is an absolute timestamp).
+        * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
+        * on old expiry lengths recorded in log entries. You'd need to provide the start date to
+        * match up with it.
+        *
         * @param $str String: the validated block duration in English
         * @return Somehow translated block duration
         * @see LanguageFi.php for example implementation
         */
        function translateBlockExpiry( $str ) {
                $duration = SpecialBlock::getSuggestedDurations( $this );
-               foreach( $duration as $show => $value ){
+               foreach ( $duration as $show => $value ) {
                        if ( strcmp( $str, $value ) == 0 ) {
                                return htmlspecialchars( trim( $show ) );
                        }
@@ -2730,7 +3240,7 @@ class Language {
                // equivalents if still here.
                $indefs = array( 'infinite', 'infinity', 'indefinite' );
                if ( in_array( $str, $indefs ) ) {
-                       foreach( $indefs as $val ) {
+                       foreach ( $indefs as $val ) {
                                $show = array_search( $val, $duration, true );
                                if ( $show !== false ) {
                                        return htmlspecialchars( trim( $show ) );
@@ -2748,7 +3258,7 @@ class Language {
         * @param $text String
         * @return String
         */
-       function segmentForDiff( $text ) {
+       public function segmentForDiff( $text ) {
                return $text;
        }
 
@@ -2758,32 +3268,73 @@ class Language {
         * @param $text String
         * @return String
         */
-       function unsegmentForDiff( $text ) {
+       public function unsegmentForDiff( $text ) {
                return $text;
        }
 
-       # convert text to all supported variants
-       function autoConvertToAllVariants( $text ) {
+       /**
+        * Return the LanguageConverter used in the Language
+        * @return LanguageConverter
+        */
+       public function getConverter() {
+               return $this->mConverter;
+       }
+
+       /**
+        * convert text to all supported variants
+        *
+        * @param $text string
+        * @return array
+        */
+       public function autoConvertToAllVariants( $text ) {
                return $this->mConverter->autoConvertToAllVariants( $text );
        }
 
-       # convert text to different variants of a language.
-       function convert( $text ) {
+       /**
+        * convert text to different variants of a language.
+        *
+        * @param $text string
+        * @return string
+        */
+       public function convert( $text ) {
                return $this->mConverter->convert( $text );
        }
 
-       # Convert a Title object to a string in the preferred variant
-       function convertTitle( $title ) {
+       /**
+        * Convert a Title object to a string in the preferred variant
+        *
+        * @param $title Title
+        * @return string
+        */
+       public function convertTitle( $title ) {
                return $this->mConverter->convertTitle( $title );
        }
 
-       # Check if this is a language with variants
-       function hasVariants() {
+       /**
+        * Check if this is a language with variants
+        *
+        * @return bool
+        */
+       public function hasVariants() {
                return sizeof( $this->getVariants() ) > 1;
        }
 
-       # Put custom tags (e.g. -{ }-) around math to prevent conversion
-       function armourMath( $text ) {
+       /**
+        * Check if the language has the specific variant
+        * @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
+        */
+       public function armourMath( $text ) {
                return $this->mConverter->armourMath( $text );
        }
 
@@ -2794,11 +3345,15 @@ 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 ) );
        }
 
-       function convertCategoryKey( $key ) {
+       /**
+        * @param $key string
+        * @return string
+        */
+       public function convertCategoryKey( $key ) {
                return $this->mConverter->convertCategoryKey( $key );
        }
 
@@ -2808,19 +3363,28 @@ class Language {
         *
         * @return array an array of language codes
         */
-       function getVariants() {
+       public function getVariants() {
                return $this->mConverter->getVariants();
        }
 
-       function getPreferredVariant() {
+       /**
+        * @return string
+        */
+       public function getPreferredVariant() {
                return $this->mConverter->getPreferredVariant();
        }
 
-       function getDefaultVariant() {
+       /**
+        * @return string
+        */
+       public function getDefaultVariant() {
                return $this->mConverter->getDefaultVariant();
        }
 
-       function getURLVariant() {
+       /**
+        * @return string
+        */
+       public function getURLVariant() {
                return $this->mConverter->getURLVariant();
        }
 
@@ -2836,7 +3400,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 );
        }
 
@@ -2846,8 +3410,12 @@ class Language {
         *  'variant' => text in that variant
         *
         * @deprecated since 1.17 Use autoConvertToAllVariants()
+        *
+        * @param $text string
+        *
+        * @return string
         */
-       function convertLinkToAllVariants( $text ) {
+       public function convertLinkToAllVariants( $text ) {
                return $this->mConverter->convertLinkToAllVariants( $text );
        }
 
@@ -2868,7 +3436,7 @@ class Language {
         *
         * @return string
         */
-       function getParsedTitle() {
+       public function getParsedTitle() {
                return $this->mConverter->getParsedTitle();
        }
 
@@ -2877,10 +3445,10 @@ class Language {
         * various functions in the Parser
         *
         * @param $text String: text to be tagged for no conversion
-        * @param $noParse
+        * @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 );
        }
 
@@ -2890,23 +3458,46 @@ class Language {
         *
         * @return string
         */
-       function linkTrail() {
+       public function linkTrail() {
                return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
        }
 
+       /**
+        * @return Language
+        */
        function getLangObj() {
                return $this;
        }
 
        /**
         * Get the RFC 3066 code for this language object
+        *
+        * @return string
         */
-       function getCode() {
+       public function getCode() {
                return $this->mCode;
        }
 
-       function setCode( $code ) {
+       /**
+        * 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
+        */
+       public function setCode( $code ) {
                $this->mCode = $code;
+               // Ensure we don't leave an incorrect html code lying around
+               $this->mHtmlCode = null;
        }
 
        /**
@@ -2916,14 +3507,14 @@ class Language {
         * @param $suffix string Append this to the filename
         * @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 ) ) 
+               if ( !Language::isValidCode( $code )
+                       || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
                {
                        throw new MWException( "Invalid language code \"$code\"" );
                }
-               
+
                return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
        }
 
@@ -2932,9 +3523,9 @@ class Language {
         * @param $filename string $prefix . $languageCode . $suffix
         * @param $prefix string Prefix before the language code
         * @param $suffix string Suffix after the language code
-        * @return Language code, or false if $prefix or $suffix isn't found
+        * @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 );
@@ -2944,43 +3535,104 @@ class Language {
                return str_replace( '_', '-', strtolower( $m[1] ) );
        }
 
-       static function getMessagesFileName( $code ) {
+       /**
+        * @param $code string
+        * @return string
+        */
+       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;
        }
 
-       static function getClassFileName( $code ) {
+       /**
+        * @param $code string
+        * @return string
+        */
+       public static function getClassFileName( $code ) {
                global $IP;
                return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
        }
 
        /**
-        * Get the fallback for a given language
+        * Get the first fallback for a given language.
+        *
+        * @param $code string
+        *
+        * @return false|string
         */
-       static function getFallbackFor( $code ) {
-               if ( $code === 'en' ) {
-                       // Shortcut
+       public static function getFallbackFor( $code ) {
+               if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
                        return false;
                } else {
-                       return self::getLocalisationCache()->getItem( $code, 'fallback' );
+                       $fallbacks = self::getFallbacksFor( $code );
+                       $first = array_shift( $fallbacks );
+                       return $first;
+               }
+       }
+
+       /**
+        * Get the ordered list of fallback languages.
+        *
+        * @since 1.19
+        * @param $code string Language code
+        * @return array
+        */
+       public static function getFallbacksFor( $code ) {
+               if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
+                       return array();
+               } else {
+                       $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
+                       $v = array_map( 'trim', explode( ',', $v ) );
+                       if ( $v[count( $v ) - 1] !== 'en' ) {
+                               $v[] = 'en';
+                       }
+                       return $v;
                }
        }
 
        /**
         * Get all messages for a given language
-        * WARNING: this may take a long time
+        * WARNING: this may take a long time. If you just need all message *keys*
+        * but need the *contents* of only a few messages, consider using getMessageKeysFor().
+        *
+        * @param $code string
+        *
+        * @return array
         */
-       static function getMessagesFor( $code ) {
+       public static function getMessagesFor( $code ) {
                return self::getLocalisationCache()->getItem( $code, 'messages' );
        }
 
        /**
         * Get a message for a given language
+        *
+        * @param $key string
+        * @param $code string
+        *
+        * @return string
         */
-       static function getMessageFor( $key, $code ) {
+       public static function getMessageFor( $key, $code ) {
                return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
        }
 
+       /**
+        * Get all message keys for a given language. This is a faster alternative to
+        * array_keys( Language::getMessagesFor( $code ) )
+        *
+        * @since 1.19
+        * @param $code string Language code
+        * @return array of message keys (strings)
+        */
+       public static function getMessageKeysFor( $code ) {
+               return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
+       }
+
+       /**
+        * @param $talk
+        * @return mixed
+        */
        function fixVariableInNamespace( $talk ) {
                if ( strpos( $talk, '$1' ) === false ) {
                        return $talk;
@@ -2998,10 +3650,18 @@ class Language {
                return str_replace( ' ', '_', $talk );
        }
 
+       /**
+        * @param $m string
+        * @return string
+        */
        function replaceGrammarInNamespace( $m ) {
                return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
        }
 
+       /**
+        * @throws MWException
+        * @return array
+        */
        static function getCaseMaps() {
                static $wikiUpperChars, $wikiLowerChars;
                if ( isset( $wikiUpperChars ) ) {
@@ -3030,7 +3690,7 @@ class Language {
         */
        public function formatExpiry( $expiry, $format = true ) {
                static $infinity, $infinityMsg;
-               if( $infinity === null ){
+               if ( $infinity === null ) {
                        $infinityMsg = wfMessage( 'infiniteblock' );
                        $infinity = wfGetDB( DB_SLAVE )->getInfinity();
                }
@@ -3041,21 +3701,46 @@ class Language {
                                : $infinity;
                } else {
                        return $format === true
-                               ? $this->timeanddate( $expiry )
+                               ? $this->timeanddate( $expiry, /* User preference timezone */ true )
                                : wfTimestamp( $format, $expiry );
                }
        }
 
        /**
         * @todo Document
-        * @param  $seconds String
+        * @param $seconds int|float
+        * @param $format Array Optional
+        *              If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
+        *              If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
+        *              If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
+        *              For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
         * @return string
         */
-       function formatTimePeriod( $seconds ) {
+       function formatTimePeriod( $seconds, $format = array() ) {
+               if ( !is_array( $format ) ) {
+                       $format = array( 'avoid' => $format ); // For backwards compatibility
+               }
+               if ( !isset( $format['avoid'] ) ) {
+                       $format['avoid'] = false;
+               }
+               if ( !isset( $format['noabbrevs' ] ) ) {
+                       $format['noabbrevs'] = false;
+               }
+               $secondsMsg = wfMessage(
+                       $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
+               $minutesMsg = wfMessage(
+                       $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
+               $hoursMsg = wfMessage(
+                       $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
+               $daysMsg = wfMessage(
+                       $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
+
                if ( round( $seconds * 10 ) < 100 ) {
-                       return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
+                       $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
+                       $s = $secondsMsg->params( $s )->text();
                } elseif ( round( $seconds ) < 60 ) {
-                       return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
+                       $s = $this->formatNum( round( $seconds ) );
+                       $s = $secondsMsg->params( $s )->text();
                } elseif ( round( $seconds ) < 3600 ) {
                        $minutes = floor( $seconds / 60 );
                        $secondsPart = round( fmod( $seconds, 60 ) );
@@ -3063,9 +3748,10 @@ class Language {
                                $secondsPart = 0;
                                $minutes++;
                        }
-                       return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
-                               $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
-               } else {
+                       $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
+                       $s .= ' ';
+                       $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
+               } elseif ( round( $seconds ) <= 2 * 86400 ) {
                        $hours = floor( $seconds / 3600 );
                        $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
                        $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
@@ -3077,18 +3763,58 @@ class Language {
                                $minutes = 0;
                                $hours++;
                        }
-                       return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
-                               $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
-                               $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
+                       $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
+                       $s .= ' ';
+                       $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
+                       if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
+                               $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
+                       }
+               } else {
+                       $days = floor( $seconds / 86400 );
+                       if ( $format['avoid'] === 'avoidminutes' ) {
+                               $hours = round( ( $seconds - $days * 86400 ) / 3600 );
+                               if ( $hours == 24 ) {
+                                       $hours = 0;
+                                       $days++;
+                               }
+                               $s = $daysMsg->params( $this->formatNum( $days ) )->text();
+                               $s .= ' ';
+                               $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
+                       } elseif ( $format['avoid'] === 'avoidseconds' ) {
+                               $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
+                               $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
+                               if ( $minutes == 60 ) {
+                                       $minutes = 0;
+                                       $hours++;
+                               }
+                               if ( $hours == 24 ) {
+                                       $hours = 0;
+                                       $days++;
+                               }
+                               $s = $daysMsg->params( $this->formatNum( $days ) )->text();
+                               $s .= ' ';
+                               $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
+                               $s .= ' ';
+                               $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
+                       } else {
+                               $s = $daysMsg->params( $this->formatNum( $days ) )->text();
+                               $s .= ' ';
+                               $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
+                       }
                }
+               return $s;
        }
 
+       /**
+        * @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 );
+               $unitIndex = (int)floor( log10( $bps ) / 3 );
                $mantissa = $bps / pow( 1000, $unitIndex );
                if ( $mantissa < 10 ) {
                        $mantissa = round( $mantissa, 1 );
@@ -3102,7 +3828,7 @@ class Language {
         * Format a size in bytes for output, using an appropriate
         * unit (B, KB, MB or GB) according to the magnitude in question
         *
-        * @param $size Size to format
+        * @param $size int Size to format
         * @return string Plain text (not HTML)
         */
        function formatSize( $size ) {
@@ -3131,10 +3857,90 @@ class Language {
                return str_replace( '$1', $this->formatNum( $size ), $text );
        }
 
+       /**
+        * Make a list item, used by various special pages
+        *
+        * @param $page String Page link
+        * @param $details String Text between brackets
+        * @param $oppositedm Boolean Add the direction mark opposite to your
+        *                    language, to display text properly
+        * @return String
+        */
+       function specialList( $page, $details, $oppositedm = true ) {
+               $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
+                       $this->getDirMark();
+               $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
+                       wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
+               return $page . $details;
+       }
+
+       /**
+        * Generate (prev x| next x) (20|50|100...) type links for paging
+        *
+        * @param $title Title object to link
+        * @param $offset Integer offset parameter
+        * @param $limit Integer limit parameter
+        * @param $query String optional URL query parameter string
+        * @param $atend Bool optional param for specified if this is the last page
+        * @return String
+        */
+       public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
+               // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
+
+               # Make 'previous' link
+               $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
+               if( $offset > 0 ) {
+                       $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
+                               $query, $prev, 'prevn-title', 'mw-prevlink' );
+               } else {
+                       $plink = htmlspecialchars( $prev );
+               }
+
+               # Make 'next' link
+               $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
+               if( $atend ) {
+                       $nlink = htmlspecialchars( $next );
+               } else {
+                       $nlink = $this->numLink( $title, $offset + $limit, $limit,
+                               $query, $next, 'prevn-title', 'mw-nextlink' );
+               }
+
+               # Make links to set number of items per page
+               $numLinks = array();
+               foreach( array( 20, 50, 100, 250, 500 ) as $num ) {
+                       $numLinks[] = $this->numLink( $title, $offset, $num,
+                               $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
+               }
+
+               return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
+                       )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
+       }
+
+       /**
+        * Helper function for viewPrevNext() that generates links
+        *
+        * @param $title Title object to link
+        * @param $offset Integer offset parameter
+        * @param $limit Integer limit parameter
+        * @param $query Array extra query parameters
+        * @param $link String text to use for the link; will be escaped
+        * @param $tooltipMsg String name of the message to use as tooltip
+        * @param $class String value of the "class" attribute of the link
+        * @return String HTML fragment
+        */
+       private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
+               $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
+               $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
+               return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
+                       'title' => $tooltip, 'class' => $class ), $link );
+       }
+
        /**
         * Get the conversion rule title, if any.
+        *
+        * @return string
         */
-       function getConvRuleTitle() {
+       public function getConvRuleTitle() {
                return $this->mConverter->getConvRuleTitle();
        }
 }