Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.73% covered (success)
98.73%
78 / 79
90.91% covered (success)
90.91%
10 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageNameUtils
98.73% covered (success)
98.73%
78 / 79
90.91% covered (success)
90.91%
10 / 11
41
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 isSupportedLanguage
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 isValidCode
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 isValidBuiltInCode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isKnownLanguageTag
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 getLanguageNames
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 getLanguageNamesUncached
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
15
 getLanguageName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getFileName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getMessagesFileName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getJsonMessagesFileName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21namespace MediaWiki\Languages;
22
23use BagOStuff;
24use HashBagOStuff;
25use InvalidArgumentException;
26use LanguageCode;
27use MediaWiki\Config\ServiceOptions;
28use MediaWiki\HookContainer\HookContainer;
29use MediaWiki\HookContainer\HookRunner;
30use MediaWiki\MainConfigNames;
31use MediaWiki\Title\MediaWikiTitleCodec;
32
33/**
34 * A service that provides utilities to do with language names and codes.
35 *
36 * See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more information.
37 *
38 * @since 1.34
39 * @ingroup Language
40 */
41class LanguageNameUtils {
42    /**
43     * Return autonyms in getLanguageName(s).
44     */
45    public const AUTONYMS = null;
46
47    /**
48     * Return all known languages in getLanguageName(s).
49     */
50    public const ALL = 'all';
51
52    /**
53     * Return in getLanguageName(s) only the languages that are defined by MediaWiki.
54     */
55    public const DEFINED = 'mw';
56
57    /**
58     * Return in getLanguageName(s) only the languages for which we have at least some localisation.
59     */
60    public const SUPPORTED = 'mwfile';
61
62    /** @var ServiceOptions */
63    private $options;
64
65    /**
66     * Cache for language names
67     * @var HashBagOStuff|null
68     */
69    private $languageNameCache;
70
71    /**
72     * Cache for validity of language codes
73     * @var array
74     */
75    private $validCodeCache = [];
76
77    /**
78     * @internal For use by ServiceWiring
79     */
80    public const CONSTRUCTOR_OPTIONS = [
81        MainConfigNames::ExtraLanguageNames,
82        MainConfigNames::UsePigLatinVariant,
83        MainConfigNames::UseXssLanguage,
84    ];
85
86    /** @var HookRunner */
87    private $hookRunner;
88
89    /**
90     * @param ServiceOptions $options
91     * @param HookContainer $hookContainer
92     */
93    public function __construct( ServiceOptions $options, HookContainer $hookContainer ) {
94        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
95        $this->options = $options;
96        $this->hookRunner = new HookRunner( $hookContainer );
97    }
98
99    /**
100     * Checks whether any localisation is available for that language tag in MediaWiki
101     * (MessagesXx.php or xx.json exists).
102     *
103     * @param string $code Language tag (in lower case)
104     * @return bool Whether language is supported
105     */
106    public function isSupportedLanguage( string $code ): bool {
107        if ( !$this->isValidBuiltInCode( $code ) ) {
108            return false;
109        }
110
111        if ( $code === 'qqq' ) {
112            // Special code for internal use, not supported even though there is a qqq.json
113            return false;
114        }
115        if (
116            $code === 'en-x-piglatin' &&
117            !$this->options->get( MainConfigNames::UsePigLatinVariant )
118        ) {
119            // Suppress Pig Latin unless explicitly enabled.
120            return false;
121        }
122
123        return is_readable( $this->getMessagesFileName( $code ) ) ||
124            is_readable( $this->getJsonMessagesFileName( $code ) );
125    }
126
127    /**
128     * Returns true if a language code string is of a valid form, whether it exists.
129     * This includes codes which are used solely for customisation via the MediaWiki namespace.
130     *
131     * @param string $code
132     *
133     * @return bool False if the language code contains dangerous characters, e.g, HTML special
134     *  characters or characters that are illegal in MediaWiki titles.
135     */
136    public function isValidCode( string $code ): bool {
137        if ( !isset( $this->validCodeCache[$code] ) ) {
138            // People think language codes are HTML-safe, so enforce it. Ideally, we should only
139            // allow a-zA-Z0-9- but .+ and other chars are often used for {{int:}} hacks.  See bugs
140            // T39564, T39587, T38938.
141            $this->validCodeCache[$code] =
142                // Protect against path traversal
143                strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code ) &&
144                !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code ) &&
145                // libicu sets ULOC_FULLNAME_CAPACITY to 157; stay comfortably lower
146                strlen( $code ) <= 128;
147        }
148        return $this->validCodeCache[$code];
149    }
150
151    /**
152     * Returns true if a language code is of a valid form for the purposes of internal customisation
153     * of MediaWiki, via Messages*.php or *.json.
154     *
155     * @param string $code
156     * @return bool
157     */
158    public function isValidBuiltInCode( string $code ): bool {
159        return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
160    }
161
162    /**
163     * Returns true if a language code is an IETF tag known to MediaWiki.
164     *
165     * @param string $tag
166     *
167     * @return bool
168     */
169    public function isKnownLanguageTag( string $tag ): bool {
170        // Quick escape for invalid input to avoid exceptions down the line when code tries to
171        // process tags which are not valid at all.
172        if ( !$this->isValidBuiltInCode( $tag ) ) {
173            return false;
174        }
175
176        if ( isset( Data\Names::$names[$tag] ) || $this->getLanguageName( $tag, $tag ) !== '' ) {
177            return true;
178        }
179
180        return false;
181    }
182
183    /**
184     * Get an array of language names, indexed by code.
185     *
186     * @param null|string $inLanguage Code of language in which to return the names
187     *   Use self::AUTONYMS for autonyms (native names)
188     * @param string $include One of:
189     *   self::ALL All available languages
190     *   self::DEFINED Only if the language is defined in MediaWiki or wgExtraLanguageNames
191     *     (default)
192     *   self::SUPPORTED Only if the language is in self::DEFINED *and* has a message file
193     * @return array Language code => language name (sorted by key)
194     */
195    public function getLanguageNames( $inLanguage = self::AUTONYMS, $include = self::DEFINED ) {
196        if ( $inLanguage !== self::AUTONYMS ) {
197            $inLanguage = LanguageCode::replaceDeprecatedCodes( LanguageCode::bcp47ToInternal( $inLanguage ) );
198        }
199        $cacheKey = $inLanguage === self::AUTONYMS ? 'null' : $inLanguage;
200        $cacheKey .= ":$include";
201        if ( !$this->languageNameCache ) {
202            $this->languageNameCache = new HashBagOStuff( [ 'maxKeys' => 20 ] );
203        }
204
205        return $this->languageNameCache->getWithSetCallback(
206            $cacheKey,
207            BagOStuff::TTL_INDEFINITE,
208            function () use ( $inLanguage, $include ) {
209                return $this->getLanguageNamesUncached( $inLanguage, $include );
210            }
211        );
212    }
213
214    /**
215     * Uncached helper for getLanguageNames.
216     *
217     * @param null|string $inLanguage As getLanguageNames
218     * @param string $include As getLanguageNames
219     * @return array Language code => language name (sorted by key)
220     */
221    private function getLanguageNamesUncached( $inLanguage, $include ) {
222        // If passed an invalid language code to use, fallback to en
223        if ( $inLanguage !== self::AUTONYMS && !$this->isValidCode( $inLanguage ) ) {
224            $inLanguage = 'en';
225        }
226
227        $names = [];
228
229        if ( $inLanguage !== self::AUTONYMS ) {
230            # TODO: also include for self::AUTONYMS, when this code is more efficient
231            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
232            $this->hookRunner->onLanguageGetTranslatedLanguageNames( $names, $inLanguage );
233        }
234
235        $mwNames = $this->options->get( MainConfigNames::ExtraLanguageNames ) + Data\Names::$names;
236        if ( !$this->options->get( MainConfigNames::UsePigLatinVariant ) ) {
237            // Suppress Pig Latin unless explicitly enabled.
238            unset( $mwNames['en-x-piglatin'] );
239        }
240        if ( $this->options->get( MainConfigNames::UseXssLanguage ) ) {
241            $mwNames['x-xss'] = 'fake xss language (see $wgUseXssLanguage)';
242        }
243
244        foreach ( $mwNames as $mwCode => $mwName ) {
245            # - Prefer own MediaWiki native name when not using the hook
246            # - For other names just add if not added through the hook
247            if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
248                $names[$mwCode] = $mwName;
249            }
250        }
251
252        if ( $include === self::ALL ) {
253            ksort( $names );
254            return $names;
255        }
256
257        $returnMw = [];
258        $coreCodes = array_keys( $mwNames );
259        foreach ( $coreCodes as $coreCode ) {
260            $returnMw[$coreCode] = $names[$coreCode];
261        }
262
263        if ( $include === self::SUPPORTED ) {
264            $namesMwFile = [];
265            # We do this using a foreach over the codes instead of a directory loop so that messages
266            # files in extensions will work correctly.
267            foreach ( $returnMw as $code => $value ) {
268                if ( is_readable( $this->getMessagesFileName( $code ) ) ||
269                    is_readable( $this->getJsonMessagesFileName( $code ) )
270                ) {
271                    $namesMwFile[$code] = $names[$code];
272                }
273            }
274
275            ksort( $namesMwFile );
276            return $namesMwFile;
277        }
278
279        ksort( $returnMw );
280        # self::DEFINED option; default if it's not one of the other two options
281        # (self::ALL/self::SUPPORTED)
282        return $returnMw;
283    }
284
285    /**
286     * @param string $code The code of the language for which to get the name
287     * @param null|string $inLanguage Code of language in which to return the name (self::AUTONYMS
288     *   for autonyms)
289     * @param string $include See getLanguageNames(), except this function defaults to self::ALL instead of
290     *   self::DEFINED
291     * @return string Language name or empty
292     */
293    public function getLanguageName( $code, $inLanguage = self::AUTONYMS, $include = self::ALL ) {
294        $code = LanguageCode::replaceDeprecatedCodes( LanguageCode::bcp47ToInternal( $code ) );
295        $array = $this->getLanguageNames( $inLanguage, $include );
296        return $array[$code] ?? '';
297    }
298
299    /**
300     * Get the name of a file for a certain language code.
301     *
302     * @param string $prefix Prepend this to the filename
303     * @param string $code Language code
304     * @param string $suffix Append this to the filename
305     * @return string $prefix . $mangledCode . $suffix
306     */
307    public function getFileName( $prefix, $code, $suffix = '.php' ) {
308        if ( !$this->isValidBuiltInCode( $code ) ) {
309            throw new InvalidArgumentException( "Invalid language code \"$code\"" );
310        }
311
312        return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
313    }
314
315    /**
316     * @param string $code
317     * @return string
318     */
319    public function getMessagesFileName( $code ) {
320        global $IP;
321        $file = $this->getFileName( "$IP/languages/messages/Messages", $code, '.php' );
322        $this->hookRunner->onLanguage__getMessagesFileName( $code, $file );
323        return $file;
324    }
325
326    /**
327     * @param string $code
328     * @return string
329     */
330    public function getJsonMessagesFileName( $code ) {
331        global $IP;
332
333        if ( !$this->isValidBuiltInCode( $code ) ) {
334            throw new InvalidArgumentException( "Invalid language code \"$code\"" );
335        }
336
337        return "$IP/languages/i18n/$code.json";
338    }
339}