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.
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.
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
21 use MediaWiki\MediaWikiServices
;
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\Storage\RevisionRecord
;
27 * Base class for language conversion.
30 * @author Zhengzhu Feng <zhengzhu@gmail.com>
31 * @author fdcn <fdcn64@gmail.com>
32 * @author shinjiman <shinjiman@gmail.com>
33 * @author PhiLiP <philip.npc@gmail.com>
35 class LanguageConverter
{
37 * languages supporting variants
41 public static $languagesWithVariants = [
55 public $mMainLanguageCode;
61 public $mVariantFallbacks;
62 public $mVariantNames;
63 public $mTablesLoaded = false;
66 * @var ReplacementArray[]
67 * @phan-var array<string,ReplacementArray>
71 // 'bidirectional' 'unidirectional' 'disable' for each variant
76 public $mDescCodeSep = ':', $mDescVarSep = ';';
77 public $mUcfirst = false;
78 public $mConvRuleTitle = false;
81 public $mHeaderVariant;
82 public $mMaxDepth = 10;
83 public $mVarSeparatorPattern;
85 const CACHE_VERSION_KEY
= 'VERSION 7';
88 * @param Language $langobj
89 * @param string $maincode The main language code of this language
90 * @param string[] $variants The supported variants of this language
91 * @param array $variantfallbacks The fallback language of each variant
92 * @param array $flags Defining the custom strings that maps to the flags
93 * @param array $manualLevel Limit for supported variants
95 public function __construct( Language
$langobj, $maincode, $variants = [],
96 $variantfallbacks = [], $flags = [],
98 global $wgDisabledVariants;
99 $this->mLangObj
= $langobj;
100 $this->mMainLanguageCode
= $maincode;
101 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
102 $this->mVariantFallbacks
= $variantfallbacks;
103 $this->mVariantNames
= Language
::fetchLanguageNames();
105 // 'S' show converted text
106 // '+' add rules for alltext
107 // 'E' the gave flags is error
108 // these flags above are reserved for program
109 'A' => 'A', // add rule for convert code (all text convert)
110 'T' => 'T', // title convert
111 'R' => 'R', // raw content
112 'D' => 'D', // convert description (subclass implement)
113 '-' => '-', // remove convert (not implement)
114 'H' => 'H', // add rule for convert code (but no display in placed code)
115 'N' => 'N', // current variant name
117 $this->mFlags
= array_merge( $defaultflags, $flags );
118 foreach ( $this->mVariants
as $v ) {
119 if ( array_key_exists( $v, $manualLevel ) ) {
120 $this->mManualLevel
[$v] = $manualLevel[$v];
122 $this->mManualLevel
[$v] = 'bidirectional';
124 $this->mFlags
[$v] = $v;
129 * Get all valid variants.
130 * Call this instead of using $this->mVariants directly.
132 * @return string[] Contains all valid variants
134 public function getVariants() {
135 return $this->mVariants
;
139 * In case some variant is not defined in the markup, we need
140 * to have some fallback. For example, in zh, normally people
141 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
142 * when zh-sg is preferred but not defined, we will pick zh-hans
143 * in this case. Right now this is only used by zh.
145 * @param string $variant The language code of the variant
146 * @return string|array The code of the fallback language or the
147 * main code if there is no fallback
149 public function getVariantFallbacks( $variant ) {
150 return $this->mVariantFallbacks
[$variant] ??
$this->mMainLanguageCode
;
154 * Get the title produced by the conversion rule.
155 * @return string The converted title text
157 public function getConvRuleTitle() {
158 return $this->mConvRuleTitle
;
162 * Get preferred language variant.
163 * @return string The preferred language code
165 public function getPreferredVariant() {
166 global $wgDefaultLanguageVariant, $wgUser;
168 $req = $this->getURLVariant();
170 Hooks
::run( 'GetLangPreferredVariant', [ &$req ] );
172 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
173 $req = $this->getUserVariant();
175 $req = $this->getHeaderVariant();
178 if ( $wgDefaultLanguageVariant && !$req ) {
179 $req = $this->validateVariant( $wgDefaultLanguageVariant );
182 $req = $this->validateVariant( $req );
184 // This function, unlike the other get*Variant functions, is
185 // not memoized (i.e. there return value is not cached) since
186 // new information might appear during processing after this
191 return $this->mMainLanguageCode
;
195 * Get default variant.
196 * This function would not be affected by user's settings
197 * @return string The default variant code
199 public function getDefaultVariant() {
200 global $wgDefaultLanguageVariant;
202 $req = $this->getURLVariant();
205 $req = $this->getHeaderVariant();
208 if ( $wgDefaultLanguageVariant && !$req ) {
209 $req = $this->validateVariant( $wgDefaultLanguageVariant );
215 return $this->mMainLanguageCode
;
219 * Validate the variant and return an appropriate strict internal
220 * variant code if one exists. Compare to Language::hasVariant()
221 * which does a strict test.
223 * @param string|null $variant The variant to validate
224 * @return mixed Returns an equivalent valid variant code if possible,
227 public function validateVariant( $variant = null ) {
228 if ( $variant === null ) {
231 // Our internal variants are always lower-case; the variant we
232 // are validating may have mixed case.
233 $variant = LanguageCode
::replaceDeprecatedCodes( strtolower( $variant ) );
234 if ( in_array( $variant, $this->mVariants
) ) {
237 // Browsers are supposed to use BCP 47 standard in the
238 // Accept-Language header, but not all of our internal
239 // mediawiki variant codes are BCP 47. Map BCP 47 code
240 // to our internal code.
241 foreach ( $this->mVariants
as $v ) {
242 // Case-insensitive match (BCP 47 is mixed case)
243 if ( strtolower( LanguageCode
::bcp47( $v ) ) === $variant ) {
251 * Get the variant specified in the URL
253 * @return mixed Variant if one found, null otherwise
255 public function getURLVariant() {
258 if ( $this->mURLVariant
) {
259 return $this->mURLVariant
;
262 // see if the preference is set in the request
263 $ret = $wgRequest->getText( 'variant' );
266 $ret = $wgRequest->getVal( 'uselang' );
269 $this->mURLVariant
= $this->validateVariant( $ret );
270 return $this->mURLVariant
;
274 * Determine if the user has a variant set.
276 * @return mixed Variant if one found, null otherwise
278 protected function getUserVariant() {
281 // memoizing this function wreaks havoc on parserTest.php
283 if ( $this->mUserVariant ) {
284 return $this->mUserVariant;
288 // Get language variant preference from logged in users
289 // Don't call this on stub objects because that causes infinite
290 // recursion during initialisation
291 if ( !$wgUser->isSafeToLoad() ) {
294 if ( $wgUser->isLoggedIn() ) {
296 $this->mMainLanguageCode
==
297 MediaWikiServices
::getInstance()->getContentLanguage()->getCode()
299 $ret = $wgUser->getOption( 'variant' );
301 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
304 // figure out user lang without constructing wgLang to avoid
305 // infinite recursion
306 $ret = $wgUser->getOption( 'language' );
309 $this->mUserVariant
= $this->validateVariant( $ret );
310 return $this->mUserVariant
;
314 * Determine the language variant from the Accept-Language header.
316 * @return mixed Variant if one found, null otherwise
318 protected function getHeaderVariant() {
321 if ( $this->mHeaderVariant
) {
322 return $this->mHeaderVariant
;
325 // See if some supported language variant is set in the
327 $languages = array_keys( $wgRequest->getAcceptLang() );
328 if ( empty( $languages ) ) {
332 $fallbackLanguages = [];
333 foreach ( $languages as $language ) {
334 $this->mHeaderVariant
= $this->validateVariant( $language );
335 if ( $this->mHeaderVariant
) {
339 // To see if there are fallbacks of current language.
340 // We record these fallback variants, and process
342 $fallbacks = $this->getVariantFallbacks( $language );
343 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
344 $fallbackLanguages[] = $fallbacks;
345 } elseif ( is_array( $fallbacks ) ) {
347 array_merge( $fallbackLanguages, $fallbacks );
351 if ( !$this->mHeaderVariant
) {
352 // process fallback languages now
353 $fallback_languages = array_unique( $fallbackLanguages );
354 foreach ( $fallback_languages as $language ) {
355 $this->mHeaderVariant
= $this->validateVariant( $language );
356 if ( $this->mHeaderVariant
) {
362 return $this->mHeaderVariant
;
366 * Dictionary-based conversion.
367 * This function would not parse the conversion rules.
368 * If you want to parse rules, try to use convert() or
371 * @param string $text The text to be converted
372 * @param bool|string $toVariant The target language code
373 * @return string The converted text
375 public function autoConvert( $text, $toVariant = false ) {
379 $toVariant = $this->getPreferredVariant();
385 if ( $this->guessVariant( $text, $toVariant ) ) {
388 /* we convert everything except:
389 1. HTML markups (anything between < and >)
391 3. placeholders created by the parser
392 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
393 Minimize use of backtracking where possible.
396 if ( $reg === null ) {
397 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
399 // this one is needed when the text is inside an HTML markup
400 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
402 // Optimize for the common case where these tags have
403 // few or no children. Thus try and possesively get as much as
404 // possible, and only engage in backtracking when we hit a '<'.
406 // disable convert to variants between <code> tags
407 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
408 // disable conversion of <script> tags
409 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
410 // disable conversion of <pre> tags
411 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
412 // The "|.*+)" at the end, is in case we missed some part of html syntax,
413 // we will fail securely (hopefully) by matching the rest of the string.
414 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
416 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
417 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
423 // Guard against delimiter nulls in the input
424 // (should never happen: see T159174)
425 $text = str_replace( "\000", '', $text );
426 $text = str_replace( "\004", '', $text );
428 $markupMatches = null;
429 $elementMatches = null;
431 // We add a marker (\004) at the end of text, to ensure we always match the
432 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
433 $textWithMarker = $text . "\004";
434 while ( $startPos < strlen( $text ) ) {
435 if ( preg_match( $reg, $textWithMarker, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
436 $elementPos = $markupMatches[0][1];
437 $element = $markupMatches[0][0];
438 if ( $element === "\004" ) {
440 $elementPos = strlen( $text );
442 } elseif ( substr( $element, -1 ) === "\004" ) {
443 // This can sometimes happen if we have
444 // unclosed html tags (For example
445 // when converting a title attribute
446 // during a recursive call that contains
447 // a < e.g. <div title="<">.
448 $element = substr( $element, 0, -1 );
451 // If we hit here, then Language Converter could be tricked
452 // into doing an XSS, so we refuse to translate.
453 // If non-crazy input manages to reach this code path,
454 // we should consider it a bug.
455 $log = LoggerFactory
::getInstance( 'languageconverter' );
456 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
457 . ". Disabling language conversion for this page.",
459 "method" => __METHOD__
,
460 "variant" => $toVariant,
461 "startOfText" => substr( $text, 0, 500 )
466 // Queue the part before the markup for translation in a batch
467 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
469 // Advance to the next position
470 $startPos = $elementPos +
strlen( $element );
472 // Translate any alt or title attributes inside the matched element
474 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
476 // FIXME, this decodes entities, so if you have something
477 // like <div title="foo<bar"> the bar won't get
478 // translated since after entity decoding it looks like
479 // unclosed html and we call this method recursively
481 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
482 // Ensure self-closing tags stay self-closing.
483 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
485 foreach ( [ 'title', 'alt' ] as $attrName ) {
486 if ( !isset( $attrs[$attrName] ) ) {
489 $attr = $attrs[$attrName];
490 // Don't convert URLs
491 if ( !strpos( $attr, '://' ) ) {
492 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
495 if ( $attr !== $attrs[$attrName] ) {
496 $attrs[$attrName] = $attr;
501 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
502 $close . $elementMatches[3];
505 $literalBlob .= $element . "\000";
508 // Do the main translation batch
509 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
511 // Put the output back together
512 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
513 $literalIter = StringUtils
::explode( "\000", $literalBlob );
515 while ( $translatedIter->valid() && $literalIter->valid() ) {
516 $output .= $translatedIter->current();
517 $output .= $literalIter->current();
518 $translatedIter->next();
519 $literalIter->next();
526 * Translate a string to a variant.
527 * Doesn't parse rules or do any of that other stuff, for that use
528 * convert() or convertTo().
530 * @param string $text Text to convert
531 * @param string $variant Variant language code
532 * @return string Translated text
534 public function translate( $text, $variant ) {
535 // If $text is empty or only includes spaces, do nothing
536 // Otherwise translate it
537 if ( trim( $text ) ) {
539 $text = $this->mTables
[$variant]->replace( $text );
545 * Call translate() to convert text to all valid variants.
547 * @param string $text The text to be converted
548 * @return array Variant => converted text
550 public function autoConvertToAllVariants( $text ) {
554 foreach ( $this->mVariants
as $variant ) {
555 $ret[$variant] = $this->translate( $text, $variant );
562 * Apply manual conversion rules.
564 * @param ConverterRule $convRule
566 protected function applyManualConv( $convRule ) {
567 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
569 // T26072: $mConvRuleTitle was overwritten by other manual
570 // rule(s) not for title, this breaks the title conversion.
571 $newConvRuleTitle = $convRule->getTitle();
572 if ( $newConvRuleTitle ) {
573 // So I add an empty check for getTitle()
574 $this->mConvRuleTitle
= $newConvRuleTitle;
577 // merge/remove manual conversion rules to/from global table
578 $convTable = $convRule->getConvTable();
579 $action = $convRule->getRulesAction();
580 foreach ( $convTable as $variant => $pair ) {
581 $v = $this->validateVariant( $variant );
586 if ( $action == 'add' ) {
587 // More efficient than array_merge(), about 2.5 times.
588 foreach ( $pair as $from => $to ) {
589 $this->mTables
[$v]->setPair( $from, $to );
591 } elseif ( $action == 'remove' ) {
592 $this->mTables
[$v]->removeArray( $pair );
598 * Auto convert a Title object to a readable string in the
601 * @param Title $title A object of Title
602 * @return string Converted title text
604 public function convertTitle( $title ) {
605 $variant = $this->getPreferredVariant();
606 $index = $title->getNamespace();
607 if ( $index !== NS_MAIN
) {
608 $text = $this->convertNamespace( $index, $variant ) . ':';
612 $text .= $this->translate( $title->getText(), $variant );
617 * Get the namespace display name in the preferred variant.
619 * @param int $index Namespace id
620 * @param string|null $variant Variant code or null for preferred variant
621 * @return string Namespace name for display
623 public function convertNamespace( $index, $variant = null ) {
624 if ( $index === NS_MAIN
) {
628 if ( $variant === null ) {
629 $variant = $this->getPreferredVariant();
632 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
633 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
634 $nsVariantText = $cache->get( $key );
635 if ( $nsVariantText !== false ) {
636 return $nsVariantText;
639 // First check if a message gives a converted name in the target variant.
640 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
641 if ( $nsConvMsg->exists() ) {
642 $nsVariantText = $nsConvMsg->plain();
645 // Then check if a message gives a converted name in content language
646 // which needs extra translation to the target variant.
647 if ( $nsVariantText === false ) {
648 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
649 if ( $nsConvMsg->exists() ) {
650 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
654 if ( $nsVariantText === false ) {
655 // No message exists, retrieve it from the target variant's namespace names.
656 $langObj = $this->mLangObj
->factory( $variant );
657 $nsVariantText = $langObj->getFormattedNsText( $index );
660 $cache->set( $key, $nsVariantText, 60 );
662 return $nsVariantText;
666 * Convert text to different variants of a language. The automatic
667 * conversion is done in autoConvert(). Here we parse the text
668 * marked with -{}-, which specifies special conversions of the
669 * text that can not be accomplished in autoConvert().
671 * Syntax of the markup:
672 * -{code1:text1;code2:text2;...}- or
673 * -{flags|code1:text1;code2:text2;...}- or
674 * -{text}- in which case no conversion should take place for text
676 * @warning Glossary state is maintained between calls. Never feed this
677 * method input that hasn't properly been escaped as it may result in
678 * an XSS in subsequent calls, even if those subsequent calls properly
680 * @param string $text Text to be converted, already html escaped.
681 * @return string Converted text (html)
683 public function convert( $text ) {
684 $variant = $this->getPreferredVariant();
685 return $this->convertTo( $text, $variant );
689 * Same as convert() except a extra parameter to custom variant.
691 * @param string $text Text to be converted, already html escaped
692 * @param-taint $text exec_html
693 * @param string $variant The target variant code
694 * @return string Converted text
695 * @return-taint escaped
697 public function convertTo( $text, $variant ) {
698 global $wgDisableLangConversion;
699 if ( $wgDisableLangConversion ) {
702 // Reset converter state for a new converter run.
703 $this->mConvRuleTitle
= false;
704 return $this->recursiveConvertTopLevel( $text, $variant );
708 * Recursively convert text on the outside. Allow to use nested
709 * markups to custom rules.
711 * @param string $text Text to be converted
712 * @param string $variant The target variant code
713 * @param int $depth Depth of recursion
714 * @return string Converted text
716 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
719 $length = strlen( $text );
720 $shouldConvert = !$this->guessVariant( $text, $variant );
723 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
724 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
725 // phpcs:ignore Generic.Files.LineLength
726 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
727 while ( $startPos < $length && $continue ) {
728 $continue = preg_match(
729 // Only match -{ outside of html.
730 "/$noScript|$noStyle|$noHtml|-\{/",
738 // No more markup, append final segment
739 $fragment = substr( $text, $startPos );
740 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
744 // Offset of the match of the regex pattern.
747 // Append initial segment
748 $fragment = substr( $text, $startPos, $pos - $startPos );
749 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
750 // -{ marker found, not in attribute
751 // Advance position up to -{ marker.
753 // Do recursive conversion
754 // Note: This passes $startPos by reference, and advances it.
755 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
761 * Recursively convert text on the inside.
763 * @param string $text Text to be converted
764 * @param string $variant The target variant code
765 * @param int &$startPos
766 * @param int $depth Depth of recursion
768 * @throws MWException
769 * @return string Converted text
771 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
772 // Quick sanity check (no function calls)
773 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
774 throw new MWException( __METHOD__
. ': invalid input string' );
779 $warningDone = false;
780 $length = strlen( $text );
782 while ( $startPos < $length ) {
784 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
794 // Append initial segment
795 $inner .= substr( $text, $startPos, $pos - $startPos );
803 if ( $depth >= $this->mMaxDepth
) {
805 if ( !$warningDone ) {
806 $inner .= '<span class="error">' .
807 wfMessage( 'language-converter-depth-warning' )
808 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
815 // Recursively parse another rule
816 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
821 $rule = new ConverterRule( $inner, $this );
822 $rule->parse( $variant );
823 $this->applyManualConv( $rule );
824 return $rule->getDisplay();
826 throw new MWException( __METHOD__
. ': invalid regex match' );
831 if ( $startPos < $length ) {
832 $inner .= substr( $text, $startPos );
835 return '-{' . $this->autoConvert( $inner, $variant );
839 * If a language supports multiple variants, it is possible that
840 * non-existing link in one variant actually exists in another variant.
841 * This function tries to find it. See e.g. LanguageZh.php
842 * The input parameters may be modified upon return
844 * @param string &$link The name of the link
845 * @param Title &$nt The title object of the link
846 * @param bool $ignoreOtherCond To disable other conditions when
847 * we need to transclude a template or update a category's link
849 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
850 # If the article has already existed, there is no need to
851 # check it again, otherwise it may cause a fault.
852 if ( is_object( $nt ) && $nt->exists() ) {
856 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
857 $isredir = $wgRequest->getText( 'redirect', 'yes' );
858 $action = $wgRequest->getText( 'action' );
859 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
862 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
863 $disableLinkConversion = $wgDisableLangConversion
864 ||
$wgDisableTitleConversion;
865 $linkBatch = new LinkBatch();
869 if ( $disableLinkConversion ||
870 ( !$ignoreOtherCond &&
873 ||
$action == 'submit'
874 ||
$linkconvert == 'no' ) ) ) {
878 if ( is_object( $nt ) ) {
879 $ns = $nt->getNamespace();
882 $variants = $this->autoConvertToAllVariants( $link );
883 if ( !$variants ) { // give up
889 foreach ( $variants as $v ) {
891 $varnt = Title
::newFromText( $v, $ns );
892 if ( !is_null( $varnt ) ) {
893 $linkBatch->addObj( $varnt );
899 // fetch all variants in single query
900 $linkBatch->execute();
902 foreach ( $titles as $varnt ) {
903 if ( $varnt->getArticleID() > 0 ) {
905 $link = $varnt->getText();
912 * Returns language specific hash options.
916 public function getExtraHashOptions() {
917 $variant = $this->getPreferredVariant();
919 return '!' . $variant;
923 * Guess if a text is written in a variant. This should be implemented in subclasses.
925 * @param string $text The text to be checked
926 * @param string $variant Language code of the variant to be checked for
927 * @return bool True if $text appears to be written in $variant, false if not
929 * @author Nikola Smolenski <smolensk@eunet.rs>
932 public function guessVariant( $text, $variant ) {
937 * Load default conversion tables.
938 * This method must be implemented in derived class.
941 * @throws MWException
943 function loadDefaultTables() {
944 $class = static::class;
945 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
949 * Load conversion tables either from the cache or the disk.
951 * @param bool $fromCache Load from memcached? Defaults to true.
953 function loadTables( $fromCache = true ) {
954 global $wgLanguageConverterCacheType;
956 if ( $this->mTablesLoaded
) {
960 $this->mTablesLoaded
= true;
961 $this->mTables
= false;
962 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
963 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
965 $this->mTables
= $cache->get( $cacheKey );
967 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
968 // not in cache, or we need a fresh reload.
969 // We will first load the default tables
970 // then update them using things in MediaWiki:Conversiontable/*
971 $this->loadDefaultTables();
972 foreach ( $this->mVariants
as $var ) {
973 $cached = $this->parseCachedTable( $var );
974 $this->mTables
[$var]->mergeArray( $cached );
977 $this->postLoadTables();
978 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
980 $cache->set( $cacheKey, $this->mTables
, 43200 );
985 * Hook for post processing after conversion tables are loaded.
987 function postLoadTables() {
991 * Reload the conversion tables.
993 * Also used by test suites which need to reset the converter state.
997 private function reloadTables() {
998 if ( $this->mTables
) {
999 // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
1000 unset( $this->mTables
);
1003 $this->mTablesLoaded
= false;
1004 $this->loadTables( false );
1008 * Parse the conversion table stored in the cache.
1010 * The tables should be in blocks of the following form:
1017 * To make the tables more manageable, subpages are allowed
1018 * and will be parsed recursively if $recursive == true.
1020 * @param string $code Language code
1021 * @param string $subpage Subpage name
1022 * @param bool $recursive Parse subpages recursively? Defaults to true.
1026 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1027 static $parsed = [];
1029 $key = 'Conversiontable/' . $code;
1031 $key .= '/' . $subpage;
1033 if ( array_key_exists( $key, $parsed ) ) {
1037 $parsed[$key] = true;
1039 if ( $subpage === '' ) {
1040 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1043 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1044 if ( $title && $title->exists() ) {
1045 $revision = Revision
::newFromTitle( $title );
1047 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1048 $txt = $revision->getContent( RevisionRecord
::RAW
)->getText();
1051 // @todo in the future, use a specialized content model, perhaps based on json!
1056 # Nothing to parse if there's no text
1057 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1061 // get all subpage links of the form
1062 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1063 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1065 $subs = StringUtils
::explode( '[[', $txt );
1067 foreach ( $subs as $sub ) {
1068 $link = explode( ']]', $sub, 2 );
1069 if ( count( $link ) != 2 ) {
1072 $b = explode( '|', $link[0], 2 );
1073 $b = explode( '/', trim( $b[0] ), 3 );
1074 if ( count( $b ) == 3 ) {
1080 if ( $b[0] == $linkhead && $b[1] == $code ) {
1081 $sublinks[] = $sublink;
1085 // parse the mappings in this page
1086 $blocks = StringUtils
::explode( '-{', $txt );
1089 foreach ( $blocks as $block ) {
1091 // Skip the part before the first -{
1095 $mappings = explode( '}-', $block, 2 )[0];
1096 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1097 $table = StringUtils
::explode( ';', $stripped );
1098 foreach ( $table as $t ) {
1099 $m = explode( '=>', $t, 3 );
1100 if ( count( $m ) != 2 ) {
1103 // trim any trailling comments starting with '//'
1104 $tt = explode( '//', $m[1], 2 );
1105 $ret[trim( $m[0] )] = trim( $tt[0] );
1109 // recursively parse the subpages
1111 foreach ( $sublinks as $link ) {
1112 $s = $this->parseCachedTable( $code, $link, $recursive );
1117 if ( $this->mUcfirst
) {
1118 foreach ( $ret as $k => $v ) {
1119 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1126 * Enclose a string with the "no conversion" tag. This is used by
1127 * various functions in the Parser.
1129 * @param string $text Text to be tagged for no conversion
1130 * @param bool $noParse Unused
1131 * @return string The tagged text
1133 public function markNoConversion( $text, $noParse = false ) {
1134 # don't mark if already marked
1135 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1139 $ret = "-{R|$text}-";
1144 * Convert the sorting key for category links. This should make different
1145 * keys that are variants of each other map to the same key.
1147 * @param string $key
1151 function convertCategoryKey( $key ) {
1156 * Refresh the cache of conversion tables when
1157 * MediaWiki:Conversiontable* is updated.
1159 * @param Title $titleobj The Title of the page being updated
1161 public function updateConversionTable( Title
$titleobj ) {
1162 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1163 $title = $titleobj->getDBkey();
1164 $t = explode( '/', $title, 3 );
1166 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1167 if ( $this->validateVariant( $t[1] ) ) {
1168 $this->reloadTables();
1175 * Get the cached separator pattern for ConverterRule::parseRules()
1178 function getVarSeparatorPattern() {
1179 if ( is_null( $this->mVarSeparatorPattern
) ) {
1180 // varsep_pattern for preg_split:
1181 // text should be splited by ";" only if a valid variant
1182 // name exist after the markup, for example:
1183 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1184 // <span style="font-size:120%;">yyy</span>;}-
1185 // we should split it as:
1187 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1188 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1191 $expandedVariants = [];
1192 foreach ( $this->mVariants
as $variant ) {
1193 $expandedVariants[ $variant ] = 1;
1194 // Accept standard BCP 47 names for variants as well.
1195 $expandedVariants[ LanguageCode
::bcp47( $variant ) ] = 1;
1197 // Accept old deprecated names for variants
1198 foreach ( LanguageCode
::getDeprecatedCodeMapping() as $old => $new ) {
1199 if ( isset( $expandedVariants[ $new ] ) ) {
1200 $expandedVariants[ $old ] = 1;
1205 foreach ( $expandedVariants as $variant => $ignore ) {
1206 // zh-hans:xxx;zh-hant:yyy
1207 $pat .= $variant . '\s*:|';
1208 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1209 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1212 $this->mVarSeparatorPattern
= $pat;
1214 return $this->mVarSeparatorPattern
;