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 static public $languagesWithVariants = [
54 public $mMainLanguageCode;
60 public $mVariantFallbacks;
61 public $mVariantNames;
62 public $mTablesLoaded = false;
64 // 'bidirectional' 'unidirectional' 'disable' for each variant
69 public $mDescCodeSep = ':', $mDescVarSep = ';';
70 public $mUcfirst = false;
71 public $mConvRuleTitle = false;
74 public $mHeaderVariant;
75 public $mMaxDepth = 10;
76 public $mVarSeparatorPattern;
78 const CACHE_VERSION_KEY
= 'VERSION 7';
81 * @param Language $langobj
82 * @param string $maincode The main language code of this language
83 * @param string[] $variants The supported variants of this language
84 * @param array $variantfallbacks The fallback language of each variant
85 * @param array $flags Defining the custom strings that maps to the flags
86 * @param array $manualLevel Limit for supported variants
88 public function __construct( $langobj, $maincode, $variants = [],
89 $variantfallbacks = [], $flags = [],
91 global $wgDisabledVariants;
92 $this->mLangObj
= $langobj;
93 $this->mMainLanguageCode
= $maincode;
94 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
95 $this->mVariantFallbacks
= $variantfallbacks;
96 $this->mVariantNames
= Language
::fetchLanguageNames();
98 // 'S' show converted text
99 // '+' add rules for alltext
100 // 'E' the gave flags is error
101 // these flags above are reserved for program
102 'A' => 'A', // add rule for convert code (all text convert)
103 'T' => 'T', // title convert
104 'R' => 'R', // raw content
105 'D' => 'D', // convert description (subclass implement)
106 '-' => '-', // remove convert (not implement)
107 'H' => 'H', // add rule for convert code (but no display in placed code)
108 'N' => 'N', // current variant name
110 $this->mFlags
= array_merge( $defaultflags, $flags );
111 foreach ( $this->mVariants
as $v ) {
112 if ( array_key_exists( $v, $manualLevel ) ) {
113 $this->mManualLevel
[$v] = $manualLevel[$v];
115 $this->mManualLevel
[$v] = 'bidirectional';
117 $this->mFlags
[$v] = $v;
122 * Get all valid variants.
123 * Call this instead of using $this->mVariants directly.
125 * @return string[] Contains all valid variants
127 public function getVariants() {
128 return $this->mVariants
;
132 * In case some variant is not defined in the markup, we need
133 * to have some fallback. For example, in zh, normally people
134 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
135 * when zh-sg is preferred but not defined, we will pick zh-hans
136 * in this case. Right now this is only used by zh.
138 * @param string $variant The language code of the variant
139 * @return string|array The code of the fallback language or the
140 * main code if there is no fallback
142 public function getVariantFallbacks( $variant ) {
143 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
144 return $this->mVariantFallbacks
[$variant];
146 return $this->mMainLanguageCode
;
150 * Get the title produced by the conversion rule.
151 * @return string The converted title text
153 public function getConvRuleTitle() {
154 return $this->mConvRuleTitle
;
158 * Get preferred language variant.
159 * @return string The preferred language code
161 public function getPreferredVariant() {
162 global $wgDefaultLanguageVariant, $wgUser;
164 $req = $this->getURLVariant();
166 Hooks
::run( 'GetLangPreferredVariant', [ &$req ] );
168 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
169 $req = $this->getUserVariant();
171 $req = $this->getHeaderVariant();
174 if ( $wgDefaultLanguageVariant && !$req ) {
175 $req = $this->validateVariant( $wgDefaultLanguageVariant );
178 $req = $this->validateVariant( $req );
180 // This function, unlike the other get*Variant functions, is
181 // not memoized (i.e. there return value is not cached) since
182 // new information might appear during processing after this
187 return $this->mMainLanguageCode
;
191 * Get default variant.
192 * This function would not be affected by user's settings
193 * @return string The default variant code
195 public function getDefaultVariant() {
196 global $wgDefaultLanguageVariant;
198 $req = $this->getURLVariant();
201 $req = $this->getHeaderVariant();
204 if ( $wgDefaultLanguageVariant && !$req ) {
205 $req = $this->validateVariant( $wgDefaultLanguageVariant );
211 return $this->mMainLanguageCode
;
215 * Validate the variant
216 * @param string|null $variant The variant to validate
217 * @return mixed Returns the variant if it is valid, null otherwise
219 public function validateVariant( $variant = null ) {
220 if ( $variant === null ) {
223 // Our internal variants are always lower-case; the variant we
224 // are validating may have mixed case.
225 $variant = LanguageCode
::replaceDeprecatedCodes( strtolower( $variant ) );
226 if ( in_array( $variant, $this->mVariants
) ) {
229 // Browsers are supposed to use BCP 47 standard in the
230 // Accept-Language header, but not all of our internal
231 // mediawiki variant codes are BCP 47. Map BCP 47 code
232 // to our internal code.
233 foreach ( $this->mVariants
as $v ) {
234 // Case-insensitive match (BCP 47 is mixed case)
235 if ( strtolower( LanguageCode
::bcp47( $v ) ) === $variant ) {
243 * Get the variant specified in the URL
245 * @return mixed Variant if one found, null otherwise
247 public function getURLVariant() {
250 if ( $this->mURLVariant
) {
251 return $this->mURLVariant
;
254 // see if the preference is set in the request
255 $ret = $wgRequest->getText( 'variant' );
258 $ret = $wgRequest->getVal( 'uselang' );
261 $this->mURLVariant
= $this->validateVariant( $ret );
262 return $this->mURLVariant
;
266 * Determine if the user has a variant set.
268 * @return mixed Variant if one found, null otherwise
270 protected function getUserVariant() {
271 global $wgUser, $wgContLang;
273 // memoizing this function wreaks havoc on parserTest.php
275 if ( $this->mUserVariant ) {
276 return $this->mUserVariant;
280 // Get language variant preference from logged in users
281 // Don't call this on stub objects because that causes infinite
282 // recursion during initialisation
283 if ( !$wgUser->isSafeToLoad() ) {
286 if ( $wgUser->isLoggedIn() ) {
287 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
288 $ret = $wgUser->getOption( 'variant' );
290 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
293 // figure out user lang without constructing wgLang to avoid
294 // infinite recursion
295 $ret = $wgUser->getOption( 'language' );
298 $this->mUserVariant
= $this->validateVariant( $ret );
299 return $this->mUserVariant
;
303 * Determine the language variant from the Accept-Language header.
305 * @return mixed Variant if one found, null otherwise
307 protected function getHeaderVariant() {
310 if ( $this->mHeaderVariant
) {
311 return $this->mHeaderVariant
;
314 // See if some supported language variant is set in the
316 $languages = array_keys( $wgRequest->getAcceptLang() );
317 if ( empty( $languages ) ) {
321 $fallbackLanguages = [];
322 foreach ( $languages as $language ) {
323 $this->mHeaderVariant
= $this->validateVariant( $language );
324 if ( $this->mHeaderVariant
) {
328 // To see if there are fallbacks of current language.
329 // We record these fallback variants, and process
331 $fallbacks = $this->getVariantFallbacks( $language );
332 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
333 $fallbackLanguages[] = $fallbacks;
334 } elseif ( is_array( $fallbacks ) ) {
336 array_merge( $fallbackLanguages, $fallbacks );
340 if ( !$this->mHeaderVariant
) {
341 // process fallback languages now
342 $fallback_languages = array_unique( $fallbackLanguages );
343 foreach ( $fallback_languages as $language ) {
344 $this->mHeaderVariant
= $this->validateVariant( $language );
345 if ( $this->mHeaderVariant
) {
351 return $this->mHeaderVariant
;
355 * Dictionary-based conversion.
356 * This function would not parse the conversion rules.
357 * If you want to parse rules, try to use convert() or
360 * @param string $text The text to be converted
361 * @param bool|string $toVariant The target language code
362 * @return string The converted text
364 public function autoConvert( $text, $toVariant = false ) {
368 $toVariant = $this->getPreferredVariant();
374 if ( $this->guessVariant( $text, $toVariant ) ) {
377 /* we convert everything except:
378 1. HTML markups (anything between < and >)
380 3. placeholders created by the parser
381 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
382 Minimize use of backtracking where possible.
384 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
386 // this one is needed when the text is inside an HTML markup
387 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
389 // Optimize for the common case where these tags have
390 // few or no children. Thus try and possesively get as much as
391 // possible, and only engage in backtracking when we hit a '<'.
393 // disable convert to variants between <code> tags
394 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
395 // disable conversion of <script> tags
396 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
397 // disable conversion of <pre> tags
398 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
399 // The "|.*+)" at the end, is in case we missed some part of html syntax,
400 // we will fail securely (hopefully) by matching the rest of the string.
401 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
403 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
404 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
409 // Guard against delimiter nulls in the input
410 // (should never happen: see T159174)
411 $text = str_replace( "\000", '', $text );
412 $text = str_replace( "\004", '', $text );
414 $markupMatches = null;
415 $elementMatches = null;
417 // We add a marker (\004) at the end of text, to ensure we always match the
418 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
419 while ( $startPos < strlen( $text ) ) {
420 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
421 $elementPos = $markupMatches[0][1];
422 $element = $markupMatches[0][0];
423 if ( $element === "\004" ) {
425 $elementPos = strlen( $text );
427 } elseif ( substr( $element, -1 ) === "\004" ) {
428 // This can sometimes happen if we have
429 // unclosed html tags (For example
430 // when converting a title attribute
431 // during a recursive call that contains
432 // a < e.g. <div title="<">.
433 $element = substr( $element, 0, -1 );
436 // If we hit here, then Language Converter could be tricked
437 // into doing an XSS, so we refuse to translate.
438 // If non-crazy input manages to reach this code path,
439 // we should consider it a bug.
440 $log = LoggerFactory
::getInstance( 'languageconverter' );
441 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
442 . ". Disabling language conversion for this page.",
444 "method" => __METHOD__
,
445 "variant" => $toVariant,
446 "startOfText" => substr( $text, 0, 500 )
451 // Queue the part before the markup for translation in a batch
452 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
454 // Advance to the next position
455 $startPos = $elementPos +
strlen( $element );
457 // Translate any alt or title attributes inside the matched element
459 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
461 // FIXME, this decodes entities, so if you have something
462 // like <div title="foo<bar"> the bar won't get
463 // translated since after entity decoding it looks like
464 // unclosed html and we call this method recursively
466 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
467 // Ensure self-closing tags stay self-closing.
468 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
470 foreach ( [ 'title', 'alt' ] as $attrName ) {
471 if ( !isset( $attrs[$attrName] ) ) {
474 $attr = $attrs[$attrName];
475 // Don't convert URLs
476 if ( !strpos( $attr, '://' ) ) {
477 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
480 if ( $attr !== $attrs[$attrName] ) {
481 $attrs[$attrName] = $attr;
486 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
487 $close . $elementMatches[3];
490 $literalBlob .= $element . "\000";
493 // Do the main translation batch
494 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
496 // Put the output back together
497 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
498 $literalIter = StringUtils
::explode( "\000", $literalBlob );
500 while ( $translatedIter->valid() && $literalIter->valid() ) {
501 $output .= $translatedIter->current();
502 $output .= $literalIter->current();
503 $translatedIter->next();
504 $literalIter->next();
511 * Translate a string to a variant.
512 * Doesn't parse rules or do any of that other stuff, for that use
513 * convert() or convertTo().
515 * @param string $text Text to convert
516 * @param string $variant Variant language code
517 * @return string Translated text
519 public function translate( $text, $variant ) {
520 // If $text is empty or only includes spaces, do nothing
521 // Otherwise translate it
522 if ( trim( $text ) ) {
524 $text = $this->mTables
[$variant]->replace( $text );
530 * Call translate() to convert text to all valid variants.
532 * @param string $text The text to be converted
533 * @return array Variant => converted text
535 public function autoConvertToAllVariants( $text ) {
539 foreach ( $this->mVariants
as $variant ) {
540 $ret[$variant] = $this->translate( $text, $variant );
547 * Apply manual conversion rules.
549 * @param ConverterRule $convRule
551 protected function applyManualConv( $convRule ) {
552 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
554 // T26072: $mConvRuleTitle was overwritten by other manual
555 // rule(s) not for title, this breaks the title conversion.
556 $newConvRuleTitle = $convRule->getTitle();
557 if ( $newConvRuleTitle ) {
558 // So I add an empty check for getTitle()
559 $this->mConvRuleTitle
= $newConvRuleTitle;
562 // merge/remove manual conversion rules to/from global table
563 $convTable = $convRule->getConvTable();
564 $action = $convRule->getRulesAction();
565 foreach ( $convTable as $variant => $pair ) {
566 $v = $this->validateVariant( $variant );
571 if ( $action == 'add' ) {
572 // More efficient than array_merge(), about 2.5 times.
573 foreach ( $pair as $from => $to ) {
574 $this->mTables
[$v]->setPair( $from, $to );
576 } elseif ( $action == 'remove' ) {
577 $this->mTables
[$v]->removeArray( $pair );
583 * Auto convert a Title object to a readable string in the
586 * @param Title $title A object of Title
587 * @return string Converted title text
589 public function convertTitle( $title ) {
590 $variant = $this->getPreferredVariant();
591 $index = $title->getNamespace();
592 if ( $index !== NS_MAIN
) {
593 $text = $this->convertNamespace( $index, $variant ) . ':';
597 $text .= $this->translate( $title->getText(), $variant );
602 * Get the namespace display name in the preferred variant.
604 * @param int $index Namespace id
605 * @param string|null $variant Variant code or null for preferred variant
606 * @return string Namespace name for display
608 public function convertNamespace( $index, $variant = null ) {
609 if ( $index === NS_MAIN
) {
613 if ( $variant === null ) {
614 $variant = $this->getPreferredVariant();
617 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
618 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
619 $nsVariantText = $cache->get( $key );
620 if ( $nsVariantText !== false ) {
621 return $nsVariantText;
624 // First check if a message gives a converted name in the target variant.
625 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
626 if ( $nsConvMsg->exists() ) {
627 $nsVariantText = $nsConvMsg->plain();
630 // Then check if a message gives a converted name in content language
631 // which needs extra translation to the target variant.
632 if ( $nsVariantText === false ) {
633 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
634 if ( $nsConvMsg->exists() ) {
635 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
639 if ( $nsVariantText === false ) {
640 // No message exists, retrieve it from the target variant's namespace names.
641 $langObj = $this->mLangObj
->factory( $variant );
642 $nsVariantText = $langObj->getFormattedNsText( $index );
645 $cache->set( $key, $nsVariantText, 60 );
647 return $nsVariantText;
651 * Convert text to different variants of a language. The automatic
652 * conversion is done in autoConvert(). Here we parse the text
653 * marked with -{}-, which specifies special conversions of the
654 * text that can not be accomplished in autoConvert().
656 * Syntax of the markup:
657 * -{code1:text1;code2:text2;...}- or
658 * -{flags|code1:text1;code2:text2;...}- or
659 * -{text}- in which case no conversion should take place for text
661 * @param string $text Text to be converted
662 * @return string Converted text
664 public function convert( $text ) {
665 $variant = $this->getPreferredVariant();
666 return $this->convertTo( $text, $variant );
670 * Same as convert() except a extra parameter to custom variant.
672 * @param string $text Text to be converted
673 * @param string $variant The target variant code
674 * @return string Converted text
676 public function convertTo( $text, $variant ) {
677 global $wgDisableLangConversion;
678 if ( $wgDisableLangConversion ) {
681 // Reset converter state for a new converter run.
682 $this->mConvRuleTitle
= false;
683 return $this->recursiveConvertTopLevel( $text, $variant );
687 * Recursively convert text on the outside. Allow to use nested
688 * markups to custom rules.
690 * @param string $text Text to be converted
691 * @param string $variant The target variant code
692 * @param int $depth Depth of recursion
693 * @return string Converted text
695 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
698 $length = strlen( $text );
699 $shouldConvert = !$this->guessVariant( $text, $variant );
702 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
703 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
704 // phpcs:ignore Generic.Files.LineLength
705 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
706 while ( $startPos < $length && $continue ) {
707 $continue = preg_match(
708 // Only match -{ outside of html.
709 "/$noScript|$noStyle|$noHtml|-\{/",
717 // No more markup, append final segment
718 $fragment = substr( $text, $startPos );
719 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
723 // Offset of the match of the regex pattern.
726 // Append initial segment
727 $fragment = substr( $text, $startPos, $pos - $startPos );
728 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
729 // -{ marker found, not in attribute
730 // Advance position up to -{ marker.
732 // Do recursive conversion
733 // Note: This passes $startPos by reference, and advances it.
734 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
740 * Recursively convert text on the inside.
742 * @param string $text Text to be converted
743 * @param string $variant The target variant code
744 * @param int &$startPos
745 * @param int $depth Depth of recursion
747 * @throws MWException
748 * @return string Converted text
750 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
751 // Quick sanity check (no function calls)
752 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
753 throw new MWException( __METHOD__
. ': invalid input string' );
758 $warningDone = false;
759 $length = strlen( $text );
761 while ( $startPos < $length ) {
763 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
773 // Append initial segment
774 $inner .= substr( $text, $startPos, $pos - $startPos );
782 if ( $depth >= $this->mMaxDepth
) {
784 if ( !$warningDone ) {
785 $inner .= '<span class="error">' .
786 wfMessage( 'language-converter-depth-warning' )
787 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
794 // Recursively parse another rule
795 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
800 $rule = new ConverterRule( $inner, $this );
801 $rule->parse( $variant );
802 $this->applyManualConv( $rule );
803 return $rule->getDisplay();
805 throw new MWException( __METHOD__
. ': invalid regex match' );
810 if ( $startPos < $length ) {
811 $inner .= substr( $text, $startPos );
814 return '-{' . $this->autoConvert( $inner, $variant );
818 * If a language supports multiple variants, it is possible that
819 * non-existing link in one variant actually exists in another variant.
820 * This function tries to find it. See e.g. LanguageZh.php
821 * The input parameters may be modified upon return
823 * @param string &$link The name of the link
824 * @param Title &$nt The title object of the link
825 * @param bool $ignoreOtherCond To disable other conditions when
826 * we need to transclude a template or update a category's link
828 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
829 # If the article has already existed, there is no need to
830 # check it again, otherwise it may cause a fault.
831 if ( is_object( $nt ) && $nt->exists() ) {
835 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
836 $isredir = $wgRequest->getText( 'redirect', 'yes' );
837 $action = $wgRequest->getText( 'action' );
838 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
841 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
842 $disableLinkConversion = $wgDisableLangConversion
843 ||
$wgDisableTitleConversion;
844 $linkBatch = new LinkBatch();
848 if ( $disableLinkConversion ||
849 ( !$ignoreOtherCond &&
852 ||
$action == 'submit'
853 ||
$linkconvert == 'no' ) ) ) {
857 if ( is_object( $nt ) ) {
858 $ns = $nt->getNamespace();
861 $variants = $this->autoConvertToAllVariants( $link );
862 if ( !$variants ) { // give up
868 foreach ( $variants as $v ) {
870 $varnt = Title
::newFromText( $v, $ns );
871 if ( !is_null( $varnt ) ) {
872 $linkBatch->addObj( $varnt );
878 // fetch all variants in single query
879 $linkBatch->execute();
881 foreach ( $titles as $varnt ) {
882 if ( $varnt->getArticleID() > 0 ) {
884 $link = $varnt->getText();
891 * Returns language specific hash options.
895 public function getExtraHashOptions() {
896 $variant = $this->getPreferredVariant();
898 return '!' . $variant;
902 * Guess if a text is written in a variant. This should be implemented in subclasses.
904 * @param string $text The text to be checked
905 * @param string $variant Language code of the variant to be checked for
906 * @return bool True if $text appears to be written in $variant, false if not
908 * @author Nikola Smolenski <smolensk@eunet.rs>
911 public function guessVariant( $text, $variant ) {
916 * Load default conversion tables.
917 * This method must be implemented in derived class.
920 * @throws MWException
922 function loadDefaultTables() {
923 $class = static::class;
924 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
928 * Load conversion tables either from the cache or the disk.
930 * @param bool $fromCache Load from memcached? Defaults to true.
932 function loadTables( $fromCache = true ) {
933 global $wgLanguageConverterCacheType;
935 if ( $this->mTablesLoaded
) {
939 $this->mTablesLoaded
= true;
940 $this->mTables
= false;
941 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
942 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
944 $this->mTables
= $cache->get( $cacheKey );
946 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
947 // not in cache, or we need a fresh reload.
948 // We will first load the default tables
949 // then update them using things in MediaWiki:Conversiontable/*
950 $this->loadDefaultTables();
951 foreach ( $this->mVariants
as $var ) {
952 $cached = $this->parseCachedTable( $var );
953 $this->mTables
[$var]->mergeArray( $cached );
956 $this->postLoadTables();
957 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
959 $cache->set( $cacheKey, $this->mTables
, 43200 );
964 * Hook for post processing after conversion tables are loaded.
966 function postLoadTables() {
970 * Reload the conversion tables.
972 * Also used by test suites which need to reset the converter state.
976 private function reloadTables() {
977 if ( $this->mTables
) {
978 unset( $this->mTables
);
981 $this->mTablesLoaded
= false;
982 $this->loadTables( false );
986 * Parse the conversion table stored in the cache.
988 * The tables should be in blocks of the following form:
995 * To make the tables more manageable, subpages are allowed
996 * and will be parsed recursively if $recursive == true.
998 * @param string $code Language code
999 * @param string $subpage Subpage name
1000 * @param bool $recursive Parse subpages recursively? Defaults to true.
1004 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1005 static $parsed = [];
1007 $key = 'Conversiontable/' . $code;
1009 $key .= '/' . $subpage;
1011 if ( array_key_exists( $key, $parsed ) ) {
1015 $parsed[$key] = true;
1017 if ( $subpage === '' ) {
1018 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1021 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1022 if ( $title && $title->exists() ) {
1023 $revision = Revision
::newFromTitle( $title );
1025 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1026 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
1029 // @todo in the future, use a specialized content model, perhaps based on json!
1034 # Nothing to parse if there's no text
1035 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1039 // get all subpage links of the form
1040 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1041 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1043 $subs = StringUtils
::explode( '[[', $txt );
1045 foreach ( $subs as $sub ) {
1046 $link = explode( ']]', $sub, 2 );
1047 if ( count( $link ) != 2 ) {
1050 $b = explode( '|', $link[0], 2 );
1051 $b = explode( '/', trim( $b[0] ), 3 );
1052 if ( count( $b ) == 3 ) {
1058 if ( $b[0] == $linkhead && $b[1] == $code ) {
1059 $sublinks[] = $sublink;
1063 // parse the mappings in this page
1064 $blocks = StringUtils
::explode( '-{', $txt );
1067 foreach ( $blocks as $block ) {
1069 // Skip the part before the first -{
1073 $mappings = explode( '}-', $block, 2 )[0];
1074 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1075 $table = StringUtils
::explode( ';', $stripped );
1076 foreach ( $table as $t ) {
1077 $m = explode( '=>', $t, 3 );
1078 if ( count( $m ) != 2 ) {
1081 // trim any trailling comments starting with '//'
1082 $tt = explode( '//', $m[1], 2 );
1083 $ret[trim( $m[0] )] = trim( $tt[0] );
1087 // recursively parse the subpages
1089 foreach ( $sublinks as $link ) {
1090 $s = $this->parseCachedTable( $code, $link, $recursive );
1095 if ( $this->mUcfirst
) {
1096 foreach ( $ret as $k => $v ) {
1097 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1104 * Enclose a string with the "no conversion" tag. This is used by
1105 * various functions in the Parser.
1107 * @param string $text Text to be tagged for no conversion
1108 * @param bool $noParse Unused
1109 * @return string The tagged text
1111 public function markNoConversion( $text, $noParse = false ) {
1112 # don't mark if already marked
1113 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1117 $ret = "-{R|$text}-";
1122 * Convert the sorting key for category links. This should make different
1123 * keys that are variants of each other map to the same key.
1125 * @param string $key
1129 function convertCategoryKey( $key ) {
1134 * Refresh the cache of conversion tables when
1135 * MediaWiki:Conversiontable* is updated.
1137 * @param Title $titleobj The Title of the page being updated
1139 public function updateConversionTable( Title
$titleobj ) {
1140 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1141 $title = $titleobj->getDBkey();
1142 $t = explode( '/', $title, 3 );
1144 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1145 if ( $this->validateVariant( $t[1] ) ) {
1146 $this->reloadTables();
1153 * Get the cached separator pattern for ConverterRule::parseRules()
1156 function getVarSeparatorPattern() {
1157 if ( is_null( $this->mVarSeparatorPattern
) ) {
1158 // varsep_pattern for preg_split:
1159 // text should be splited by ";" only if a valid variant
1160 // name exist after the markup, for example:
1161 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1162 // <span style="font-size:120%;">yyy</span>;}-
1163 // we should split it as:
1165 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1166 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1170 foreach ( $this->mVariants
as $variant ) {
1171 // zh-hans:xxx;zh-hant:yyy
1172 $pat .= $variant . '\s*:|';
1173 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1174 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1177 $this->mVarSeparatorPattern
= $pat;
1179 return $this->mVarSeparatorPattern
;