Debian Codegraph @

includes/language/LanguageConverter.php

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