Misc EOL w/s and spaces-instead-of-tabs fixes. One day I'll get around to nagging...
[lhc/web/wiklou.git] / languages / Language.php
index 7eeb6fa..8047bc0 100644 (file)
@@ -1,12 +1,16 @@
 <?php
 /**
- * @defgroup Language Language
+ * Internationalisation code
  *
  * @file
  * @ingroup Language
  */
 
-if( !defined( 'MEDIAWIKI' ) ) {
+/**
+ * @defgroup Language Language
+ */
+
+if ( !defined( 'MEDIAWIKI' ) ) {
        echo "This file is part of MediaWiki, it is not a valid entry point.\n";
        exit( 1 );
 }
@@ -15,15 +19,7 @@ if( !defined( 'MEDIAWIKI' ) ) {
 global $wgLanguageNames;
 require_once( dirname( __FILE__ ) . '/Names.php' );
 
-global $wgInputEncoding, $wgOutputEncoding;
-
-/**
- * These are always UTF-8, they exist only for backwards compatibility
- */
-$wgInputEncoding    = 'UTF-8';
-$wgOutputEncoding      = 'UTF-8';
-
-if( function_exists( 'mb_strtoupper' ) ) {
+if ( function_exists( 'mb_strtoupper' ) ) {
        mb_internal_encoding( 'UTF-8' );
 }
 
@@ -34,19 +30,21 @@ if( function_exists( 'mb_strtoupper' ) ) {
  */
 class FakeConverter {
        var $mLang;
-       function FakeConverter( $langobj ) { $this->mLang = $langobj; }
-       function autoConvertToAllVariants( $text ) { return $text; }
+       function __construct( $langobj ) { $this->mLang = $langobj; }
+       function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
        function convert( $t ) { return $t; }
        function convertTitle( $t ) { return $t->getPrefixedText(); }
        function getVariants() { return array( $this->mLang->getCode() ); }
        function getPreferredVariant() { return $this->mLang->getCode(); }
+       function getDefaultVariant() { return $this->mLang->getCode(); }
+       function getURLVariant() { return ''; }
        function getConvRuleTitle() { return false; }
-       function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) {}
+       function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
        function getExtraHashOptions() { return ''; }
        function getParsedTitle() { return ''; }
        function markNoConversion( $text, $noParse = false ) { return $text; }
        function convertCategoryKey( $key ) { return $key; }
-       function convertLinkToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
+       function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
        function armourMath( $text ) { return $text; }
 }
 
@@ -67,7 +65,11 @@ class Language {
         */
        var $transformData = array();
 
+       /**
+        * @var LocalisationCache
+        */
        static public $dataCache;
+
        static public $mLangObjCache = array();
 
        static public $mWeekdayMsgs = array(
@@ -126,10 +128,12 @@ class Language {
 
        /**
         * Get a cached language object for a given language code
+        * @param $code String
+        * @return Language
         */
        static function factory( $code ) {
                if ( !isset( self::$mLangObjCache[$code] ) ) {
-                       if( count( self::$mLangObjCache ) > 10 ) {
+                       if ( count( self::$mLangObjCache ) > 10 ) {
                                // Don't keep a billion objects around, that's stupid.
                                self::$mLangObjCache = array();
                        }
@@ -140,20 +144,40 @@ class Language {
 
        /**
         * Create a language object for a given language code
+        * @param $code String
+        * @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 ) )
+               {
+                       throw new MWException( "Invalid language code \"$code\"" );
+               }
+
+               if ( !Language::isValidBuiltInCode( $code ) ) {
+                       // 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 ) );
-                       // 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" );
+                       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" );
+                               }
                        }
                }
 
@@ -161,7 +185,7 @@ class Language {
                        throw new MWException( "Language fallback loop detected when creating class $class\n" );
                }
 
-               if( !class_exists( $class ) ) {
+               if ( !MWInit::classExists( $class ) ) {
                        $fallback = Language::getFallbackFor( $code );
                        ++$recursionLevel;
                        $lang = Language::newFromCode( $fallback );
@@ -173,8 +197,29 @@ class Language {
                return $lang;
        }
 
+       /**
+        * 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.
+        */
+       public static function isValidCode( $code ) {
+               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
+        * internal customisation of MediaWiki, via Messages*.php.
+        */
+       public static function isValidBuiltInCode( $code ) {
+               return preg_match( '/^[a-z0-9-]*$/i', $code );
+       }
+
        /**
         * Get the LocalisationCache instance
+        *
+        * @return LocalisationCache
         */
        public static function getLocalisationCache() {
                if ( is_null( self::$dataCache ) ) {
@@ -209,16 +254,7 @@ class Language {
         * Hook which will be called if this is the content language.
         * Descendants can use this to register hook functions or modify globals
         */
-       function initContLang() {}
-
-       /**
-        * @deprecated Use User::getDefaultOptions()
-        * @return array
-        */
-       function getDefaultUserOptions() {
-               wfDeprecated( __METHOD__ );
-               return User::getDefaultOptions();
-       }
+       function initContLang() { }
 
        function getFallbackLanguageCode() {
                if ( $this->mCode === 'en' ) {
@@ -241,12 +277,12 @@ class Language {
         */
        function getNamespaces() {
                if ( is_null( $this->namespaceNames ) ) {
-                       global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk;
+                       global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
 
                        $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
-                       if ( $wgExtraNamespaces ) {
-                               $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames;
-                       }
+                       $validNamespaces = MWNamespace::getCanonicalNamespaces();
+
+                       $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
 
                        $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
                        if ( $wgMetaNamespaceTalk ) {
@@ -257,6 +293,13 @@ class Language {
                                        $this->fixVariableInNamespace( $talk );
                        }
 
+                       # Sometimes a language will be localised but not actually exist on this wiki.
+                       foreach( $this->namespaceNames as $key => $text ) {
+                               if ( !isset( $validNamespaces[$key] ) ) {
+                                       unset( $this->namespaceNames[$key] );
+                               }
+                       }
+
                        # The above mixing may leave namespaces out of canonical order.
                        # Re-order by namespace ID number...
                        ksort( $this->namespaceNames );
@@ -274,7 +317,7 @@ class Language {
         */
        function getFormattedNamespaces() {
                $ns = $this->getNamespaces();
-               foreach( $ns as $k => $v ) {
+               foreach ( $ns as $k => $v ) {
                        $ns[$k] = strtr( $v, '_', ' ' );
                }
                return $ns;
@@ -307,6 +350,29 @@ class Language {
                return strtr( $ns, '_', ' ' );
        }
 
+       /**
+        * Returns gender-dependent namespace alias if available.
+        * @param $index Int: namespace index
+        * @param $gender String: gender key (male, female... )
+        * @return String
+        * @since 1.18
+        */
+       function getGenderNsText( $index, $gender ) {
+               $ns = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+               return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
+       }
+
+       /**
+        * Whether this language makes distinguishes genders for example in
+        * namespaces.
+        * @return bool
+        * @since 1.18
+        */
+       function needsGenderDistinction() {
+               $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+               return count( $aliases ) > 0;
+       }
+
        /**
         * Get a namespace key by value, case insensitive.
         * Only matches namespace names for the current language, not the
@@ -335,6 +401,14 @@ class Language {
                                        }
                                }
                        }
+
+                       $genders = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
+                       foreach ( $genders as $index => $forms ) {
+                               foreach ( $forms as $alias ) {
+                                       $aliases[$alias] = $index;
+                               }
+                       }
+
                        $this->namespaceAliases = $aliases;
                }
                return $this->namespaceAliases;
@@ -408,10 +482,6 @@ class Language {
                );
        }
 
-       function getMathNames() {
-               return self::$dataCache->getItem( $this->mCode, 'mathNames' );
-       }
-
        function getDatePreferences() {
                return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
        }
@@ -455,8 +525,14 @@ class Language {
         * If $customisedOnly is true, only returns codes with a messages file
         */
        public static function getLanguageNames( $customisedOnly = false ) {
-               global $wgLanguageNames, $wgExtraLanguageNames;
-               $allNames = $wgExtraLanguageNames + $wgLanguageNames;
+               global $wgExtraLanguageNames;
+               static $coreLanguageNames;
+
+               if ( $coreLanguageNames === null ) {
+                       include( MWInit::compiledPath( 'languages/Names.php' ) );
+               }
+
+               $allNames = $wgExtraLanguageNames + $coreLanguageNames;
                if ( !$customisedOnly ) {
                        return $allNames;
                }
@@ -464,7 +540,7 @@ class Language {
                global $IP;
                $names = array();
                $dir = opendir( "$IP/languages/messages" );
-               while( false !== ( $file = readdir( $dir ) ) ) {
+               while ( false !== ( $file = readdir( $dir ) ) ) {
                        $code = self::getCodeFromFileName( $file, 'Messages' );
                        if ( $code && isset( $allNames[$code] ) ) {
                                $names[$code] = $allNames[$code];
@@ -474,6 +550,25 @@ class Language {
                return $names;
        }
 
+       /**
+        * Get translated language names. This is done on best effort and
+        * by default this is exactly the same as Language::getLanguageNames.
+        * The CLDR extension provides translated names.
+        * @param $code String Language code.
+        * @return Array language code => language name
+        * @since 1.18.0
+        */
+       public static function getTranslatedLanguageNames( $code ) {
+               $names = array();
+               wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
+
+               foreach ( self::getLanguageNames() as $code => $name ) {
+                       if ( !isset( $names[$code] ) ) $names[$code] = $name;
+               }
+
+               return $names;
+       }
+
        /**
         * Get a message from the MediaWiki namespace.
         *
@@ -496,6 +591,14 @@ class Language {
                return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
        }
 
+       function getMonthNamesArray() {
+               $monthNames = array( '' );
+               for ( $i=1; $i < 13; $i++ ) {
+                       $monthNames[] = $this->getMonthName( $i );
+               }
+               return $monthNames;
+       }
+
        function getMonthNameGen( $key ) {
                return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
        }
@@ -504,6 +607,14 @@ class Language {
                return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
        }
 
+       function getMonthAbbreviationsArray() {
+               $monthNames = array('');
+               for ( $i=1; $i < 13; $i++ ) {
+                       $monthNames[] = $this->getMonthAbbreviation( $i );
+               }
+               return $monthNames;
+       }
+
        function getWeekdayName( $key ) {
                return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
        }
@@ -558,15 +669,15 @@ class Language {
 
                $minDiff = 0;
                if ( $data[0] == 'System' || $tz == '' ) {
-                       # Global offset in minutes.
-                       if( isset( $wgLocalTZoffset ) ) {
+                       #  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 ) {
+                       if ( count( $data ) == 2 ) {
                                $data[0] = intval( $data[0] );
                                $data[1] = intval( $data[1] );
                                $minDiff = abs( $data[0] ) * 60 + $data[1];
@@ -588,12 +699,12 @@ class Language {
                # 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, 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
+                 (int)substr( $ts, 0, 4 ) ); # Year
 
                $date = date( 'YmdHis', $t );
                wfRestoreWarnings();
@@ -607,9 +718,8 @@ class Language {
         * escaping format.
         *
         * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
-        * PHP manual for definitions. "o" format character is supported since
-        * PHP 5.1.0, previous versions return literal o.
-        * There are a number of extensions, which start with "x":
+        * PHP manual for definitions. There are a number of extensions, which
+        * start with "x":
         *
         *    xn   Do not translate digits of the next numeric format character
         *    xN   Toggle raw digit (xn) flag, stays set until explicitly unset
@@ -659,7 +769,6 @@ class Language {
         * @param $ts String: 14-character timestamp
         *      YYYYMMDDHHMMSS
         *      01234567890123
-        * @todo emulation of "o" format character for PHP pre 5.1.0
         * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
         */
        function sprintfDate( $format, $ts ) {
@@ -834,18 +943,11 @@ class Language {
                                        }
                                        $num = gmdate( 'L', $unix );
                                        break;
-                               # 'o' is supported since PHP 5.1.0
-                               # return literal if not supported
-                               # TODO: emulation for pre 5.1.0 versions
                                case 'o':
                                        if ( !$unix ) {
                                                $unix = wfTimestamp( TS_UNIX, $ts );
                                        }
-                                       if ( version_compare( PHP_VERSION, '5.1.0' ) === 1 ) {
-                                               $num = date( 'o', $unix );
-                                       } else {
-                                               $s .= 'o';
-                                       }
+                                       $num = date( 'o', $unix );
                                        break;
                                case 'Y':
                                        $num = substr( $ts, 0, 4 );
@@ -967,13 +1069,12 @@ class Language {
                                } elseif ( $roman ) {
                                        $s .= self::romanNumeral( $num );
                                        $roman = false;
-                               } elseif( $hebrewNum ) {
+                               } elseif ( $hebrewNum ) {
                                        $s .= self::hebrewNumeral( $num );
                                        $hebrewNum = false;
                                } else {
                                        $s .= $this->formatNum( $num, true );
                                }
-                               $num = false;
                        }
                }
                return $s;
@@ -992,7 +1093,7 @@ class Language {
        private static function tsToIranian( $ts ) {
                $gy = substr( $ts, 0, 4 ) -1600;
                $gm = substr( $ts, 4, 2 ) -1;
-               $gd = substr( $ts, 6, 2 ) -1;
+               $gd = (int)substr( $ts, 6, 2 ) -1;
 
                # Days passed from the beginning (including leap years)
                $gDayNo = 365 * $gy
@@ -1002,12 +1103,12 @@ class Language {
 
 
                // Add days of the past months of this year
-               for( $i = 0; $i < $gm; $i++ ) {
+               for ( $i = 0; $i < $gm; $i++ ) {
                        $gDayNo += self::$GREG_DAYS[$i];
                }
 
                // Leap years
-               if ( $gm > 1 && ( ( $gy%4 === 0 && $gy%100 !== 0 || ( $gy%400 == 0 ) ) ) ) {
+               if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
                        $gDayNo++;
                }
 
@@ -1068,11 +1169,11 @@ class Language {
                                                                (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
                }
 
-               $zl = $zjd-1948440 + 10632;
+               $zl = $zjd -1948440 + 10632;
                $zn = (int)( ( $zl - 1 ) / 10631 );
                $zl = $zl - 10631 * $zn + 354;
-               $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ((int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
-               $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ((int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
+               $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
+               $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
                $zm = (int)( ( 24 * $zl ) / 709 );
                $zd = $zl - (int)( ( 709 * $zm ) / 24 );
                $zy = 30 * $zn + $zj - 30;
@@ -1102,7 +1203,7 @@ class Language {
 
                # Month number when September = 1, August = 12
                $month += 4;
-               if( $month > 12 ) {
+               if ( $month > 12 ) {
                        # Next year
                        $month -= 12;
                        $year++;
@@ -1111,15 +1212,15 @@ class Language {
 
                # Calculate day of year from 1 September
                $dayOfYear = $day;
-               for( $i = 1; $i < $month; $i++ ) {
-                       if( $i == 6 ) {
+               for ( $i = 1; $i < $month; $i++ ) {
+                       if ( $i == 6 ) {
                                # February
                                $dayOfYear += 28;
                                # Check if the year is leap
-                               if( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
+                               if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
                                        $dayOfYear++;
                                }
-                       } elseif( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
+                       } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
                                $dayOfYear += 30;
                        } else {
                                $dayOfYear += 31;
@@ -1130,7 +1231,7 @@ class Language {
                $start = self::hebrewYearStart( $hebrewYear );
 
                # Calculate next year's start
-               if( $dayOfYear <= $start ) {
+               if ( $dayOfYear <= $start ) {
                        # Day is before the start of the year - it is the previous year
                        # Next year's start
                        $nextStart = $start;
@@ -1139,7 +1240,7 @@ class Language {
                        $hebrewYear--;
                        # Add days since previous year's 1 September
                        $dayOfYear += 365;
-                       if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
+                       if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
                                # Leap year
                                $dayOfYear++;
                        }
@@ -1158,7 +1259,7 @@ class Language {
                # Add 12 (or 13 for leap years) days to ignore the difference between
                # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
                # difference is only about the year type
-               if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
+               if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
                        $diff += 13;
                } else {
                        $diff += 12;
@@ -1178,14 +1279,14 @@ class Language {
                $hebrewDay = $hebrewDayOfYear;
                $hebrewMonth = 1;
                $days = 0;
-               while( $hebrewMonth <= 12 ) {
+               while ( $hebrewMonth <= 12 ) {
                        # Calculate days in this month
-                       if( $isLeap && $hebrewMonth == 6 ) {
+                       if ( $isLeap && $hebrewMonth == 6 ) {
                                # Adar in a leap year
-                               if( $isLeap ) {
+                               if ( $isLeap ) {
                                        # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
                                        $days = 30;
-                                       if( $hebrewDay <= $days ) {
+                                       if ( $hebrewDay <= $days ) {
                                                # Day in Adar I
                                                $hebrewMonth = 13;
                                        } else {
@@ -1193,23 +1294,23 @@ class Language {
                                                $hebrewDay -= $days;
                                                # Try Adar II
                                                $days = 29;
-                                               if( $hebrewDay <= $days ) {
+                                               if ( $hebrewDay <= $days ) {
                                                        # Day in Adar II
                                                        $hebrewMonth = 14;
                                                }
                                        }
                                }
-                       } elseif( $hebrewMonth == 2 && $yearPattern == 2 ) {
+                       } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
                                # Cheshvan in a complete year (otherwise as the rule below)
                                $days = 30;
-                       } elseif( $hebrewMonth == 3 && $yearPattern == 0 ) {
+                       } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
                                # Kislev in an incomplete year (otherwise as the rule below)
                                $days = 29;
                        } else {
                                # Odd months have 30 days, even have 29
                                $days = 30 - ( $hebrewMonth - 1 ) % 2;
                        }
-                       if( $hebrewDay <= $days ) {
+                       if ( $hebrewDay <= $days ) {
                                # In the current month
                                break;
                        } else {
@@ -1232,21 +1333,21 @@ class Language {
                $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
                $b = intval( ( $year - 1 ) % 4 );
                $m = 32.044093161144 + 1.5542417966212 * $a +  $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
-               if( $m < 0 ) {
+               if ( $m < 0 ) {
                        $m--;
                }
                $Mar = intval( $m );
-               if( $m < 0 ) {
+               if ( $m < 0 ) {
                        $m++;
                }
                $m -= $Mar;
 
-               $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7);
-               if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
+               $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 ) {
+               } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
                        $Mar += 2;
-               } else if( $c == 2 || $c == 4 || $c == 6 ) {
+               } else if ( $c == 2 || $c == 4 || $c == 6 ) {
                        $Mar++;
                }
 
@@ -1364,7 +1465,7 @@ class Language {
                return $s;
        }
 
-       /**
+       /**
         * Hebrew Gematria number formatting up to 9999
         */
        static function hebrewNumeral( $num ) {
@@ -1388,14 +1489,14 @@ class Language {
                                        $num = 0;
                                } else {
                                        $s .= $table[$i][intval( ( $num / $pow10 ) )];
-                                       if( $pow10 == 1000 ) {
+                                       if ( $pow10 == 1000 ) {
                                                $s .= "'";
                                        }
                                }
                        }
                        $num = $num % $pow10;
                }
-               if( strlen( $s ) == 2 ) {
+               if ( strlen( $s ) == 2 ) {
                        $str = $s . "'";
                } else  {
                        $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
@@ -1443,8 +1544,8 @@ class Language {
        function dateFormat( $usePrefs = true ) {
                global $wgUser;
 
-               if( is_bool( $usePrefs ) ) {
-                       if( $usePrefs ) {
+               if ( is_bool( $usePrefs ) ) {
+                       if ( $usePrefs ) {
                                $datePreference = $wgUser->getDatePreference();
                        } else {
                                $datePreference = (string)User::getDefaultOption( 'date' );
@@ -1454,7 +1555,7 @@ class Language {
                }
 
                // return int
-               if( $datePreference == '' ) {
+               if ( $datePreference == '' ) {
                        return 'default';
                }
 
@@ -1494,6 +1595,7 @@ class Language {
         * @return string
         */
        function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
+               $ts = wfTimestamp( TS_MW, $ts );
                if ( $adj ) {
                        $ts = $this->userAdjust( $ts, $timecorrection );
                }
@@ -1512,6 +1614,7 @@ class Language {
         * @return string
         */
        function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
+               $ts = wfTimestamp( TS_MW, $ts );
                if ( $adj ) {
                        $ts = $this->userAdjust( $ts, $timecorrection );
                }
@@ -1530,7 +1633,7 @@ class Language {
         *                        validateTimeZone() in Special:Preferences
         * @return string
         */
-       function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
+       function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
                $ts = wfTimestamp( TS_MW, $ts );
                if ( $adj ) {
                        $ts = $this->userAdjust( $ts, $timecorrection );
@@ -1589,32 +1692,37 @@ class Language {
                return strtr( $matches[0], $wikiUpperChars );
        }
 
+       /**
+        * Make a string's first character uppercase
+        */
        function ucfirst( $str ) {
                $o = ord( $str );
-               if ( $o < 96 ) {
+               if ( $o < 96 ) { // if already uppercase...
                        return $str;
                } elseif ( $o < 128 ) {
-                       return ucfirst( $str );
+                       return ucfirst( $str ); // use PHP's ucfirst()
                } else {
                        // fall back to more complex logic in case of multibyte strings
-                       return self::uc( $str, true );
+                       return $this->uc( $str, true );
                }
        }
 
+       /**
+        * Convert a string to uppercase
+        */
        function uc( $str, $first = false ) {
                if ( function_exists( 'mb_strtoupper' ) ) {
                        if ( $first ) {
-                               if ( self::isMultibyte( $str ) ) {
+                               if ( $this->isMultibyte( $str ) ) {
                                        return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
                                } else {
                                        return ucfirst( $str );
                                }
                        } else {
-                               return self::isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
+                               return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
                        }
                } else {
-                       if ( self::isMultibyte( $str ) ) {
-                               list( $wikiUpperChars ) = $this->getCaseMaps();
+                       if ( $this->isMultibyte( $str ) ) {
                                $x = $first ? '^' : '';
                                return preg_replace_callback(
                                        "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
@@ -1632,7 +1740,7 @@ class Language {
                if ( !$o ) {
                        return strval( $str );
                } elseif ( $o >= 128 ) {
-                       return self::lc( $str, true );
+                       return $this->lc( $str, true );
                } elseif ( $o > 96 ) {
                        return $str;
                } else {
@@ -1644,17 +1752,16 @@ class Language {
        function lc( $str, $first = false ) {
                if ( function_exists( 'mb_strtolower' ) ) {
                        if ( $first ) {
-                               if ( self::isMultibyte( $str ) ) {
+                               if ( $this->isMultibyte( $str ) ) {
                                        return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
                                } else {
                                        return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
                                }
                        } else {
-                               return self::isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
+                               return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
                        }
                } else {
-                       if ( self::isMultibyte( $str ) ) {
-                               list( , $wikiLowerChars ) = self::getCaseMaps();
+                       if ( $this->isMultibyte( $str ) ) {
                                $x = $first ? '^' : '';
                                return preg_replace_callback(
                                        "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
@@ -1672,8 +1779,8 @@ class Language {
        }
 
        function ucwords( $str ) {
-               if ( self::isMultibyte( $str ) ) {
-                       $str = self::lc( $str );
+               if ( $this->isMultibyte( $str ) ) {
+                       $str = $this->lc( $str );
 
                        // regexp to find first letter in each word (i.e. after each space)
                        $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
@@ -1699,8 +1806,8 @@ class Language {
 
        # capitalize words at word breaks
        function ucwordbreaks( $str ) {
-               if ( self::isMultibyte( $str ) ) {
-                       $str = self::lc( $str );
+               if ( $this->isMultibyte( $str ) ) {
+                       $str = $this->lc( $str );
 
                        // since \b doesn't work for UTF-8, we explicitely define word break chars
                        $breaks = "[ \-\(\)\}\{\.,\?!]";
@@ -1746,18 +1853,18 @@ class Language {
        }
 
        function checkTitleEncoding( $s ) {
-               if( is_array( $s ) ) {
+               if ( is_array( $s ) ) {
                        wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
                }
                # Check for non-UTF-8 URLs
-               $ishigh = preg_match( '/[\x80-\xff]/', $s);
-               if( !$ishigh ) {
+               $ishigh = preg_match( '/[\x80-\xff]/', $s );
+               if ( !$ishigh ) {
                        return $s;
                }
 
                $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
-                '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
-               if( $isutf8 ) {
+                               '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
+               if ( $isutf8 ) {
                        return $s;
                }
 
@@ -1797,7 +1904,7 @@ class Language {
         * @return String
         */
        function normalizeForSearch( $string ) {
-               return self::convertDoubleWidth($string);
+               return self::convertDoubleWidth( $string );
        }
 
        /**
@@ -1808,7 +1915,7 @@ class Language {
                static $full = null;
                static $half = null;
 
-               if( $full === null ) {
+               if ( $full === null ) {
                        $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                        $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                        $full = str_split( $fullWidth, 3 );
@@ -1904,7 +2011,7 @@ class Language {
                # wgInputEncoding, this text will be further converted
                # to wgOutputEncoding.
                global $wgEditEncoding;
-               if( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
+               if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
                        return $s;
                } else {
                        return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
@@ -1914,12 +2021,12 @@ class Language {
        function recodeInput( $s ) {
                # Take the previous into account.
                global $wgEditEncoding;
-               if( $wgEditEncoding != '' ) {
+               if ( $wgEditEncoding != '' ) {
                        $enc = $wgEditEncoding;
                } else {
                        $enc = 'UTF-8';
                }
-               if( $enc == 'UTF-8' ) {
+               if ( $enc == 'UTF-8' ) {
                        return $s;
                } else {
                        return $this->iconv( $enc, 'UTF-8', $s );
@@ -1934,7 +2041,14 @@ class Language {
         * This is language-specific for performance reasons only.
         */
        function normalize( $s ) {
-               return UtfNormal::cleanUp( $s );
+               global $wgAllUnicodeFixes;
+               $s = UtfNormal::cleanUp( $s );
+               if ( $wgAllUnicodeFixes ) {
+                       $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
+                       $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
+               }
+
+               return $s;
        }
 
        /**
@@ -2032,14 +2146,20 @@ class Language {
                return self::$dataCache->getItem( $this->mCode, 'magicWords' );
        }
 
+       protected function doMagicHook() {
+               if ( $this->mMagicHookDone ) {
+                       return;
+               }
+               $this->mMagicHookDone = true;
+               wfProfileIn( 'LanguageGetMagic' );
+               wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
+               wfProfileOut( 'LanguageGetMagic' );
+       }
+
        # Fill a MagicWord object with data from here
        function getMagic( $mw ) {
-               if ( !$this->mMagicHookDone ) {
-                       $this->mMagicHookDone = true;
-                       wfProfileIn( 'LanguageGetMagic' );
-                       wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
-                       wfProfileOut( 'LanguageGetMagic' );
-               }
+               $this->doMagicHook();
+
                if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
                        $rawEntry = $this->mMagicExtensions[$mw->mId];
                } else {
@@ -2051,7 +2171,7 @@ class Language {
                        }
                }
 
-               if( !is_array( $rawEntry ) ) {
+               if ( !is_array( $rawEntry ) ) {
                        error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
                } else {
                        $mw->mCaseSensitive = $rawEntry[0];
@@ -2172,7 +2292,7 @@ class Language {
         * @param $_ mixed
         * @return string
         */
-       function commafy($_) {
+       function commafy( $_ ) {
                return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
        }
 
@@ -2195,13 +2315,13 @@ class Language {
        function listToText( $l ) {
                $s = '';
                $m = count( $l ) - 1;
-               if( $m == 1 ) {
+               if ( $m == 1 ) {
                        return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
                } else {
                        for ( $i = $m; $i >= 0; $i-- ) {
                                if ( $i == $m ) {
                                        $s = $l[$i];
-                               } else if( $i == $m - 1 ) {
+                               } else if ( $i == $m - 1 ) {
                                        $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
                                } else {
                                        $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
@@ -2269,32 +2389,45 @@ class Language {
         * If $length is negative, the string will be truncated from the beginning
         *
         * @param $string String to truncate
-        * @param $length Int: maximum length (excluding ellipses)
+        * @param $length Int: maximum length (including ellipses)
         * @param $ellipsis String to append to the truncated text
+        * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
+        *      $adjustLength was introduced in 1.18, before that behaved as if false.
         * @return string
         */
-       function truncate( $string, $length, $ellipsis = '...' ) {
+       function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
                # Use the localized ellipsis character
                if ( $ellipsis == '...' ) {
                        $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
                }
                # Check if there is no need to truncate
                if ( $length == 0 ) {
-                       return $ellipsis;
+                       return $ellipsis; // convention
                } elseif ( strlen( $string ) <= abs( $length ) ) {
-                       return $string;
+                       return $string; // no need to truncate
                }
                $stringOriginal = $string;
-               if ( $length > 0 ) {
-                       $string = substr( $string, 0, $length ); // xyz...
-                       $string = $this->removeBadCharLast( $string );
-                       $string = $string . $ellipsis;
+               # If ellipsis length is >= $length then we can't apply $adjustLength
+               if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
+                       $string = $ellipsis; // this can be slightly unexpected
+               # Otherwise, truncate and add ellipsis...
                } else {
-                       $string = substr( $string, $length ); // ...xyz
-                       $string = $this->removeBadCharFirst( $string );
-                       $string = $ellipsis . $string;
+                       $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
+                       if ( $length > 0 ) {
+                               $length -= $eLength;
+                               $string = substr( $string, 0, $length ); // xyz...
+                               $string = $this->removeBadCharLast( $string );
+                               $string = $string . $ellipsis;
+                       } else {
+                               $length += $eLength;
+                               $string = substr( $string, $length ); // ...xyz
+                               $string = $this->removeBadCharFirst( $string );
+                               $string = $ellipsis . $string;
+                       }
                }
-               # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
+               # 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.
                if ( strlen( $string ) < strlen( $stringOriginal ) ) {
                        return $string;
                } else {
@@ -2310,17 +2443,19 @@ class Language {
         * @return string
         */
        protected function removeBadCharLast( $string ) {
-               $char = ord( $string[strlen( $string ) - 1] );
-               $m = array();
-               if ( $char >= 0xc0 ) {
-                       # We got the first byte only of a multibyte char; remove it.
-                       $string = substr( $string, 0, -1 );
-               } elseif ( $char >= 0x80 &&
-                     preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
-                                 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
-               {
-                       # We chopped in the middle of a character; remove it
-                       $string = $m[1];
+               if ( $string != '' ) {
+                       $char = ord( $string[strlen( $string ) - 1] );
+                       $m = array();
+                       if ( $char >= 0xc0 ) {
+                               # We got the first byte only of a multibyte char; remove it.
+                               $string = substr( $string, 0, -1 );
+                       } elseif ( $char >= 0x80 &&
+                                 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
+                                                         '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
+                       {
+                               # We chopped in the middle of a character; remove it
+                               $string = $m[1];
+                       }
                }
                return $string;
        }
@@ -2333,25 +2468,28 @@ class Language {
         * @return string
         */
        protected function removeBadCharFirst( $string ) {
-               $char = ord( $string[0] );
-               if ( $char >= 0x80 && $char < 0xc0 ) {
-                       # We chopped in the middle of a character; remove the whole thing
-                       $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
+               if ( $string != '' ) {
+                       $char = ord( $string[0] );
+                       if ( $char >= 0x80 && $char < 0xc0 ) {
+                               # We chopped in the middle of a character; remove the whole thing
+                               $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
+                       }
                }
                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
         *
         * This is only intended for styled/linked text, such as HTML with
-        * tags like <span> and <a>, were the tags are self-contained (valid HTML)
+        * tags like <span> and <a>, were the tags are self-contained (valid HTML).
+        * Also, this will not detect things like "display:none" CSS.
         *
-        * Note: tries to fix broken HTML with MWTidy
+        * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
         *
-        * @param string $text String to truncate
-        * @param int $length (zero/positive) Maximum length (excluding ellipses)
+        * @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
         */
@@ -2360,22 +2498,45 @@ class Language {
                if ( $ellipsis == '...' ) {
                        $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
                }
-               # Check if there is no need to truncate
+               # Check if there is clearly no need to truncate
                if ( $length <= 0 ) {
-                       return $ellipsis; // no text shown, nothing to format
+                       return $ellipsis; // no text shown, nothing to format (convention)
                } elseif ( strlen( $text ) <= $length ) {
-                       return $text; // string short enough even *with* HTML
+                       return $text; // string short enough even *with* HTML (short-circuit)
                }
-               $text = MWTidy::tidy( $text ); // fix tags
+
                $displayLen = 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 = $ch = '';
-               $openTags = array();
-               $textLen = strlen($text);
-               for( $pos = 0; $pos < $textLen; ++$pos ) {
+               $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
+               $openTags = array(); // open tag stack
+               $pOpenTags = array();
+
+               $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.
+                       # Check that we're not in the middle of a bracket/entity...
+                       if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
+                               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 ) ) {
+                                       # 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
+                                       $ret .= $ellipsis; // add ellipsis
+                                       break;
+                               }
+                       }
+                       if ( $pos >= $textLen ) break; // extra iteration just for above checks
+
+                       # Read the next char...
                        $ch = $text[$pos];
                        $lastCh = $pos ? $text[$pos - 1] : '';
                        $ret .= $ch; // add to result string
@@ -2413,36 +2574,20 @@ class Language {
                                                $entityState = 1; // entity found, (e.g. "&#160;")
                                        } else {
                                                $displayLen++; // this char is displayed
-                                               // Add on the other display text after this...
-                                               $skipped = $this->truncate_skip(
-                                                       $ret, $text, "<>&", $pos + 1, $length - $displayLen );
+                                               // Add the next $max display text chars after this in one swoop...
+                                               $max = ( $testingEllipsis ? $length : $neLength ) - $displayLen;
+                                               $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
                                                $displayLen += $skipped;
                                                $pos += $skipped;
                                        }
                                }
                        }
-                       # Consider truncation once the display length has reached the maximim.
-                       # Double-check that we're not in the middle of a bracket/entity...
-                       if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
-                               if ( !$testingEllipsis ) {
-                                       $testingEllipsis = true;
-                                       # Save where we are; we will truncate here unless
-                                       # the ellipsis actually makes the string longer.
-                                       $pOpenTags = $openTags; // save state
-                                       $pRet = $ret; // save state
-                               } elseif ( $displayLen > ( $length + strlen( $ellipsis ) ) ) {
-                                       # Ellipsis won't make string longer/equal, the truncation point was OK.
-                                       $openTags = $pOpenTags; // reload state
-                                       $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
-                                       $ret .= $ellipsis; // add ellipsis
-                                       break;
-                               }
-                       }
                }
                if ( $displayLen == 0 ) {
                        return ''; // no text shown, nothing to format
                }
-               $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
+               // Close the last tag if left unclosed by bad HTML
+               $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
                while ( count( $openTags ) > 0 ) {
                        $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
                }
@@ -2451,25 +2596,36 @@ class Language {
 
        // truncateHtml() helper function
        // like strcspn() but adds the skipped chars to $ret
-       private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
+       private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
+               if ( $len === null ) {
+                       $len = -1; // -1 means "no limit" for strcspn
+               } elseif ( $len < 0 ) {
+                       $len = 0; // sanity
+               }
                $skipCount = 0;
-               if( $start < strlen( $text ) ) {
+               if ( $start < strlen( $text ) ) {
                        $skipCount = strcspn( $text, $search, $start, $len );
                        $ret .= substr( $text, $start, $skipCount );
                }
                return $skipCount;
        }
 
-       // truncateHtml() helper function
-       // (a) push or pop $tag from $openTags as needed
-       // (b) clear $tag value
+       /**
+        * 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)
+        */
        private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
                $tag = ltrim( $tag );
-               if( $tag != '' ) {
-                       if( $tagType == 0 && $lastCh != '/' ) {
+               if ( $tag != '' ) {
+                       if ( $tagType == 0 && $lastCh != '/' ) {
                                $openTags[] = $tag; // tag opened (didn't close itself)
-                       } else if( $tagType == 1 ) {
-                               if( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
+                       } else if ( $tagType == 1 ) {
+                               if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
                                        array_pop( $openTags ); // tag closed
                                }
                        }
@@ -2541,7 +2697,7 @@ class Language {
 
        /**
         * Checks that convertPlural was given an array and pads it to requested
-        * amound of forms by copying the last one.
+        * amount of forms by copying the last one.
         *
         * @param $count Integer: How many forms should there be at least
         * @param $forms Array of forms given to convertPlural
@@ -2555,28 +2711,33 @@ class Language {
        }
 
        /**
-        * For translating of expiry times
-        * @param $str String: the validated block time in English
-        * @return Somehow translated block time
+        * 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).
+        * @param $str String: the validated block duration in English
+        * @return Somehow translated block duration
         * @see LanguageFi.php for example implementation
         */
        function translateBlockExpiry( $str ) {
-               $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
-
-               if ( $scBlockExpiryOptions == '-' ) {
-                       return $str;
-               }
-
-               foreach ( explode( ',', $scBlockExpiryOptions) as $option ) {
-                       if ( strpos( $option, ':' ) === false ) {
-                               continue;
-                       }
-                       list( $show, $value ) = explode( ':', $option );
+               $duration = SpecialBlock::getSuggestedDurations( $this );
+               foreach( $duration as $show => $value ){
                        if ( strcmp( $str, $value ) == 0 ) {
                                return htmlspecialchars( trim( $show ) );
                        }
                }
 
+               // Since usually only infinite or indefinite is only on list, so try
+               // equivalents if still here.
+               $indefs = array( 'infinite', 'infinity', 'indefinite' );
+               if ( in_array( $str, $indefs ) ) {
+                       foreach( $indefs as $val ) {
+                               $show = array_search( $val, $duration, true );
+                               if ( $show !== false ) {
+                                       return htmlspecialchars( trim( $show ) );
+                               }
+                       }
+               }
+               // If all else fails, return the original string.
                return $str;
        }
 
@@ -2642,7 +2803,7 @@ class Language {
        }
 
        /**
-        * Get the list of variants supported by this langauge
+        * Get the list of variants supported by this language
         * see sample implementation in LanguageZh.php
         *
         * @return array an array of language codes
@@ -2651,8 +2812,16 @@ class Language {
                return $this->mConverter->getVariants();
        }
 
-       function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
-               return $this->mConverter->getPreferredVariant( $fromUser, $fromHeader );
+       function getPreferredVariant() {
+               return $this->mConverter->getPreferredVariant();
+       }
+
+       function getDefaultVariant() {
+               return $this->mConverter->getDefaultVariant();
+       }
+
+       function getURLVariant() {
+               return $this->mConverter->getURLVariant();
        }
 
        /**
@@ -2675,6 +2844,8 @@ class Language {
         * If a language supports multiple variants, converts text
         * into an array of all possible variants of the text:
         *  'variant' => text in that variant
+        *
+        * @deprecated since 1.17 Use autoConvertToAllVariants()
         */
        function convertLinkToAllVariants( $text ) {
                return $this->mConverter->convertLinkToAllVariants( $text );
@@ -2746,6 +2917,13 @@ class Language {
         * @return string $prefix . $mangledCode . $suffix
         */
        static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
+               // Protect against path traversal
+               if ( !Language::isValidCode( $code )
+                       || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
+               {
+                       throw new MWException( "Invalid language code \"$code\"" );
+               }
+
                return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
        }
 
@@ -2836,25 +3014,57 @@ class Language {
                        throw new MWException(
                                "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
                }
-               extract( $arr );
+               $wikiUpperChars = $arr['wikiUpperChars'];
+               $wikiLowerChars = $arr['wikiLowerChars'];
                wfProfileOut( __METHOD__ );
                return array( $wikiUpperChars, $wikiLowerChars );
        }
 
+       /**
+        * Decode an expiry (block, protection, etc) which has come from the DB
+        *
+        * @param $expiry String: Database expiry String
+        * @param $format Bool|Int true to process using language functions, or TS_ constant
+        *     to return the expiry in a given timestamp
+        * @return String
+        */
+       public function formatExpiry( $expiry, $format = true ) {
+               static $infinity, $infinityMsg;
+               if( $infinity === null ){
+                       $infinityMsg = wfMessage( 'infiniteblock' );
+                       $infinity = wfGetDB( DB_SLAVE )->getInfinity();
+               }
+
+               if ( $expiry == '' || $expiry == $infinity ) {
+                       return $format === true
+                               ? $infinityMsg
+                               : $infinity;
+               } else {
+                       return $format === true
+                               ? $this->timeanddate( $expiry )
+                               : wfTimestamp( $format, $expiry );
+               }
+       }
+
+       /**
+        * @todo Document
+        * @param  $seconds String
+        * @return string
+        */
        function formatTimePeriod( $seconds ) {
-               if ( $seconds < 10 ) {
-                       return $this->formatNum( sprintf( "%.1f", $seconds ) ) . ' ' . $this->getMessageFromDB( 'seconds-abbrev' );
-               } elseif ( $seconds < 60 ) {
-                       return $this->formatNum( round( $seconds ) ) . ' ' . $this->getMessageFromDB( 'seconds-abbrev' );
-               } elseif ( $seconds < 3600 ) {
+               if ( round( $seconds * 10 ) < 100 ) {
+                       return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
+               } elseif ( round( $seconds ) < 60 ) {
+                       return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
+               } elseif ( round( $seconds ) < 3600 ) {
                        $minutes = floor( $seconds / 60 );
                        $secondsPart = round( fmod( $seconds, 60 ) );
                        if ( $secondsPart == 60 ) {
                                $secondsPart = 0;
                                $minutes++;
                        }
-                       return $this->formatNum( $minutes ) . ' ' . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
-                               $this->formatNum( $secondsPart ) . ' ' . $this->getMessageFromDB( 'seconds-abbrev' );
+                       return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
+                               $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
                } else {
                        $hours = floor( $seconds / 3600 );
                        $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
@@ -2867,9 +3077,9 @@ 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' );
+                       return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
+                               $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
+                               $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
                }
        }
 
@@ -2898,13 +3108,13 @@ class Language {
        function formatSize( $size ) {
                // For small sizes no decimal places necessary
                $round = 0;
-               if( $size > 1024 ) {
+               if ( $size > 1024 ) {
                        $size = $size / 1024;
-                       if( $size > 1024 ) {
+                       if ( $size > 1024 ) {
                                $size = $size / 1024;
                                // For MB and bigger two decimal places are smarter
                                $round = 2;
-                               if( $size > 1024 ) {
+                               if ( $size > 1024 ) {
                                        $size = $size / 1024;
                                        $msg = 'size-gigabytes';
                                } else {