Localisation updates for core and extension messages from translatewiki.net (2011...
[lhc/web/wiklou.git] / languages / Language.php
index 3056143..76d8fd9 100644 (file)
@@ -1,11 +1,15 @@
 <?php
 /**
- * @defgroup Language Language
+ * Internationalisation code
  *
  * @file
  * @ingroup Language
  */
 
+/**
+ * @defgroup Language Language
+ */
+
 if ( !defined( 'MEDIAWIKI' ) ) {
        echo "This file is part of MediaWiki, it is not a valid entry point.\n";
        exit( 1 );
@@ -34,19 +38,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 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; }
 }
 
@@ -126,6 +132,8 @@ 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] ) ) {
@@ -140,10 +148,18 @@ 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 ) ) {
+                       throw new MWException( "Invalid language code \"$code\"" );
+               }
+
                if ( $code == 'en' ) {
                        $class = 'Language';
                } else {
@@ -173,6 +189,14 @@ class Language {
                return $lang;
        }
 
+       /**
+        * Returns true if a language code string is of a valid form, whether or 
+        * not it exists.
+        */
+       public static function isValidCode( $code ) {
+               return strcspn( $code, "/\\\000" ) === strlen( $code );
+       }
+
        /**
         * Get the LocalisationCache instance
         */
@@ -241,12 +265,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 ) {
@@ -256,13 +280,12 @@ class Language {
                                $this->namespaceNames[NS_PROJECT_TALK] =
                                        $this->fixVariableInNamespace( $talk );
                        }
-                       
+
                        # Sometimes a language will be localised but not actually exist on this wiki.
-                       $validNamespaces = MWNamespace::getValidNamespaces();
                        foreach( $this->namespaceNames as $key => $text ) {
-                               if ( ! in_array( $key, $validNamespaces ) ) {
-                                       unset( $this->namespaceNames[$key] );
-                               }
+                               if ( !isset( $validNamespaces[$key] ) ) {
+                                       unset( $this->namespaceNames[$key] );
+                               }
                        }
 
                        # The above mixing may leave namespaces out of canonical order.
@@ -315,6 +338,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
@@ -343,6 +389,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;
@@ -482,6 +536,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.
         *
@@ -615,9 +688,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
@@ -667,7 +739,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 ) {
@@ -842,18 +913,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 );
@@ -981,7 +1045,6 @@ class Language {
                                } else {
                                        $s .= $this->formatNum( $num, true );
                                }
-                               $num = false;
                        }
                }
                return $s;
@@ -1372,7 +1435,7 @@ class Language {
                return $s;
        }
 
-       /**
+       /**
         * Hebrew Gematria number formatting up to 9999
         */
        static function hebrewNumeral( $num ) {
@@ -1502,6 +1565,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 );
                }
@@ -1520,6 +1584,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 );
                }
@@ -1597,18 +1662,24 @@ 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 $this->uc( $str, true );
                }
        }
 
+       /**
+        * Convert a string to uppercase
+        */
        function uc( $str, $first = false ) {
                if ( function_exists( 'mb_strtoupper' ) ) {
                        if ( $first ) {
@@ -1762,7 +1833,7 @@ class Language {
                }
 
                $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
-                '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
+                               '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
                if ( $isutf8 ) {
                        return $s;
                }
@@ -2045,14 +2116,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 {
@@ -2329,8 +2406,8 @@ class Language {
                        # 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 ) )
+                         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];
@@ -2363,7 +2440,7 @@ class Language {
         *
         * Note: tries to fix broken HTML with MWTidy
         *
-        * @param string $text String to truncate
+        * @param string $text HTML string to truncate
         * @param int $length (zero/positive) Maximum length (excluding ellipses)
         * @param string $ellipsis String to append to the truncated text
         * @returns string
@@ -2385,8 +2462,8 @@ class Language {
                $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();
+               $tag = $ret = '';
+               $openTags = array(); // open tag stack
                $textLen = strlen( $text );
                for ( $pos = 0; $pos < $textLen; ++$pos ) {
                        $ch = $text[$pos];
@@ -2455,7 +2532,8 @@ class Language {
                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
                }
@@ -2473,9 +2551,15 @@ class Language {
                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 != '' ) {
@@ -2655,7 +2739,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
@@ -2664,8 +2748,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();
        }
 
        /**
@@ -2688,6 +2780,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 Use autoConvertToAllVariants()
         */
        function convertLinkToAllVariants( $text ) {
                return $this->mConverter->convertLinkToAllVariants( $text );
@@ -2759,6 +2853,11 @@ class Language {
         * @return string $prefix . $mangledCode . $suffix
         */
        static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
+               // Protect against path traversal
+               if ( !Language::isValidCode( $code ) ) {
+                       throw new MWException( "Invalid language code \"$code\"" );
+               }
+               
                return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
        }
 
@@ -2849,17 +2948,18 @@ 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 );
        }
 
        function formatTimePeriod( $seconds ) {
-               if ( $seconds < 10 ) {
-                       return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
-               } elseif ( $seconds < 60 ) {
+               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 ( $seconds < 3600 ) {
+               } elseif ( round( $seconds ) < 3600 ) {
                        $minutes = floor( $seconds / 60 );
                        $secondsPart = round( fmod( $seconds, 60 ) );
                        if ( $secondsPart == 60 ) {
@@ -2940,63 +3040,4 @@ class Language {
        function getConvRuleTitle() {
                return $this->mConverter->getConvRuleTitle();
        }
-
-       /**
-        * Given a string, convert it to a (hopefully short) key that can be used
-        * for efficient sorting.  A binary sort according to the sortkeys
-        * corresponds to a logical sort of the corresponding strings.  Current
-        * code expects that a null character should sort before all others, but
-        * has no other particular expectations (and that one can be changed if
-        * necessary).
-        *
-        * @param string $string UTF-8 string
-        * @return string Binary sortkey
-        */
-       public function convertToSortkey( $string ) {
-               # Fake function for now
-               return strtoupper( $string );
-       }
-
-       /**
-        * Does it make sense for lists to be split up into sections based on their
-        * first letter?  Logogram-based scripts probably want to return false.
-        *
-        * TODO: Use this in CategoryPage.php.
-        *
-        * @return boolean
-        */
-       public function usesFirstLettersInLists() {
-               return true;
-       }
-
-       /**
-        * Given a string, return the logical "first letter" to be used for
-        * grouping on category pages and so on.  This has to be coordinated
-        * carefully with convertToSortkey(), or else the sorted list might jump
-        * back and forth between the same "initial letters" or other pathological
-        * behavior.  For instance, if you just return the first character, but "a"
-        * sorts the same as "A" based on convertToSortkey(), then you might get a
-        * list like
-        *
-        * == A ==
-        * * [[Aardvark]]
-        *
-        * == a ==
-        * * [[antelope]]
-        *
-        * == A ==
-        * * [[Ape]]
-        *
-        * etc., assuming for the sake of argument that $wgCapitalLinks is false.
-        * Obviously, this is ignored if usesFirstLettersInLists() is false.
-        *
-        * @param string $string UTF-8 string
-        * @return string UTF-8 string corresponding to the first letter of input
-        */
-       public function firstLetterForLists( $string ) {
-               if ( $string[0] == "\0" ) {
-                       $string = substr( $string, 1 );
-               }
-               return strtoupper( $this->firstChar( $string ) );
-       }
 }