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
;
26 * Base class for language conversion.
29 * @author Zhengzhu Feng <zhengzhu@gmail.com>
30 * @author fdcn <fdcn64@gmail.com>
31 * @author shinjiman <shinjiman@gmail.com>
32 * @author PhiLiP <philip.npc@gmail.com>
34 class LanguageConverter
{
36 * languages supporting variants
40 public static $languagesWithVariants = [
54 public $mMainLanguageCode;
60 public $mVariantFallbacks;
61 public $mVariantNames;
62 public $mTablesLoaded = false;
65 * @var ReplacementArray[]
66 * @phan-var array<string,ReplacementArray>
70 // 'bidirectional' 'unidirectional' 'disable' for each variant
75 public $mDescCodeSep = ':', $mDescVarSep = ';';
76 public $mUcfirst = false;
77 public $mConvRuleTitle = false;
80 public $mHeaderVariant;
81 public $mMaxDepth = 10;
82 public $mVarSeparatorPattern;
84 const CACHE_VERSION_KEY
= 'VERSION 7';
87 * @param Language $langobj
88 * @param string $maincode The main language code of this language
89 * @param string[] $variants The supported variants of this language
90 * @param array $variantfallbacks The fallback language of each variant
91 * @param array $flags Defining the custom strings that maps to the flags
92 * @param array $manualLevel Limit for supported variants
94 public function __construct( Language
$langobj, $maincode, $variants = [],
95 $variantfallbacks = [], $flags = [],
97 global $wgDisabledVariants;
98 $this->mLangObj
= $langobj;
99 $this->mMainLanguageCode
= $maincode;
100 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
101 $this->mVariantFallbacks
= $variantfallbacks;
102 $this->mVariantNames
= Language
::fetchLanguageNames();
104 // 'S' show converted text
105 // '+' add rules for alltext
106 // 'E' the gave flags is error
107 // these flags above are reserved for program
108 'A' => 'A', // add rule for convert code (all text convert)
109 'T' => 'T', // title convert
110 'R' => 'R', // raw content
111 'D' => 'D', // convert description (subclass implement)
112 '-' => '-', // remove convert (not implement)
113 'H' => 'H', // add rule for convert code (but no display in placed code)
114 'N' => 'N', // current variant name
116 $this->mFlags
= array_merge( $defaultflags, $flags );
117 foreach ( $this->mVariants
as $v ) {
118 if ( array_key_exists( $v, $manualLevel ) ) {
119 $this->mManualLevel
[$v] = $manualLevel[$v];
121 $this->mManualLevel
[$v] = 'bidirectional';
123 $this->mFlags
[$v] = $v;
128 * Get all valid variants.
129 * Call this instead of using $this->mVariants directly.
131 * @return string[] Contains all valid variants
133 public function getVariants() {
134 return $this->mVariants
;
138 * In case some variant is not defined in the markup, we need
139 * to have some fallback. For example, in zh, normally people
140 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
141 * when zh-sg is preferred but not defined, we will pick zh-hans
142 * in this case. Right now this is only used by zh.
144 * @param string $variant The language code of the variant
145 * @return string|array The code of the fallback language or the
146 * main code if there is no fallback
148 public function getVariantFallbacks( $variant ) {
149 return $this->mVariantFallbacks
[$variant] ??
$this->mMainLanguageCode
;
153 * Get the title produced by the conversion rule.
154 * @return string The converted title text
156 public function getConvRuleTitle() {
157 return $this->mConvRuleTitle
;
161 * Get preferred language variant.
162 * @return string The preferred language code
164 public function getPreferredVariant() {
165 global $wgDefaultLanguageVariant, $wgUser;
167 $req = $this->getURLVariant();
169 Hooks
::run( 'GetLangPreferredVariant', [ &$req ] );
171 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
172 $req = $this->getUserVariant();
174 $req = $this->getHeaderVariant();
177 if ( $wgDefaultLanguageVariant && !$req ) {
178 $req = $this->validateVariant( $wgDefaultLanguageVariant );
181 $req = $this->validateVariant( $req );
183 // This function, unlike the other get*Variant functions, is
184 // not memoized (i.e. there return value is not cached) since
185 // new information might appear during processing after this
190 return $this->mMainLanguageCode
;
194 * Get default variant.
195 * This function would not be affected by user's settings
196 * @return string The default variant code
198 public function getDefaultVariant() {
199 global $wgDefaultLanguageVariant;
201 $req = $this->getURLVariant();
204 $req = $this->getHeaderVariant();
207 if ( $wgDefaultLanguageVariant && !$req ) {
208 $req = $this->validateVariant( $wgDefaultLanguageVariant );
214 return $this->mMainLanguageCode
;
218 * Validate the variant and return an appropriate strict internal
219 * variant code if one exists. Compare to Language::hasVariant()
220 * which does a strict test.
222 * @param string|null $variant The variant to validate
223 * @return mixed Returns an equivalent valid variant code if possible,
226 public function validateVariant( $variant = null ) {
227 if ( $variant === null ) {
230 // Our internal variants are always lower-case; the variant we
231 // are validating may have mixed case.
232 $variant = LanguageCode
::replaceDeprecatedCodes( strtolower( $variant ) );
233 if ( in_array( $variant, $this->mVariants
) ) {
236 // Browsers are supposed to use BCP 47 standard in the
237 // Accept-Language header, but not all of our internal
238 // mediawiki variant codes are BCP 47. Map BCP 47 code
239 // to our internal code.
240 foreach ( $this->mVariants
as $v ) {
241 // Case-insensitive match (BCP 47 is mixed case)
242 if ( strtolower( LanguageCode
::bcp47( $v ) ) === $variant ) {
250 * Get the variant specified in the URL
252 * @return mixed Variant if one found, null otherwise
254 public function getURLVariant() {
257 if ( $this->mURLVariant
) {
258 return $this->mURLVariant
;
261 // see if the preference is set in the request
262 $ret = $wgRequest->getText( 'variant' );
265 $ret = $wgRequest->getVal( 'uselang' );
268 $this->mURLVariant
= $this->validateVariant( $ret );
269 return $this->mURLVariant
;
273 * Determine if the user has a variant set.
275 * @return mixed Variant if one found, null otherwise
277 protected function getUserVariant() {
280 // memoizing this function wreaks havoc on parserTest.php
282 if ( $this->mUserVariant ) {
283 return $this->mUserVariant;
287 // Get language variant preference from logged in users
288 // Don't call this on stub objects because that causes infinite
289 // recursion during initialisation
290 if ( !$wgUser->isSafeToLoad() ) {
293 if ( $wgUser->isLoggedIn() ) {
295 $this->mMainLanguageCode
==
296 MediaWikiServices
::getInstance()->getContentLanguage()->getCode()
298 $ret = $wgUser->getOption( 'variant' );
300 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
303 // figure out user lang without constructing wgLang to avoid
304 // infinite recursion
305 $ret = $wgUser->getOption( 'language' );
308 $this->mUserVariant
= $this->validateVariant( $ret );
309 return $this->mUserVariant
;
313 * Determine the language variant from the Accept-Language header.
315 * @return mixed Variant if one found, null otherwise
317 protected function getHeaderVariant() {
320 if ( $this->mHeaderVariant
) {
321 return $this->mHeaderVariant
;
324 // See if some supported language variant is set in the
326 $languages = array_keys( $wgRequest->getAcceptLang() );
327 if ( empty( $languages ) ) {
331 $fallbackLanguages = [];
332 foreach ( $languages as $language ) {
333 $this->mHeaderVariant
= $this->validateVariant( $language );
334 if ( $this->mHeaderVariant
) {
338 // To see if there are fallbacks of current language.
339 // We record these fallback variants, and process
341 $fallbacks = $this->getVariantFallbacks( $language );
342 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
343 $fallbackLanguages[] = $fallbacks;
344 } elseif ( is_array( $fallbacks ) ) {
346 array_merge( $fallbackLanguages, $fallbacks );
350 if ( !$this->mHeaderVariant
) {
351 // process fallback languages now
352 $fallback_languages = array_unique( $fallbackLanguages );
353 foreach ( $fallback_languages as $language ) {
354 $this->mHeaderVariant
= $this->validateVariant( $language );
355 if ( $this->mHeaderVariant
) {
361 return $this->mHeaderVariant
;
365 * Dictionary-based conversion.
366 * This function would not parse the conversion rules.
367 * If you want to parse rules, try to use convert() or
370 * @param string $text The text to be converted
371 * @param bool|string $toVariant The target language code
372 * @return string The converted text
374 public function autoConvert( $text, $toVariant = false ) {
378 $toVariant = $this->getPreferredVariant();
384 if ( $this->guessVariant( $text, $toVariant ) ) {
387 /* we convert everything except:
388 1. HTML markups (anything between < and >)
390 3. placeholders created by the parser
391 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
392 Minimize use of backtracking where possible.
394 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
396 // this one is needed when the text is inside an HTML markup
397 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
399 // Optimize for the common case where these tags have
400 // few or no children. Thus try and possesively get as much as
401 // possible, and only engage in backtracking when we hit a '<'.
403 // disable convert to variants between <code> tags
404 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
405 // disable conversion of <script> tags
406 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
407 // disable conversion of <pre> tags
408 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
409 // The "|.*+)" at the end, is in case we missed some part of html syntax,
410 // we will fail securely (hopefully) by matching the rest of the string.
411 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
413 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
414 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
419 // Guard against delimiter nulls in the input
420 // (should never happen: see T159174)
421 $text = str_replace( "\000", '', $text );
422 $text = str_replace( "\004", '', $text );
424 $markupMatches = null;
425 $elementMatches = null;
427 // We add a marker (\004) at the end of text, to ensure we always match the
428 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
429 while ( $startPos < strlen( $text ) ) {
430 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
431 $elementPos = $markupMatches[0][1];
432 $element = $markupMatches[0][0];
433 if ( $element === "\004" ) {
435 $elementPos = strlen( $text );
437 } elseif ( substr( $element, -1 ) === "\004" ) {
438 // This can sometimes happen if we have
439 // unclosed html tags (For example
440 // when converting a title attribute
441 // during a recursive call that contains
442 // a < e.g. <div title="<">.
443 $element = substr( $element, 0, -1 );
446 // If we hit here, then Language Converter could be tricked
447 // into doing an XSS, so we refuse to translate.
448 // If non-crazy input manages to reach this code path,
449 // we should consider it a bug.
450 $log = LoggerFactory
::getInstance( 'languageconverter' );
451 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
452 . ". Disabling language conversion for this page.",
454 "method" => __METHOD__
,
455 "variant" => $toVariant,
456 "startOfText" => substr( $text, 0, 500 )
461 // Queue the part before the markup for translation in a batch
462 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
464 // Advance to the next position
465 $startPos = $elementPos +
strlen( $element );
467 // Translate any alt or title attributes inside the matched element
469 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
471 // FIXME, this decodes entities, so if you have something
472 // like <div title="foo<bar"> the bar won't get
473 // translated since after entity decoding it looks like
474 // unclosed html and we call this method recursively
476 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
477 // Ensure self-closing tags stay self-closing.
478 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
480 foreach ( [ 'title', 'alt' ] as $attrName ) {
481 if ( !isset( $attrs[$attrName] ) ) {
484 $attr = $attrs[$attrName];
485 // Don't convert URLs
486 if ( !strpos( $attr, '://' ) ) {
487 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
490 if ( $attr !== $attrs[$attrName] ) {
491 $attrs[$attrName] = $attr;
496 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
497 $close . $elementMatches[3];
500 $literalBlob .= $element . "\000";
503 // Do the main translation batch
504 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
506 // Put the output back together
507 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
508 $literalIter = StringUtils
::explode( "\000", $literalBlob );
510 while ( $translatedIter->valid() && $literalIter->valid() ) {
511 $output .= $translatedIter->current();
512 $output .= $literalIter->current();
513 $translatedIter->next();
514 $literalIter->next();
521 * Translate a string to a variant.
522 * Doesn't parse rules or do any of that other stuff, for that use
523 * convert() or convertTo().
525 * @param string $text Text to convert
526 * @param string $variant Variant language code
527 * @return string Translated text
529 public function translate( $text, $variant ) {
530 // If $text is empty or only includes spaces, do nothing
531 // Otherwise translate it
532 if ( trim( $text ) ) {
534 $text = $this->mTables
[$variant]->replace( $text );
540 * Call translate() to convert text to all valid variants.
542 * @param string $text The text to be converted
543 * @return array Variant => converted text
545 public function autoConvertToAllVariants( $text ) {
549 foreach ( $this->mVariants
as $variant ) {
550 $ret[$variant] = $this->translate( $text, $variant );
557 * Apply manual conversion rules.
559 * @param ConverterRule $convRule
561 protected function applyManualConv( $convRule ) {
562 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
564 // T26072: $mConvRuleTitle was overwritten by other manual
565 // rule(s) not for title, this breaks the title conversion.
566 $newConvRuleTitle = $convRule->getTitle();
567 if ( $newConvRuleTitle ) {
568 // So I add an empty check for getTitle()
569 $this->mConvRuleTitle
= $newConvRuleTitle;
572 // merge/remove manual conversion rules to/from global table
573 $convTable = $convRule->getConvTable();
574 $action = $convRule->getRulesAction();
575 foreach ( $convTable as $variant => $pair ) {
576 $v = $this->validateVariant( $variant );
581 if ( $action == 'add' ) {
582 // More efficient than array_merge(), about 2.5 times.
583 foreach ( $pair as $from => $to ) {
584 $this->mTables
[$v]->setPair( $from, $to );
586 } elseif ( $action == 'remove' ) {
587 $this->mTables
[$v]->removeArray( $pair );
593 * Auto convert a Title object to a readable string in the
596 * @param Title $title A object of Title
597 * @return string Converted title text
599 public function convertTitle( $title ) {
600 $variant = $this->getPreferredVariant();
601 $index = $title->getNamespace();
602 if ( $index !== NS_MAIN
) {
603 $text = $this->convertNamespace( $index, $variant ) . ':';
607 $text .= $this->translate( $title->getText(), $variant );
612 * Get the namespace display name in the preferred variant.
614 * @param int $index Namespace id
615 * @param string|null $variant Variant code or null for preferred variant
616 * @return string Namespace name for display
618 public function convertNamespace( $index, $variant = null ) {
619 if ( $index === NS_MAIN
) {
623 if ( $variant === null ) {
624 $variant = $this->getPreferredVariant();
627 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
628 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
629 $nsVariantText = $cache->get( $key );
630 if ( $nsVariantText !== false ) {
631 return $nsVariantText;
634 // First check if a message gives a converted name in the target variant.
635 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
636 if ( $nsConvMsg->exists() ) {
637 $nsVariantText = $nsConvMsg->plain();
640 // Then check if a message gives a converted name in content language
641 // which needs extra translation to the target variant.
642 if ( $nsVariantText === false ) {
643 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
644 if ( $nsConvMsg->exists() ) {
645 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
649 if ( $nsVariantText === false ) {
650 // No message exists, retrieve it from the target variant's namespace names.
651 $langObj = $this->mLangObj
->factory( $variant );
652 $nsVariantText = $langObj->getFormattedNsText( $index );
655 $cache->set( $key, $nsVariantText, 60 );
657 return $nsVariantText;
661 * Convert text to different variants of a language. The automatic
662 * conversion is done in autoConvert(). Here we parse the text
663 * marked with -{}-, which specifies special conversions of the
664 * text that can not be accomplished in autoConvert().
666 * Syntax of the markup:
667 * -{code1:text1;code2:text2;...}- or
668 * -{flags|code1:text1;code2:text2;...}- or
669 * -{text}- in which case no conversion should take place for text
671 * @warning Glossary state is maintained between calls. Never feed this
672 * method input that hasn't properly been escaped as it may result in
673 * an XSS in subsequent calls, even if those subsequent calls properly
675 * @param string $text Text to be converted, already html escaped.
676 * @return string Converted text (html)
678 public function convert( $text ) {
679 $variant = $this->getPreferredVariant();
680 return $this->convertTo( $text, $variant );
684 * Same as convert() except a extra parameter to custom variant.
686 * @param string $text Text to be converted, already html escaped
687 * @param-taint $text exec_html
688 * @param string $variant The target variant code
689 * @return string Converted text
690 * @return-taint escaped
692 public function convertTo( $text, $variant ) {
693 global $wgDisableLangConversion;
694 if ( $wgDisableLangConversion ) {
697 // Reset converter state for a new converter run.
698 $this->mConvRuleTitle
= false;
699 return $this->recursiveConvertTopLevel( $text, $variant );
703 * Recursively convert text on the outside. Allow to use nested
704 * markups to custom rules.
706 * @param string $text Text to be converted
707 * @param string $variant The target variant code
708 * @param int $depth Depth of recursion
709 * @return string Converted text
711 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
714 $length = strlen( $text );
715 $shouldConvert = !$this->guessVariant( $text, $variant );
718 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
719 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
720 // phpcs:ignore Generic.Files.LineLength
721 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
722 while ( $startPos < $length && $continue ) {
723 $continue = preg_match(
724 // Only match -{ outside of html.
725 "/$noScript|$noStyle|$noHtml|-\{/",
733 // No more markup, append final segment
734 $fragment = substr( $text, $startPos );
735 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
739 // Offset of the match of the regex pattern.
742 // Append initial segment
743 $fragment = substr( $text, $startPos, $pos - $startPos );
744 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
745 // -{ marker found, not in attribute
746 // Advance position up to -{ marker.
748 // Do recursive conversion
749 // Note: This passes $startPos by reference, and advances it.
750 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
756 * Recursively convert text on the inside.
758 * @param string $text Text to be converted
759 * @param string $variant The target variant code
760 * @param int &$startPos
761 * @param int $depth Depth of recursion
763 * @throws MWException
764 * @return string Converted text
766 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
767 // Quick sanity check (no function calls)
768 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
769 throw new MWException( __METHOD__
. ': invalid input string' );
774 $warningDone = false;
775 $length = strlen( $text );
777 while ( $startPos < $length ) {
779 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
789 // Append initial segment
790 $inner .= substr( $text, $startPos, $pos - $startPos );
798 if ( $depth >= $this->mMaxDepth
) {
800 if ( !$warningDone ) {
801 $inner .= '<span class="error">' .
802 wfMessage( 'language-converter-depth-warning' )
803 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
810 // Recursively parse another rule
811 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
816 $rule = new ConverterRule( $inner, $this );
817 $rule->parse( $variant );
818 $this->applyManualConv( $rule );
819 return $rule->getDisplay();
821 throw new MWException( __METHOD__
. ': invalid regex match' );
826 if ( $startPos < $length ) {
827 $inner .= substr( $text, $startPos );
830 return '-{' . $this->autoConvert( $inner, $variant );
834 * If a language supports multiple variants, it is possible that
835 * non-existing link in one variant actually exists in another variant.
836 * This function tries to find it. See e.g. LanguageZh.php
837 * The input parameters may be modified upon return
839 * @param string &$link The name of the link
840 * @param Title &$nt The title object of the link
841 * @param bool $ignoreOtherCond To disable other conditions when
842 * we need to transclude a template or update a category's link
844 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
845 # If the article has already existed, there is no need to
846 # check it again, otherwise it may cause a fault.
847 if ( is_object( $nt ) && $nt->exists() ) {
851 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
852 $isredir = $wgRequest->getText( 'redirect', 'yes' );
853 $action = $wgRequest->getText( 'action' );
854 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
857 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
858 $disableLinkConversion = $wgDisableLangConversion
859 ||
$wgDisableTitleConversion;
860 $linkBatch = new LinkBatch();
864 if ( $disableLinkConversion ||
865 ( !$ignoreOtherCond &&
868 ||
$action == 'submit'
869 ||
$linkconvert == 'no' ) ) ) {
873 if ( is_object( $nt ) ) {
874 $ns = $nt->getNamespace();
877 $variants = $this->autoConvertToAllVariants( $link );
878 if ( !$variants ) { // give up
884 foreach ( $variants as $v ) {
886 $varnt = Title
::newFromText( $v, $ns );
887 if ( !is_null( $varnt ) ) {
888 $linkBatch->addObj( $varnt );
894 // fetch all variants in single query
895 $linkBatch->execute();
897 foreach ( $titles as $varnt ) {
898 if ( $varnt->getArticleID() > 0 ) {
900 $link = $varnt->getText();
907 * Returns language specific hash options.
911 public function getExtraHashOptions() {
912 $variant = $this->getPreferredVariant();
914 return '!' . $variant;
918 * Guess if a text is written in a variant. This should be implemented in subclasses.
920 * @param string $text The text to be checked
921 * @param string $variant Language code of the variant to be checked for
922 * @return bool True if $text appears to be written in $variant, false if not
924 * @author Nikola Smolenski <smolensk@eunet.rs>
927 public function guessVariant( $text, $variant ) {
932 * Load default conversion tables.
933 * This method must be implemented in derived class.
936 * @throws MWException
938 function loadDefaultTables() {
939 $class = static::class;
940 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
944 * Load conversion tables either from the cache or the disk.
946 * @param bool $fromCache Load from memcached? Defaults to true.
948 function loadTables( $fromCache = true ) {
949 global $wgLanguageConverterCacheType;
951 if ( $this->mTablesLoaded
) {
955 $this->mTablesLoaded
= true;
956 $this->mTables
= false;
957 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
958 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
960 $this->mTables
= $cache->get( $cacheKey );
962 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
963 // not in cache, or we need a fresh reload.
964 // We will first load the default tables
965 // then update them using things in MediaWiki:Conversiontable/*
966 $this->loadDefaultTables();
967 foreach ( $this->mVariants
as $var ) {
968 $cached = $this->parseCachedTable( $var );
969 $this->mTables
[$var]->mergeArray( $cached );
972 $this->postLoadTables();
973 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
975 $cache->set( $cacheKey, $this->mTables
, 43200 );
980 * Hook for post processing after conversion tables are loaded.
982 function postLoadTables() {
986 * Reload the conversion tables.
988 * Also used by test suites which need to reset the converter state.
992 private function reloadTables() {
993 if ( $this->mTables
) {
994 unset( $this->mTables
);
997 $this->mTablesLoaded
= false;
998 $this->loadTables( false );
1002 * Parse the conversion table stored in the cache.
1004 * The tables should be in blocks of the following form:
1011 * To make the tables more manageable, subpages are allowed
1012 * and will be parsed recursively if $recursive == true.
1014 * @param string $code Language code
1015 * @param string $subpage Subpage name
1016 * @param bool $recursive Parse subpages recursively? Defaults to true.
1020 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1021 static $parsed = [];
1023 $key = 'Conversiontable/' . $code;
1025 $key .= '/' . $subpage;
1027 if ( array_key_exists( $key, $parsed ) ) {
1031 $parsed[$key] = true;
1033 if ( $subpage === '' ) {
1034 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1037 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1038 if ( $title && $title->exists() ) {
1039 $revision = Revision
::newFromTitle( $title );
1041 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1042 $txt = $revision->getContent( Revision
::RAW
)->getText();
1045 // @todo in the future, use a specialized content model, perhaps based on json!
1050 # Nothing to parse if there's no text
1051 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1055 // get all subpage links of the form
1056 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1057 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1059 $subs = StringUtils
::explode( '[[', $txt );
1061 foreach ( $subs as $sub ) {
1062 $link = explode( ']]', $sub, 2 );
1063 if ( count( $link ) != 2 ) {
1066 $b = explode( '|', $link[0], 2 );
1067 $b = explode( '/', trim( $b[0] ), 3 );
1068 if ( count( $b ) == 3 ) {
1074 if ( $b[0] == $linkhead && $b[1] == $code ) {
1075 $sublinks[] = $sublink;
1079 // parse the mappings in this page
1080 $blocks = StringUtils
::explode( '-{', $txt );
1083 foreach ( $blocks as $block ) {
1085 // Skip the part before the first -{
1089 $mappings = explode( '}-', $block, 2 )[0];
1090 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1091 $table = StringUtils
::explode( ';', $stripped );
1092 foreach ( $table as $t ) {
1093 $m = explode( '=>', $t, 3 );
1094 if ( count( $m ) != 2 ) {
1097 // trim any trailling comments starting with '//'
1098 $tt = explode( '//', $m[1], 2 );
1099 $ret[trim( $m[0] )] = trim( $tt[0] );
1103 // recursively parse the subpages
1105 foreach ( $sublinks as $link ) {
1106 $s = $this->parseCachedTable( $code, $link, $recursive );
1111 if ( $this->mUcfirst
) {
1112 foreach ( $ret as $k => $v ) {
1113 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1120 * Enclose a string with the "no conversion" tag. This is used by
1121 * various functions in the Parser.
1123 * @param string $text Text to be tagged for no conversion
1124 * @param bool $noParse Unused
1125 * @return string The tagged text
1127 public function markNoConversion( $text, $noParse = false ) {
1128 # don't mark if already marked
1129 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1133 $ret = "-{R|$text}-";
1138 * Convert the sorting key for category links. This should make different
1139 * keys that are variants of each other map to the same key.
1141 * @param string $key
1145 function convertCategoryKey( $key ) {
1150 * Refresh the cache of conversion tables when
1151 * MediaWiki:Conversiontable* is updated.
1153 * @param Title $titleobj The Title of the page being updated
1155 public function updateConversionTable( Title
$titleobj ) {
1156 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1157 $title = $titleobj->getDBkey();
1158 $t = explode( '/', $title, 3 );
1160 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1161 if ( $this->validateVariant( $t[1] ) ) {
1162 $this->reloadTables();
1169 * Get the cached separator pattern for ConverterRule::parseRules()
1172 function getVarSeparatorPattern() {
1173 if ( is_null( $this->mVarSeparatorPattern
) ) {
1174 // varsep_pattern for preg_split:
1175 // text should be splited by ";" only if a valid variant
1176 // name exist after the markup, for example:
1177 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1178 // <span style="font-size:120%;">yyy</span>;}-
1179 // we should split it as:
1181 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1182 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1185 $expandedVariants = [];
1186 foreach ( $this->mVariants
as $variant ) {
1187 $expandedVariants[ $variant ] = 1;
1188 // Accept standard BCP 47 names for variants as well.
1189 $expandedVariants[ LanguageCode
::bcp47( $variant ) ] = 1;
1191 // Accept old deprecated names for variants
1192 foreach ( LanguageCode
::getDeprecatedCodeMapping() as $old => $new ) {
1193 if ( isset( $expandedVariants[ $new ] ) ) {
1194 $expandedVariants[ $old ] = 1;
1199 foreach ( $expandedVariants as $variant => $ignore ) {
1200 // zh-hans:xxx;zh-hant:yyy
1201 $pat .= $variant . '\s*:|';
1202 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1203 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1206 $this->mVarSeparatorPattern
= $pat;
1208 return $this->mVarSeparatorPattern
;