Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.38% covered (warning)
50.38%
262 / 520
26.09% covered (danger)
26.09%
12 / 46
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageConverter
50.48% covered (warning)
50.48%
262 / 519
26.09% covered (danger)
26.09%
12 / 46
4479.54
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
 getMainCode
n/a
0 / 0
n/a
0 / 0
0
 getStaticDefaultVariant
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getLanguageVariants
n/a
0 / 0
n/a
0 / 0
0
 getVariantsFallbacks
n/a
0 / 0
n/a
0 / 0
0
 getFlags
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 getAdditionalFlags
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getManualLevel
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 getAdditionalManualLevel
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDescCodeSeparator
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDescVarSeparator
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getVariantNames
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getVariants
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getVariantFallbacks
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getConvRuleTitle
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getConvRuleTitleFragment
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 getPreferredVariant
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 getDefaultVariant
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 validateVariant
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
7
 getURLVariant
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 getUserVariant
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
5.09
 getHeaderVariant
64.00% covered (warning)
64.00%
16 / 25
0.00% covered (danger)
0.00%
0 / 1
16.65
 autoConvert
55.84% covered (warning)
55.84%
43 / 77
0.00% covered (danger)
0.00%
0 / 1
50.08
 translate
33.33% covered (danger)
33.33%
5 / 15
0.00% covered (danger)
0.00%
0 / 1
5.67
 translateWithoutRomanNumbers
70.59% covered (warning)
70.59%
12 / 17
0.00% covered (danger)
0.00%
0 / 1
3.23
 autoConvertToAllVariants
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 applyManualConv
35.71% covered (danger)
35.71%
5 / 14
0.00% covered (danger)
0.00%
0 / 1
20.02
 convertSplitTitle
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 convertTitle
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 convertNamespace
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 computeNsVariantText
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
 convert
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 convertTo
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 recursiveConvertTopLevel
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
7
 recursiveConvertRule
