Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.94% covered (warning)
77.94%
53 / 68
66.67% covered (warning)
66.67%
6 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageCode
79.10% covered (warning)
79.10%
53 / 67
66.67% covered (warning)
66.67%
6 / 9
32.17
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDeprecatedCodeMapping
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getNonstandardLanguageCodeMapping
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 replaceDeprecatedCodes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 bcp47
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
9
 bcp47ToInternal
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
5.20
 normalizeNonstandardCodeAndWarn
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 isWellFormedLanguageTag
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Language;
8
9use Wikimedia\Bcp47Code\Bcp47Code;
10use Wikimedia\Bcp47Code\Bcp47CodeValue;
11
12/**
13 * Methods for dealing with language codes.
14 *
15 * @since 1.29
16 * @ingroup Language
17 */
18class LanguageCode {
19    /**
20     * @unstable
21     * @since 1.43
22     */
23    public function __construct( private readonly string $code ) {
24    }
25
26    /**
27     * @since 1.43
28     */
29    public function toString(): string {
30        return $this->code;
31    }
32
33    /**
34     * Mapping of deprecated language codes that were used in previous
35     * versions of MediaWiki to up-to-date, current language codes.
36     * These may or may not be valid BCP 47 codes; they are included here
37     * because MediaWiki renamed these particular codes at some point.
38     *
39     * @var array Mapping from deprecated MediaWiki-internal language code
40     *   to replacement MediaWiki-internal language code.
41     *
42     * @see https://meta.wikimedia.org/wiki/Special_language_codes
43     * @phpcs-require-sorted-array
44     */
45    private const DEPRECATED_LANGUAGE_CODE_MAPPING = [
46        // Note that als is actually a valid ISO 639 code (Tosk Albanian), but it
47        // was previously used in MediaWiki for Alsatian, which comes under gsw
48        'als' => 'gsw', // T25215
49        'bat-smg' => 'sgs', // T27522
50        'be-x-old' => 'be-tarask', // T11823
51        'fiu-vro' => 'vro', // T31186
52        'roa-rup' => 'rup', // T17988
53        'zh-classical' => 'lzh', // T30443
54        'zh-min-nan' => 'nan', // T30442
55        'zh-yue' => 'yue', // T30441
56    ];
57
58    /**
59     * Mapping of non-standard language codes used in MediaWiki to
60     * standardized BCP 47 codes. These are not deprecated (yet?):
61     * IANA may eventually recognize the subtag, in which case the `-x-`
62     * infix could be removed, or else we could rename the code in
63     * MediaWiki, in which case they'd move up to the above mapping
64     * of deprecated codes.
65     *
66     * As a rule, we preserve all distinctions made by MediaWiki
67     * internally. For example, `de-formal` becomes `de-x-formal`
68     * instead of just `de` because MediaWiki distinguishes `de-formal`
69     * from `de` (for example, for interface translations). Similarly,
70     * BCP 47 indicates that `kk-Cyrl` SHOULD not be used because it
71     * "typically does not add information", but in our case MediaWiki
72     * LanguageConverter distinguishes `kk` (render content in a mix of
73     * Kurdish variants) from `kk-Cyrl` (convert content to be uniformly
74     * Cyrillic). As the BCP 47 requirement is a SHOULD not a MUST,
75     * `kk-Cyrl` is a valid code, although some validators may emit
76     * a warning note.
77     *
78     * @var array Mapping from nonstandard MediaWiki-internal codes to
79     *   BCP 47 codes
80     *
81     * @see https://meta.wikimedia.org/wiki/Special_language_codes
82     * @see https://phabricator.wikimedia.org/T125073
83     */
84    private const NON_STANDARD_LANGUAGE_CODE_MAPPING = [
85        // All codes returned by LanguageNameUtils::getLanguageNames() validated
86        // against IANA registry at
87        //   https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
88        // with help of validator at
89        //   http://schneegans.de/lv/
90        'cbk-zam' => 'cbk', // T124657
91        'de-formal' => 'de-x-formal',
92        'eml' => 'egl', // T36217
93        'en-rtl' => 'en-x-rtl',
94        'es-formal' => 'es-x-formal',
95        'hu-formal' => 'hu-x-formal',
96        'map-bms' => 'jv-x-bms', // [[en:Banyumasan_dialect]] T125073
97        'mo' => 'ro-Cyrl-MD', // T125073
98        'nrm' => 'nrf', // [[en:Norman_language]] T25216
99        'nl-informal' => 'nl-x-informal',
100        'roa-tara' => 'nap-x-tara', // [[en:Tarantino_dialect]]
101        'simple' => 'en-simple',
102        'sr-ec' => 'sr-Cyrl', // T117845
103        'sr-el' => 'sr-Latn', // T117845
104
105        // Although these next codes aren't *wrong* per se, including
106        // both the script and the country code helps compatibility with
107        // other BCP 47 users. Note that MW also uses
108        // `kk-Arab`/`kk-Cyrl`/`kk-Latn`, `zh-Hans`/`zh-Hant`,
109        // without a country code, and those should be left alone.
110        // `kk` has the Suppress-Script: Cyrl field, so `kk-KZ` won't be mapped
111        // to `kk-Cyrl-KZ`.
112        // (See getVariantsFallbacks() in KkConverter.php for Arab/Cyrl/Latn id.)
113        // (See getVariantsFallbacks() in ZhConverter.php for Hans/Hant id.)
114        'crh-ro' => 'crh-Latn-RO',
115        'kk-cn' => 'kk-Arab-CN',
116        'kk-tr' => 'kk-Latn-TR',
117        'zh-cn' => 'zh-Hans-CN',
118        'zh-sg' => 'zh-Hans-SG',
119        'zh-my' => 'zh-Hans-MY',
120        'zh-tw' => 'zh-Hant-TW',
121        'zh-hk' => 'zh-Hant-HK',
122        'zh-mo' => 'zh-Hant-MO',
123    ];
124
125    /**
126     * Returns a mapping of deprecated language codes that were used in previous
127     * versions of MediaWiki to up-to-date, current language codes.
128     *
129     * This array is merged into $wgDummyLanguageCodes in
130     * SetupDynamicConfig.php, along with the fake language codes
131     * 'qqq' and 'qqx', which are used internally by MediaWiki's
132     * localisation system.
133     *
134     * @return string[]
135     *
136     * @since 1.29
137     */
138    public static function getDeprecatedCodeMapping() {
139        return self::DEPRECATED_LANGUAGE_CODE_MAPPING;
140    }
141
142    /**
143     * Returns a mapping of non-standard language codes used by
144     * (current and previous version of) MediaWiki, mapped to standard
145     * BCP 47 names.
146     *
147     * This array is exported to JavaScript to ensure
148     * mediawiki.language.bcp47 stays in sync with LanguageCode::bcp47().
149     *
150     * @return string[]
151     *
152     * @since 1.32
153     */
154    public static function getNonstandardLanguageCodeMapping() {
155        static $result = [];
156        if ( $result ) {
157            return $result;
158        }
159        foreach ( self::DEPRECATED_LANGUAGE_CODE_MAPPING as $code => $ignore ) {
160            $result[$code] = self::bcp47( $code );
161        }
162        foreach ( self::NON_STANDARD_LANGUAGE_CODE_MAPPING as $code => $ignore ) {
163            $result[$code] = self::bcp47( $code );
164        }
165        return $result;
166    }
167
168    /**
169     * Replace deprecated language codes that were used in previous
170     * versions of MediaWiki to up-to-date, current language codes.
171     * Any other code will be returned unchanged.
172     *
173     * @param string $code Old language code
174     * @return string New language code
175     *
176     * @since 1.30
177     */
178    public static function replaceDeprecatedCodes( $code ) {
179        return self::DEPRECATED_LANGUAGE_CODE_MAPPING[$code] ?? $code;
180    }
181
182    /**
183     * Get the normalised IANA language tag
184     * See unit test for examples.
185     * See mediawiki.language.bcp47 for the JavaScript implementation.
186     *
187     * @param string $code The language code.
188     * @return string A language code complying with BCP 47 standards.
189     *
190     * @since 1.31
191     */
192    public static function bcp47( $code ) {
193        $code = self::replaceDeprecatedCodes( strtolower( $code ) );
194        if ( isset( self::NON_STANDARD_LANGUAGE_CODE_MAPPING[$code] ) ) {
195            $code = self::NON_STANDARD_LANGUAGE_CODE_MAPPING[$code];
196        }
197        $codeSegment = explode( '-', $code );
198        $codeBCP = [];
199        foreach ( $codeSegment as $segNo => $seg ) {
200            // when the previous segment is x, it is a private segment and should be lc
201            if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
202                $codeBCP[$segNo] = strtolower( $seg );
203            // ISO 3166 country code
204            } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
205                $codeBCP[$segNo] = strtoupper( $seg );
206            // ISO 15924 script code
207            } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
208                $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
209            // Use lowercase for other cases
210            } else {
211                $codeBCP[$segNo] = strtolower( $seg );
212            }
213        }
214        return implode( '-', $codeBCP );
215    }
216
217    /**
218     * Convert standardized BCP 47 codes to the internal names used
219     * by MediaWiki and returned by Language::getCode(). This function
220     * should be the inverse of LanguageCode::bcp47(). Note that BCP 47
221     * explicitly states that language codes are case-insensitive.
222     *
223     * Since LanguageFactory::getLanguage() is pretty generous about
224     * accepting aliases (as long as they are lowercased), this function
225     * should be equivalent to:
226     *   LanguageFactory::getLanguage(strtolower($code))->getCode()
227     * but (a) better describes the caller's intention, and (b) should
228     * be much more efficient in practice.
229     *
230     * @param string|Bcp47Code $code The standard BCP-47 language code
231     * @return string A MediaWiki-internal code, as returned, for example, by
232     *    Language::getCode()
233     * @since 1.40
234     */
235    public static function bcp47ToInternal( $code ): string {
236        if ( $code instanceof Language ) {
237            return $code->getCode();
238        }
239        if ( $code instanceof Bcp47Code ) {
240            $code = $code->toBcp47Code();
241        }
242        static $invertedLookup = [];
243        if ( !$invertedLookup ) {
244            // There should never be two different entries in
245            // NON_STANDARD_LANGUAGE_CODE_MAPPING that map *different*
246            // internal codes to the same external BCP-47 code.  That is,
247            // BCP-47 should preserve all the information from the internal
248            // code (discussed further above)[*].  But note the converse isn't
249            // true: multiple BCP-47 codes can alias to the same internal code:
250            //     BCP-47      internal
251            //   zh-Hans-CN => zh-cn    (in NON_STANDARD_LANGUAGE_CODE_MAPPING)
252            //   zh-Hans    => zh-hans  (not in " )
253            //   zh-CN      => zh-cn    (not in " )
254            //
255            // [*] eml/egl are the "exception that proves the rule": `egl` *is*
256            // (prematurely?) defined as an internal code, but only
257            // eml.wikipedia.org exists, and it defines its language as `eml`;
258            // for internal purposes `egl` should map back into `eml` until
259            // `eml` is deprecated (aka an `eml => egl` entry is added to
260            // DEPRECATED_LANGUAGE_CODE_MAPPING): T36217.
261            foreach ( self::NON_STANDARD_LANGUAGE_CODE_MAPPING as $internal => $bcp47 ) {
262                $invertedLookup[strtolower( $bcp47 )] = $internal;
263            }
264            // We deliberately do *not* use DEPRECATED_LANGUAGE_CODE_MAPPING
265            // here: deprecated codes are no longer valid mediawiki internal
266            // codes, and we should never return them.
267        }
268        // Internal codes are all lowercase.  This also achieves
269        // case-insensitivity in the lookup.
270        $code = strtolower( $code );
271        return $invertedLookup[$code] ?? $code;
272    }
273
274    /**
275     * We want to eventually require valid BCP-47 codes on HTTP and HTML
276     * APIs (where the standards require it).  This will "prefer" to
277     * interpret the given $code as BCP-47, but if a mediawiki internal
278     * code is provided, it will map it to the proper BCP-47 code.  We
279     * don't emit a logged warning on this path yet, but we intend to
280     * in the future.
281     *
282     * @param string $code A "language code" provided from an HTTP or HTML
283     *   API, presumed to be BCP-47
284     * @return Bcp47Code An "actual" BCP-47 code
285     * @internal
286     */
287    public static function normalizeNonstandardCodeAndWarn( string $code ): Bcp47Code {
288        $compatMap = self::getNonstandardLanguageCodeMapping();
289        if ( isset( $compatMap[strtolower( $code )] ) ) {
290            // Backward compatibility, since clients may have been
291            // sending us non-standards-compliant
292            // "mediawiki internal language codes"; eventually we'll
293            // emit a logged warning here.
294            $code = $compatMap[strtolower( $code )];
295        }
296        return new Bcp47CodeValue( $code );
297    }
298
299    /**
300     * Returns true if a language code string is a well-formed language tag
301     * according to RFC 5646.
302     * This function only checks well-formedness; it doesn't check that
303     * language, script or variant codes actually exist in the repositories.
304     *
305     * Based on regexes by Mark Davis of the Unicode Consortium:
306     * https://github.com/unicode-org/icu/blob/37e295627156bc334e1f1e88807025fac984da0e/icu4j/main/tests/translit/src/com/ibm/icu/dev/test/translit/langtagRegex.txt
307     *
308     * @param string $code
309     * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
310     *
311     * @return bool
312     * @since 1.39
313     */
314    public static function isWellFormedLanguageTag( string $code, bool $lenient = false ): bool {
315        $alpha = '[a-z]';
316        $digit = '[0-9]';
317        $alphanum = '[a-z0-9]';
318        $x = 'x'; # private use singleton
319        $singleton = '[a-wy-z]'; # other singleton
320        $s = $lenient ? '[-_]' : '-';
321
322        $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
323        $script = "$alpha{4}"; # ISO 15924
324        $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
325        $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
326        $extension = "$singleton(?:$s$alphanum{2,8})+";
327        $privateUse = "$x(?:$s$alphanum{1,8})+";
328
329        # Define certain legacy language tags (marked as “Type: grandfathered” in BCP 47),
330        # since otherwise the regex is pretty useless.
331        # Since these are limited, this is safe even later changes to the registry --
332        # the only oddity is that it might change the type of the tag, and thus
333        # the results from the capturing groups.
334        # https://www.iana.org/assignments/language-subtag-registry
335
336        $legacy = "en{$s}gb{$s}oed"
337            . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
338            . "|no{$s}(?:bok|nyn)"
339            . "|sgn{$s}(?:be{$s}(?:fr|nl)|ch{$s}de)"
340            . "|zh{$s}min{$s}nan";
341
342        $variantList = "$variant(?:$s$variant)*";
343        $extensionList = "$extension(?:$s$extension)*";
344
345        $langtag = "(?:($language)"
346            . "(?:$s$script)?"
347            . "(?:$s$region)?"
348            . "(?:$s$variantList)?"
349            . "(?:$s$extensionList)?"
350            . "(?:$s$privateUse)?)";
351
352        # Here is the final breakdown, with capturing groups for each of these components
353        # The variants, extensions, legacy, and private-use may have interior '-'
354
355        $root = "^(?:$langtag|$privateUse|$legacy)$";
356
357        return preg_match( "/$root/i", $code );
358    }
359}
360
361/** @deprecated class alias since 1.43 */
362class_alias( LanguageCode::class, 'LanguageCode' );