51.28% covered (warning)
51.28%
20 / 39
0.00% covered (danger)
0.00%
0 / 1
24.99
 findVariantLink
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
420
 getExtraHashOptions
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 guessVariant
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 loadDefaultTables
n/a
0 / 0
n/a
0 / 0
0
 loadTables
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
4
 postLoadTables
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reloadTables
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 parseCachedTable
17.19% covered (danger)
17.19%
11 / 64
0.00% covered (danger)
0.00%
0 / 1
296.87
 markNoConversion
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 convertCategoryKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 updateConversionTable
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
30
 getVarSeparatorPattern
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
5.01
 hasVariants
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 hasVariant
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 convertHtml
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 * @author Zhengzhu Feng <zhengzhu@gmail.com>
6 * @author fdcn <fdcn64@gmail.com>
7 * @author shinjiman <shinjiman@gmail.com>
8 * @author PhiLiP <philip.npc@gmail.com>
9 */
10
11namespace MediaWiki\Language;
12
13use InvalidArgumentException;
14use MediaWiki\Context\RequestContext;
15use MediaWiki\Debug\DeprecationHelper;
16use MediaWiki\HookContainer\HookRunner;
17use MediaWiki\Html\Html;
18use MediaWiki\Linker\LinkTarget;
19use MediaWiki\Logger\LoggerFactory;
20use MediaWiki\MainConfigNames;
21use MediaWiki\MediaWikiServices;
22use MediaWiki\Page\PageIdentity;
23use MediaWiki\Parser\Parser;
24use MediaWiki\Parser\Sanitizer;
25use MediaWiki\Revision\RevisionRecord;
26use MediaWiki\Revision\SlotRecord;
27use MediaWiki\StubObject\StubUserLang;
28use MediaWiki\Title\Title;
29use MediaWiki\User\User;
30use RuntimeException;
31use UnexpectedValueException;
32use Wikimedia\ObjectCache\BagOStuff;
33use Wikimedia\Parsoid\DOM\Document;
34use Wikimedia\Parsoid\DOM\DocumentFragment;
35use Wikimedia\Parsoid\Utils\DOMCompat;
36use Wikimedia\ReplacementArray;
37use Wikimedia\StringUtils\StringUtils;
38
39/**
40 * Base class for multi-variant language conversion.
41 *
42 * @ingroup Language
43 */
44abstract class LanguageConverter implements ILanguageConverter {
45    use DeprecationHelper;
46
47    /**
48     * languages supporting variants
49     * @since 1.20
50     * @var string[]
51     * @phpcs-require-sorted-array
52     */
53    public static $languagesWithVariants = [
54        'ban',
55        'crh',
56        'en',
57        'gan',
58        'iu',
59        'ku',
60        'mni',
61        'sh',
62        'shi',
63        'sr',
64        'tg',
65        'tly',
66        'uz',
67        'wuu',
68        'zgh',
69        'zh',
70    ];
71
72    /**
73     * static default variant of languages supporting variants
74     * for use with DefaultOptionsLookup.php
75     * @since 1.40
76     * @var array<string,string>
77     * @phpcs-require-sorted-array
78     */
79    public static $languagesWithStaticDefaultVariant = [
80        'ban' => 'ban',
81        'crh' => 'crh',
82        'en' => 'en',
83        'gan' => 'gan',
84        'iu' => 'iu',
85        'ku' => 'ku',
86        'mni' => 'mni',
87        'sh' => 'sh-latn',
88        'shi' => 'shi',
89        'sr' => 'sr',
90        'tg' => 'tg',
91        'tly' => 'tly',
92        'uz' => 'uz',
93        'wuu' => 'wuu',
94        'zgh' => 'zgh',
95        'zh' => 'zh',
96    ];
97
98    /** @var bool */
99    private $mTablesLoaded = false;
100    /** @var ReplacementArray[] */
101    protected $mTables = [];
102    /** @var Language|StubUserLang */
103    private $mLangObj;
104
105    private string|DocumentFragment|false $mConvRuleTitle = false;
106
107    /** @var string|null */
108    private $mURLVariant;
109    /** @var string|null */
110    private $mUserVariant;
111    /** @var string|null */
112    private $mHeaderVariant;
113    /** @var int */
114    private $mMaxDepth = 10;
115    /** @var string|null */
116    private $mVarSeparatorPattern;
117
118    private const CACHE_VERSION_KEY = 'VERSION 8';
119
120    /**
121     * @param Language|StubUserLang $langobj
122     */
123    public function __construct( $langobj ) {
124        $this->mLangObj = $langobj;
125    }
126
127    /**
128     * Get the language code with converter (the "main" language code).
129     * Page language code would be the same of the language code with converter.
130     * Note that this code might not be included as one of the variant languages.
131     * @since 1.36
132     *
133     * @return string
134     */
135    abstract public function getMainCode(): string;
136
137    /**
138     * Get static default variant.
139     * For use of specify the default variant form when it different from the
140     *  default "unconverted/mixed-variant form".
141     * @since 1.40
142     *
143     * @return string
144     */
145    protected function getStaticDefaultVariant(): string {
146        $code = $this->getMainCode();
147        return self::$languagesWithStaticDefaultVariant[$code] ?? $code;
148    }
149
150    /**
151     * Get supported variants of the language.
152     * @since 1.36
153     *
154     * @return array
155     */
156    abstract protected function getLanguageVariants(): array;
157
158    /**
159     * Get language variants fallbacks.
160     * @since 1.36
161     *
162     * @return array
163     */
164    abstract public function getVariantsFallbacks(): array;
165
166    /**
167     * Get the strings that map to the flags.
168     * @since 1.36
169     *
170     * @return array
171     */
172    final public function getFlags(): array {
173        $defaultflags = [
174            // 'S' show the converted text
175            // '+' add rules for alltext
176            // 'E' the flags have an error
177            // these flags above are reserved for program
178            'A' => 'A', // add rule for convert code (all text converted)
179            'T' => 'T', // title convert
180            'R' => 'R', // raw content
181            'D' => 'D', // convert description (subclass implement)
182            '-' => '-', // remove convert (not implement)
183            'H' => 'H', // add rule for convert code (but no display in placed code)
184            'N' => 'N', // current variant name
185        ];
186        $flags = array_merge( $defaultflags, $this->getAdditionalFlags() );
187        foreach ( $this->getVariants() as $v ) {
188            $flags[$v] = $v;
189        }
190        return $flags;
191    }
192
193    /**
194     * Provides additional flags for converter. By default, it returns empty array and
195     * typically should be overridden by implementation of converter.
196     * @deprecated since 1.46. Unused except by SrConverter, which uses this
197     *  to define non-functional flags.
198     */
199    protected function getAdditionalFlags(): array {
200        return [];
201    }
202
203    /**
204     * Get manual level limit for supported variants.
205     * @since 1.36
206     *
207     * @return array
208     */
209    final public function getManualLevel() {
210        $manualLevel  = $this->getAdditionalManualLevel();
211        $result = [];
212        foreach ( $this->getVariants() as $v ) {
213            if ( array_key_exists( $v, $manualLevel ) ) {
214                $result[$v] = $manualLevel[$v];
215            } else {
216                $result[$v] = 'bidirectional';
217            }
218        }
219        return $result;
220    }
221
222    /**
223     * Provides additional flags for converter. By default, this function returns an empty array and
224     * typically should be overridden by the implementation of converter.
225     * @since 1.36
226     *
227     * @return array
228     */
229    protected function getAdditionalManualLevel(): array {
230        return [];
231    }
232
233    /**
234     * Get desc code separator. By default returns ":", can be overridden by
235     * implementation of converter.
236     * @since 1.36
237     *
238     * @return string
239     */
240    public function getDescCodeSeparator(): string {
241        return ':';
242    }
243
244    /**
245     * Get desc var separator. By default returns ";", can be overridden by
246     * implementation of converter.
247     * @since 1.36
248     *
249     * @return string
250     */
251    public function getDescVarSeparator(): string {
252        return ';';
253    }
254
255    public function getVariantNames(): array {
256        return MediaWikiServices::getInstance()
257            ->getLanguageNameUtils()
258            ->getLanguageNames();
259    }
260
261    /** @inheritDoc */
262    final public function getVariants() {
263        $disabledVariants = MediaWikiServices::getInstance()->getMainConfig()->get(
264            MainConfigNames::DisabledVariants );
265        return array_diff( $this->getLanguageVariants(), $disabledVariants );
266    }
267
268    /** @inheritDoc */
269    public function getVariantFallbacks( $variant ) {
270        return $this->getVariantsFallbacks()[$variant] ?? $this->getStaticDefaultVariant();
271    }
272
273    /** @inheritDoc */
274    public function getConvRuleTitle() {
275        $title = $this->mConvRuleTitle;
276        if ( $title instanceof DocumentFragment ) {
277            return $title->textContent;
278        }
279        return $title;
280    }
281
282    /** @inheritDoc */
283    public function getConvRuleTitleFragment( Document $ownerDocument ): ?DocumentFragment {
284        $title = $this->mConvRuleTitle;
285        if ( $title instanceof DocumentFragment || $title === false ) {
286            return $title ?: null;
287        }
288        $df = $ownerDocument->createDocumentFragment();
289        DOMCompat::replaceChildren( $df, $title );
290        return $df;
291    }
292
293    /** @inheritDoc */
294    public function getPreferredVariant() {
295        $req = $this->getURLVariant();
296
297        $services = MediaWikiServices::getInstance();
298        ( new HookRunner( $services->getHookContainer() ) )->onGetLangPreferredVariant( $req );
299
300        if ( !$req ) {
301            $user = RequestContext::getMain()->getUser();
302            // NOTE: For some calls there may not be a context user or session that is safe
303            // to use, see (T235360)
304            // Use case: During user autocreation, UserNameUtils::isUsable is called which uses interface
305            // messages for reserved usernames.
306            if ( $user->isSafeToLoad() && $user->isRegistered() ) {
307                $req = $this->getUserVariant( $user );
308            } else {
309                $req = $this->getHeaderVariant();
310            }
311        }
312
313        $defaultLanguageVariant = $services->getMainConfig()
314            ->get( MainConfigNames::DefaultLanguageVariant );
315        if ( !$req && $defaultLanguageVariant ) {
316            $req = $defaultLanguageVariant;
317        }
318
319        $req = $this->validateVariant( $req );
320
321        // This function, unlike the other get*Variant functions, is
322        // not memoized (i.e., there return value is not cached) since
323        // new information might appear during processing after this
324        // is first called.
325        return $req ?? $this->getStaticDefaultVariant();
326    }
327
328    /** @inheritDoc */
329    public function getDefaultVariant() {
330        $defaultLanguageVariant = MediaWikiServices::getInstance()->getMainConfig()->get(
331            MainConfigNames::DefaultLanguageVariant );
332
333        $req = $this->getURLVariant() ?? $this->getHeaderVariant();
334
335        if ( !$req && $defaultLanguageVariant ) {
336            $req = $this->validateVariant( $defaultLanguageVariant );
337        }
338
339        return $req ?? $this->getStaticDefaultVariant();
340    }
341
342    /** @inheritDoc */
343    public function validateVariant( $variant = null, bool $fallbackToDefault = false ) {
344        if ( $variant === null ) {
345            return $fallbackToDefault ? $this->getStaticDefaultVariant() : null;
346        }
347        // Our internal variants are always lower-case; the variant we
348        // are validating may have mixed cases.
349        $variant = LanguageCode::replaceDeprecatedCodes( strtolower( $variant ) );
350        if ( in_array( $variant, $this->getVariants() ) ) {
351            return $variant;
352        }
353        // Browsers are supposed to use BCP 47 standard in the
354        // Accept-Language header, but not all of our internal
355        // mediawiki variant codes are BCP 47.  Map BCP 47 code
356        // to our internal code.
357        foreach ( $this->getVariants() as $v ) {
358            // Case-insensitive match (BCP 47 is mixed-case)
359            if ( strtolower( LanguageCode::bcp47( $v ) ) === $variant ) {
360                return $v;
361            }
362        }
363        return $fallbackToDefault ? $this->getStaticDefaultVariant() : null;
364    }
365
366    /** @inheritDoc */
367    public function getURLVariant() {
368        if ( $this->mURLVariant ) {
369            return $this->mURLVariant;
370        }
371
372        $request = RequestContext::getMain()->getRequest();
373        // see if the preference is set in the request
374        $ret = $request->getText( 'variant' );
375
376        if ( !$ret ) {
377            $ret = $request->getVal( 'uselang' );
378        }
379
380        $this->mURLVariant = $this->validateVariant( $ret );
381        return $this->mURLVariant;
382    }
383
384    /**
385     * Determine if the user has a variant set.
386     *
387     * @param User $user
388     * @return string|null Variant if one found, null otherwise
389     */
390    protected function getUserVariant( User $user ) {
391        // This should only be called within the class after the user is known to be
392        // safe to load and logged in, but check just in case.
393        if ( !$user->isSafeToLoad() ) {
394            return null;
395        }
396
397        if ( !$this->mUserVariant ) {
398            $services = MediaWikiServices::getInstance();
399            if ( $user->isRegistered() ) {
400                // Get language variant preference from logged in users
401                if (
402                    $this->getMainCode() ===
403                    $services->getContentLanguageCode()->toString()
404                ) {
405                    $optionName = 'variant';
406                } else {
407                    $optionName = 'variant-' . $this->getMainCode();
408                }
409            } else {
410                // figure out user lang without constructing wgLang to avoid
411                // infinite recursion
412                $optionName = 'language';
413            }
414            $ret = $services->getUserOptionsLookup()->getOption( $user, $optionName );
415
416            $this->mUserVariant = $this->validateVariant( $ret );
417        }
418
419        return $this->mUserVariant;
420    }
421
422    /**
423     * Determine the language variant from the Accept-Language header.
424     *
425     * @return string|null Variant if one found, null otherwise
426     */
427    protected function getHeaderVariant() {
428        if ( $this->mHeaderVariant ) {
429            return $this->mHeaderVariant;
430        }
431
432        $request = RequestContext::getMain()->getRequest();
433        // See if some supported language variant is set in the
434        // HTTP header.
435        $languages = array_keys( $request->getAcceptLang() );
436        if ( !$languages ) {
437            return null;
438        }
439
440        $fallbackLanguages = [];
441        foreach ( $languages as $language ) {
442            $this->mHeaderVariant = $this->validateVariant( $language );
443            if ( $this->mHeaderVariant ) {
444                break;
445            }
446
447            // To see if there are fallbacks of current language.
448            // We record these fallback variants, and process
449            // them later.
450            $fallbacks = $this->getVariantFallbacks( $language );
451            if (
452                is_string( $fallbacks ) &&
453                $fallbacks !== $this->getStaticDefaultVariant()
454            ) {
455                $fallbackLanguages[] = $fallbacks;
456            } elseif ( is_array( $fallbacks ) ) {
457                $fallbackLanguages =
458                    array_merge( $fallbackLanguages, $fallbacks );
459            }
460        }
461
462        if ( !$this->mHeaderVariant ) {
463            // process fallback languages now
464            $fallback_languages = array_unique( $fallbackLanguages );
465            foreach ( $fallback_languages as $language ) {
466                $this->mHeaderVariant = $this->validateVariant( $language );
467                if ( $this->mHeaderVariant ) {
468                    break;
469                }
470            }
471        }
472
473        return $this->mHeaderVariant;
474    }
475
476    /** @inheritDoc */
477    public function autoConvert( $text, $toVariant = false ) {
478        $this->loadTables();
479
480        if ( !$toVariant ) {
481            $toVariant = $this->getPreferredVariant();
482            if ( !$toVariant ) {
483                return $text;
484            }
485        }
486
487        if ( $this->guessVariant( $text, $toVariant ) ) {
488            return $text;
489        }
490        /**
491         * We convert everything except:
492         * 1. HTML markups (anything between < and >)
493         * 2. HTML entities
494         * 3. placeholders created by the parser
495         * IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
496         * Minimize the use of backtracking where possible.
497         */
498        static $reg;
499        if ( $reg === null ) {
500            $marker = '|' . Parser::MARKER_PREFIX . '[^\x7f]++\x7f';
501
502            // this one is needed when the text is inside an HTML markup
503            $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
504
505            // Optimize for the common case where these tags have
506            // few or no children. Thus try and possessively get as much as
507            // possible, and only engage in backtracking when we hit a '<'.
508
509            // disable convert to variants between <code> tags
510            $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
511            // disable conversion of <script> tags
512            $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
513            // disable conversion of <pre> tags
514            $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
515            // disable conversion of <math> tags
516            $mathfix = '<math[^>]*+>[^<]*+(?:(?:(?!<\/math>).)[^<]*+)*+<\/math>|';
517            // disable conversion of <svg> tags
518            $svgfix = '<svg[^>]*+>[^<]*+(?:(?:(?!<\/svg>).)[^<]*+)*+<\/svg>|';
519            // The "|.*+)" at the end, is in case we missed some part of html syntax,
520            // we will fail securely (hopefully) by matching the rest of the string.
521            $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
522
523            $reg = '/' . $codefix . $scriptfix . $prefix . $mathfix . $svgfix .
524                $htmlFullTag .
525                '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
526        }
527        $startPos = 0;
528        $sourceBlob = '';
529        $literalBlob = '';
530
531        // Guard against delimiter nulls in the input
532        // (should never happen: see T159174)
533        $text = str_replace( "\000", '', $text );
534        $text = str_replace( "\004", '', $text );
535
536        $markupMatches = null;
537        $elementMatches = null;
538
539        // We add a marker (\004) at the end of text, to ensure we always match the
540        // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
541        $textWithMarker = $text . "\004";
542        while ( $startPos < strlen( $text ) ) {
543            if ( preg_match( $reg, $textWithMarker, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
544                $elementPos = $markupMatches[0][1];
545                $element = $markupMatches[0][0];
546                if ( $element === "\004" ) {
547                    // We hit the end.
548                    $elementPos = strlen( $text );
549                    $element = '';
550                } elseif ( substr( $element, -1 ) === "\004" ) {
551                    // This can sometimes happen if we have
552                    // unclosed html tags. For example,
553                    // when converting a title attribute
554                    // during a recursive call that contains
555                    // a &lt; e.g. <div title="&lt;">.
556                    $element = substr( $element, 0, -1 );
557                }
558            } else {
559                // If we hit here, then Language Converter could be tricked
560                // into doing an XSS, so we refuse to translate.
561                // If expected input manages to reach this code path,
562                // we should consider it a bug.
563                $log = LoggerFactory::getInstance( 'languageconverter' );
564                $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
565                    . ". Disabling language conversion for this page.",
566                    [
567                        "method" => __METHOD__,
568                        "variant" => $toVariant,
569                        "startOfText" => substr( $text, 0, 500 )
570                    ]
571                );
572                return $text;
573            }
574            // Queue the part before the markup for translation in a batch
575            $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
576
577            // Advance to the next position
578            $startPos = $elementPos + strlen( $element );
579
580            // Translate any alt or title attributes inside the matched element
581            if ( $element !== ''
582                && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
583            ) {
584                // FIXME, this decodes entities, so if you have something
585                // like <div title="foo&lt;bar"> the bar won't get
586                // translated since after entity decoding it looks like
587                // unclosed html and we call this method recursively
588                // on attributes.
589                $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
590                // Ensure self-closing tags stay self-closing.
591                $close = substr( $elementMatches[2], -1 ) === '/' ? ' /' : '';
592                $changed = false;
593                foreach ( [ 'title', 'alt' ] as $attrName ) {
594                    if ( !isset( $attrs[$attrName] ) ) {
595                        continue;
596                    }
597                    $attr = $attrs[$attrName];
598                    // Don't convert URLs
599                    if ( !str_contains( $attr, '://' ) ) {
600                        $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
601                    }
602
603                    if ( $attr !== $attrs[$attrName] ) {
604                        $attrs[$attrName] = $attr;
605                        $changed = true;
606                    }
607                }
608                if ( $changed ) {
609                    // @phan-suppress-next-line SecurityCheck-DoubleEscaped Explained above with decodeTagAttributes
610                    $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
611                        $close . $elementMatches[3];
612                }
613            }
614            $literalBlob .= $element . "\000";
615        }
616
617        // Do the main translation batch
618        $translatedBlob = $this->translate( $sourceBlob, $toVariant );
619
620        // Put the output back together
621        $translatedIter = StringUtils::explode( "\000", $translatedBlob );
622        $literalIter = StringUtils::explode( "\000", $literalBlob );
623        $output = '';
624        while ( $translatedIter->valid() && $literalIter->valid() ) {
625            $output .= $translatedIter->current();
626            $output .= $literalIter->current();
627            $translatedIter->next();
628            $literalIter->next();
629        }
630
631        return $output;
632    }
633
634    /** @inheritDoc */
635    public function translate( $text, $variant ) {
636        // If $text is empty or only includes spaces, do nothing
637        // Otherwise translate it
638        if ( trim( $text ) ) {
639            $this->loadTables();
640            // (T337427) Debugging / note error state if mTables not initialised
641            if ( !$this->mTables[$variant] ) {
642                $log = LoggerFactory::getInstance( 'languageconverter' );
643                $log->error( "Tables not initialised for variant in " . __METHOD__
644                    . ". No language conversion made for this string.",
645                    [
646                        "method" => __METHOD__,
647                        "variant" => $variant,
648                        "startOfText" => substr( $text, 0, 500 )
649                    ]
650                );
651                return $text;
652            }
653            $text = $this->mTables[$variant]->replace( $text );
654        }
655        return $text;
656    }
657
658    /**
659     * @param string $text Text to convert
660     * @param string $variant Variant language code
661     * @return string Translated text
662     */
663    protected function translateWithoutRomanNumbers( $text, $variant ) {
664        $breaks = '[^\w\x80-\xff]';
665
666        // regexp for roman numbers
667        // Lookahead assertion ensures $roman doesn't match the empty string
668        $roman = '(?=[MDCLXVI])M{0,4}(C[DM]|D?C{0,3})(X[LC]|L?X{0,3})(I[VX]|V?I{0,3})';
669
670        $reg = '/^' . $roman . '$|^' . $roman . $breaks . '|' . $breaks
671            . $roman . '$|' . $breaks . $roman . $breaks . '/';
672
673        $matches = preg_split( $reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE );
674
675        $m = array_shift( $matches );
676        $this->loadTables();
677        if ( !isset( $this->mTables[$variant] ) ) {
678            throw new RuntimeException( "Broken variant table: "
679                . implode( ',', array_keys( $this->mTables ) ) );
680        }
681        $ret = $this->mTables[$variant]->replace( $m[0] );
682        $mstart = (int)$m[1] + strlen( $m[0] );
683        foreach ( $matches as $m ) {
684            $ret .= substr( $text, $mstart, (int)$m[1] - $mstart );
685            $ret .= $this->translate( $m[0], $variant );
686            $mstart = (int)$m[1] + strlen( $m[0] );
687        }
688
689        return $ret;
690    }
691
692    /** @inheritDoc */
693    public function autoConvertToAllVariants( $text ) {
694        $this->loadTables();
695
696        $ret = [];
697        foreach ( $this->getVariants() as $variant ) {
698            $ret[$variant] = $this->translate( $text, $variant );
699        }
700
701        return $ret;
702    }
703
704    /**
705     * Apply manual conversion rules.
706     * @internal
707     */
708    public function applyManualConv( ConverterRule $convRule ) {
709        // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
710        // title conversion.
711        // T26072: $mConvRuleTitle was overwritten by other manual
712        // rule(s) not for title, this breaks the title conversion.
713        $newConvRuleTitle = $convRule->getTitleValue();
714        if ( $newConvRuleTitle !== null ) {
715            // So I add an empty check for getTitle()
716            $this->mConvRuleTitle = $newConvRuleTitle;
717        }
718
719        // merge/remove manual conversion rules to/from global table
720        $convTable = $convRule->getConvTable();
721        $action = $convRule->getRulesAction();
722        foreach ( $convTable as $variant => $pair ) {
723            $v = $this->validateVariant( $variant );
724            if ( !$v ) {
725                continue;
726            }
727
728            if ( $action == 'add' ) {
729                // More efficient than array_merge(), about 2.5 times.
730                foreach ( $pair as $from => $to ) {
731                    $this->mTables[$v]->setPair( $from, $to );
732                }
733            } elseif ( $action == 'remove' ) {
734                $this->mTables[$v]->removeArray( $pair );
735            }
736        }
737    }
738
739    /** @inheritDoc */
740    public function convertSplitTitle( $title, ?string $variant = null ) {
741        $variant ??= $this->getPreferredVariant();
742
743        $index = $title->getNamespace();
744        $nsText = $this->convertNamespace( $index, $variant );
745
746        $name = str_replace( '_', ' ', $title->getDBKey() );
747        $mainText = $this->translate( $name, $variant );
748
749        return [ $nsText, ':', $mainText ];
750    }
751
752    /** @inheritDoc */
753    public function convertTitle( $title ) {
754        [ $nsText, $nsSeparator, $mainText ] = $this->convertSplitTitle( $title );
755        return $nsText !== '' ?
756            $nsText . $nsSeparator . $mainText :
757            $mainText;
758    }
759
760    /** @inheritDoc */
761    public function convertNamespace( $index, $variant = null ) {
762        if ( $index === NS_MAIN ) {
763            return '';
764        }
765
766        $variant ??= $this->getPreferredVariant();
767
768        $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
769        $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
770        return $cache->getWithSetCallback(
771            $key,
772            BagOStuff::TTL_MINUTE,
773            function () use ( $index, $variant ) {
774                return $this->computeNsVariantText( $index, $variant );
775            }
776        );
777    }
778
779    /**
780     * @param int $index
781     * @param string $variant
782     * @return string
783     */
784    private function computeNsVariantText( int $index, string $variant ): string {
785        $nsVariantText = false;
786
787        // Check if a message for this namespace exists. Note that this would follow
788        // the fallback chain, and the site's content language as the last resort.
789        $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
790        if ( $nsConvMsg->exists() ) {
791            $nsVariantText = $nsConvMsg->plain();
792        }
793
794        if ( $nsVariantText === false ) {
795            // No message exists, retrieve it from the target variant's namespace names.
796            $langObj = MediaWikiServices::getInstance()
797                ->getLanguageFactory()
798                ->getLanguage( $variant );
799            $nsVariantText = $langObj->getFormattedNsText( $index );
800        }
801        return $nsVariantText;
802    }
803
804    /** @inheritDoc */
805    public function convert( $text ) {
806        $variant = $this->getPreferredVariant();
807        return $this->convertTo( $text, $variant );
808    }
809
810    /** @inheritDoc */
811    public function convertTo( $text, $variant, bool $clearState = true ) {
812        $languageConverterFactory = MediaWikiServices::getInstance()->getLanguageConverterFactory();
813        if ( $languageConverterFactory->isConversionDisabled() ) {
814            return $text;
815        }
816        // Reset converter state for a new converter run.
817        if ( $clearState ) {
818            $this->mConvRuleTitle = false;
819        }
820        return $this->recursiveConvertTopLevel( $text, $variant );
821    }
822
823    /**
824     * Recursively convert text on the outside. Allow to use nested
825     * markups to custom rules.
826     *
827     * @param string $text Text to be converted
828     * @param string $variant The target variant code
829     * @param int $depth Depth of recursion
830     * @return string Converted text
831     */
832    protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
833        $startPos = 0;
834        $out = '';
835        $length = strlen( $text );
836        $shouldConvert = !$this->guessVariant( $text, $variant );
837        if ( RequestContext::getMain()->getRequest()->getFuzzyBool( 'nolcguess', false ) ) {
838            $shouldConvert = true;
839        }
840        $continue = true;
841
842        $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
843        $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
844        $noMath = '<math.*?>.*?<\/math>(*SKIP)(*FAIL)';
845        $noSvg = '<svg.*?>.*?<\/svg>(*SKIP)(*FAIL)';
846        // phpcs:ignore Generic.Files.LineLength
847        $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
848        while ( $startPos < $length && $continue ) {
849            $continue = preg_match(
850                // Only match "-{" outside the html.
851                "/$noScript|$noStyle|$noMath|$noSvg|$noHtml|-\{/",
852                $text,
853                $m,
854                PREG_OFFSET_CAPTURE,
855                $startPos
856            );
857
858            if ( !$continue ) {
859                // No more markup, append final segment
860                $fragment = substr( $text, $startPos );
861                $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
862                return $out;
863            }
864
865            // Offset of the match of the regex pattern.
866            $pos = $m[0][1];
867
868            // Append initial segment
869            $fragment = substr( $text, $startPos, $pos - $startPos );
870            $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
871            // -{ marker found, not in attribute
872            // Advance position up to -{ marker.
873            $startPos = $pos;
874            // Do recursive conversion
875            // Note: This passes $startPos by reference, and advances it.
876            $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
877        }
878        return $out;
879    }
880
881    /**
882     * Recursively convert text on the inside.
883     *
884     * @param string $text Text to be converted
885     * @param string $variant The target variant code
886     * @param int &$startPos
887     * @param int $depth Depth of recursion
888     * @return string Converted text
889     */
890    protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
891        // Quick check (no function calls)
892        if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
893            throw new InvalidArgumentException( __METHOD__ . ': invalid input string' );
894        }
895
896        $startPos += 2;
897        $inner = '';
898        $warningDone = false;
899        $length = strlen( $text );
900
901        while ( $startPos < $length ) {
902            $m = false;
903            preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
904            if ( !$m ) {
905                // Unclosed rule
906                break;
907            }
908
909            $token = $m[0][0];
910            $pos = $m[0][1];
911
912            // Markup found
913            // Append initial segment
914            $inner .= substr( $text, $startPos, $pos - $startPos );
915
916            // Advance position
917            $startPos = $pos;
918
919            switch ( $token ) {
920                case '-{':
921                    // Check max depth
922                    if ( $depth >= $this->mMaxDepth ) {
923                        $inner .= '-{';
924                        if ( !$warningDone ) {
925                            $inner .= '<span class="error">' .
926                                wfMessage( 'language-converter-depth-warning' )
927                                    ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
928                                '</span>';
929                            $warningDone = true;
930                        }
931                        $startPos += 2;
932                        break;
933                    }
934                    // Recursively parse another rule
935                    $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
936                    break;
937                case '}-':
938                    // Apply the rule
939                    $startPos += 2;
940                    $rule = new ConverterRule( $this );
941                    $rule->parse( $inner, $variant );
942                    $this->applyManualConv( $rule );
943                    return $rule->getDisplay();
944                default:
945                    throw new UnexpectedValueException( __METHOD__ . ': invalid regex match' );
946            }
947        }
948
949        // Unclosed rule
950        if ( $startPos < $length ) {
951            $inner .= substr( $text, $startPos );
952        }
953        $startPos = $length;
954        return '-{' . $this->autoConvert( $inner, $variant );
955    }
956
957    /** @inheritDoc */
958    public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
959        # If the article has already existed, there is no need to
960        # check it again. Otherwise it may cause a fault.
961        if ( $nt instanceof LinkTarget ) {
962            $nt = Title::castFromLinkTarget( $nt );
963            if ( $nt->exists() ) {
964                return;
965            }
966        }
967
968        if ( $nt instanceof PageIdentity && $nt->exists() ) {
969            return;
970        }
971
972        $request = RequestContext::getMain()->getRequest();
973
974        $isredir = $request->getText( 'redirect', 'yes' );
975        $action = $request->getText( 'action' );
976        if ( $action == 'edit' && $request->getBool( 'redlink' ) ) {
977            $action = 'view';
978        }
979        $linkconvert = $request->getText( 'linkconvert', 'yes' );
980        $disableLinkConversion =
981            MediaWikiServices::getInstance()->getLanguageConverterFactory()
982            ->isLinkConversionDisabled();
983        $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
984        $linkBatch = $linkBatchFactory->newLinkBatch();
985
986        $ns = NS_MAIN;
987
988        if ( $disableLinkConversion ||
989            ( !$ignoreOtherCond &&
990                ( $isredir == 'no'
991                    || $action == 'edit'
992                    || $action == 'submit'
993                    || $linkconvert == 'no' )
994            )
995        ) {
996            return;
997        }
998
999        if ( is_object( $nt ) ) {
1000            $ns = $nt->getNamespace();
1001        }
1002
1003        $variants = $this->autoConvertToAllVariants( $link );
1004        if ( !$variants ) { // give up
1005            return;
1006        }
1007
1008        $titles = [];
1009
1010        foreach ( $variants as $v ) {
1011            if ( $v != $link ) {
1012                $varnt = Title::newFromText( $v, $ns );
1013                if ( $varnt !== null ) {
1014                    $linkBatch->addObj( $varnt );
1015                    $titles[] = $varnt;
1016                }
1017            }
1018        }
1019
1020        // fetch all variants in single query
1021        $linkBatch->execute();
1022
1023        foreach ( $titles as $varnt ) {
1024            if ( $varnt->getArticleID() > 0 ) {
1025                $nt = $varnt;
1026                $link = $varnt->getText();
1027                break;
1028            }
1029        }
1030    }
1031
1032    /** @inheritDoc */
1033    public function getExtraHashOptions() {
1034        $variant = $this->getPreferredVariant();
1035
1036        return '!' . $variant;
1037    }
1038
1039    /** @inheritDoc */
1040    public function guessVariant( $text, $variant ) {
1041        return false;
1042    }
1043
1044    /**
1045     * Load default conversion tables.
1046     *
1047     * @return array<string,ReplacementArray>
1048     */
1049    abstract protected function loadDefaultTables(): array;
1050
1051    /**
1052     * Load conversion tables either from the cache or the disk.
1053     * @private
1054     * @param bool $fromCache Whether to load from cache. Defaults to true.
1055     */
1056    protected function loadTables( $fromCache = true ) {
1057        $services = MediaWikiServices::getInstance();
1058        $languageConverterCacheType = $services
1059            ->getMainConfig()->get( MainConfigNames::LanguageConverterCacheType );
1060
1061        if ( $this->mTablesLoaded ) {
1062            return;
1063        }
1064
1065        $cache = $services->getObjectCacheFactory()->getInstance( $languageConverterCacheType );
1066        $cacheKey = $cache->makeKey(
1067            'conversiontables', $this->getMainCode(),
1068            md5( implode( ',', $this->getVariants() ) ), self::CACHE_VERSION_KEY
1069        );
1070        if ( !$fromCache ) {
1071            $cache->delete( $cacheKey );
1072        }
1073        $this->mTables = $cache->getWithSetCallback( $cacheKey, $cache::TTL_HOUR * 12, function () {
1074            // We will first load the default tables
1075            // then update them using things in MediaWiki:Conversiontable/*
1076            $tables = $this->loadDefaultTables();
1077            foreach ( $this->getVariants() as $var ) {
1078                $cached = $this->parseCachedTable( $var );
1079                $tables[$var]->mergeArray( $cached );
1080            }
1081
1082            $this->postLoadTables( $tables );
1083            return $tables;
1084        } );
1085        $this->mTablesLoaded = true;
1086    }
1087
1088    /**
1089     * Hook for post-processing after conversion tables are loaded.
1090     *
1091     * @param array<string,ReplacementArray> &$tables
1092     */
1093    protected function postLoadTables( &$tables ) {
1094    }
1095
1096    /**
1097     * Reload the conversion tables.
1098     *
1099     * Also used by test suites which need to reset the converter state.
1100     *
1101     * Called by ParserTestRunner with the help of TestingAccessWrapper
1102     */
1103    private function reloadTables() {
1104        if ( $this->mTables ) {
1105            $this->mTables = [];
1106        }
1107
1108        $this->mTablesLoaded = false;
1109        $this->loadTables( false );
1110    }
1111
1112    /**
1113     * Parse the conversion table stored in the cache.
1114     *
1115     * The tables should be in blocks of the following form:
1116     *         -{
1117     *             word => word ;
1118     *             word => word ;
1119     *             ...
1120     *         }-
1121     *
1122     * To make the tables more manageable, subpages are allowed
1123     * and will be parsed recursively if $recursive == true.
1124     *
1125     * @param string $code Language code
1126     * @param string $subpage Subpage name
1127     * @param bool $recursive Parse subpages recursively? Defaults to true.
1128     *
1129     * @return array
1130     */
1131    private function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1132        static $parsed = [];
1133
1134        $key = 'Conversiontable/' . $code;
1135        if ( $subpage ) {
1136            $key .= '/' . $subpage;
1137        }
1138        if ( array_key_exists( $key, $parsed ) ) {
1139            return [];
1140        }
1141
1142        $parsed[$key] = true;
1143
1144        if ( $subpage === '' ) {
1145            $messageCache = MediaWikiServices::getInstance()->getMessageCache();
1146            $txt = $messageCache->getMsgFromNamespace( $key, $code );
1147        } else {
1148            $txt = false;
1149            $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
1150            if ( $title && $title->exists() ) {
1151                $revision = MediaWikiServices::getInstance()
1152                    ->getRevisionLookup()
1153                    ->getRevisionByTitle( $title );
1154                if ( $revision ) {
1155                    $model = $revision->getSlot(
1156                        SlotRecord::MAIN,
1157                        RevisionRecord::RAW
1158                    )->getModel();
1159                    if ( $model == CONTENT_MODEL_WIKITEXT ) {
1160                        // @phan-suppress-next-line PhanUndeclaredMethod
1161                        $txt = $revision->getContent(
1162                            SlotRecord::MAIN,
1163                            RevisionRecord::RAW
1164                        )->getText();
1165                    }
1166
1167                    // @todo in the future, use a specialized content model, perhaps based on json!
1168                }
1169            }
1170        }
1171
1172        # Nothing to parse if there's no text
1173        if ( $txt === false || $txt === null || $txt === '' ) {
1174            return [];
1175        }
1176
1177        // get all subpage links of the form
1178        // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1179        $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
1180            ':Conversiontable';
1181        $subs = StringUtils::explode( '[[', $txt );
1182        $sublinks = [];
1183        foreach ( $subs as $sub ) {
1184            $link = explode( ']]', $sub, 2 );
1185            if ( count( $link ) != 2 ) {
1186                continue;
1187            }
1188            $b = explode( '|', $link[0], 2 );
1189            $b = explode( '/', trim( $b[0] ), 3 );
1190            if ( count( $b ) == 3 ) {
1191                $sublink = $b[2];
1192            } else {
1193                $sublink = '';
1194            }
1195
1196            if ( $b[0] == $linkhead && $b[1] == $code ) {
1197                $sublinks[] = $sublink;
1198            }
1199        }
1200
1201        // parse the mappings in this page
1202        $blocks = StringUtils::explode( '-{', $txt );
1203        $ret = [];
1204        $first = true;
1205        foreach ( $blocks as $block ) {
1206            if ( $first ) {
1207                // Skip the part before the first -{
1208                $first = false;
1209                continue;
1210            }
1211            $mappings = explode( '}-', $block, 2 )[0];
1212            $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1213            $table = StringUtils::explode( ';', $stripped );
1214            foreach ( $table as $t ) {
1215                $m = explode( '=>', $t, 3 );
1216                if ( count( $m ) != 2 ) {
1217                    continue;
1218                }
1219                // trim any trailing comments starting with '//'
1220                $tt = explode( '//', $m[1], 2 );
1221                $ret[trim( $m[0] )] = trim( $tt[0] );
1222            }
1223        }
1224
1225        // recursively parse the subpages
1226        if ( $recursive ) {
1227            foreach ( $sublinks as $link ) {
1228                $s = $this->parseCachedTable( $code, $link, $recursive );
1229                $ret = $s + $ret;
1230            }
1231        }
1232        return $ret;
1233    }
1234
1235    /** @inheritDoc */
1236    public function markNoConversion( $text, $noParse = false ) {
1237        # don't mark if already marked
1238        if ( str_contains( $text, '-{' ) || str_contains( $text, '}-' ) ) {
1239            return $text;
1240        }
1241
1242        return "-{R|$text}-";
1243    }
1244
1245    /** @inheritDoc */
1246    public function convertCategoryKey( $key ) {
1247        return $key;
1248    }
1249
1250    /**
1251     * @param PageIdentity $page Message page
1252     *
1253     * @return void
1254     */
1255    public function updateConversionTable( PageIdentity $page ) {
1256        if ( $page->getNamespace() === NS_MEDIAWIKI ) {
1257            $t = explode( '/', $page->getDBkey(), 3 );
1258            $c = count( $t );
1259            if ( $c > 1 && $t[0] == 'Conversiontable' && $this->validateVariant( $t[1] ) ) {
1260                $this->reloadTables();
1261            }
1262        }
1263    }
1264
1265    /**
1266     * Get the cached separator pattern for ConverterRule::parseRules()
1267     * @return string
1268     */
1269    public function getVarSeparatorPattern() {
1270        if ( $this->mVarSeparatorPattern === null ) {
1271            // varsep_pattern for preg_split:
1272            // The text should be split by ";" only if a valid variant
1273            // name exists after the markup.
1274            // For example
1275            //  -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1276            //  <span style="font-size:120%;">yyy</span>;}-
1277            // we should split it as:
1278            //  [
1279            //    [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1280            //    [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1281            //    [2] => ''
1282            //  ]
1283            $expandedVariants = [];
1284            foreach ( $this->getVariants() as $variant ) {
1285                $expandedVariants[ $variant ] = 1;
1286                // Accept standard BCP 47 names for variants as well.
1287                $expandedVariants[ LanguageCode::bcp47( $variant ) ] = 1;
1288            }
1289            // Accept old deprecated names for variants
1290            foreach ( LanguageCode::getDeprecatedCodeMapping() as $old => $new ) {
1291                if ( isset( $expandedVariants[ $new ] ) ) {
1292                    $expandedVariants[ $old ] = 1;
1293                }
1294            }
1295            $expandedVariants = implode( '|', array_keys( $expandedVariants ) );
1296
1297            $pat = '/;\s*(?=';
1298            // zh-hans:xxx;zh-hant:yyy
1299            $pat .= '(?:' . $expandedVariants . ')\s*:';
1300            // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1301            $pat .= '|[^;]*?=>\s*(?:' . $expandedVariants . ')\s*:';
1302            $pat .= '|\s*$)/';
1303            $this->mVarSeparatorPattern = $pat;
1304        }
1305        return $this->mVarSeparatorPattern;
1306    }
1307
1308    /** @inheritDoc */
1309    public function hasVariants() {
1310        return count( $this->getVariants() ) > 1;
1311    }
1312
1313    /** @inheritDoc */
1314    public function hasVariant( $variant ) {
1315        return $variant && ( $variant === $this->validateVariant( $variant ) );
1316    }
1317
1318    /** @inheritDoc */
1319    public function convertHtml( $text ) {
1320        // @phan-suppress-next-line SecurityCheck-DoubleEscaped convert() is documented to return html
1321        return htmlspecialchars( $this->convert( $text ) );
1322    }
1323}
1324
1325/** @deprecated class alias since 1.43 */
1326class_alias( LanguageConverter::class, 'LanguageConverter' );