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 // This function, unlike the other get*Variant functions, is
179 // not memoized (i.e. there return value is not cached) since
180 // new information might appear during processing after this
182 if ( $this->validateVariant( $req ) ) {
185 return $this->mMainLanguageCode
;
189 * Get default variant.
190 * This function would not be affected by user's settings
191 * @return string The default variant code
193 public function getDefaultVariant() {
194 global $wgDefaultLanguageVariant;
196 $req = $this->getURLVariant();
199 $req = $this->getHeaderVariant();
202 if ( $wgDefaultLanguageVariant && !$req ) {
203 $req = $this->validateVariant( $wgDefaultLanguageVariant );
209 return $this->mMainLanguageCode
;
213 * Validate the variant
214 * @param string|null $variant The variant to validate
215 * @return mixed Returns the variant if it is valid, null otherwise
217 public function validateVariant( $variant = null ) {
218 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
225 * Get the variant specified in the URL
227 * @return mixed Variant if one found, null otherwise
229 public function getURLVariant() {
232 if ( $this->mURLVariant
) {
233 return $this->mURLVariant
;
236 // see if the preference is set in the request
237 $ret = $wgRequest->getText( 'variant' );
240 $ret = $wgRequest->getVal( 'uselang' );
243 $this->mURLVariant
= $this->validateVariant( $ret );
244 return $this->mURLVariant
;
248 * Determine if the user has a variant set.
250 * @return mixed Variant if one found, null otherwise
252 protected function getUserVariant() {
253 global $wgUser, $wgContLang;
255 // memoizing this function wreaks havoc on parserTest.php
257 if ( $this->mUserVariant ) {
258 return $this->mUserVariant;
262 // Get language variant preference from logged in users
263 // Don't call this on stub objects because that causes infinite
264 // recursion during initialisation
265 if ( !$wgUser->isSafeToLoad() ) {
268 if ( $wgUser->isLoggedIn() ) {
269 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
270 $ret = $wgUser->getOption( 'variant' );
272 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
275 // figure out user lang without constructing wgLang to avoid
276 // infinite recursion
277 $ret = $wgUser->getOption( 'language' );
280 $this->mUserVariant
= $this->validateVariant( $ret );
281 return $this->mUserVariant
;
285 * Determine the language variant from the Accept-Language header.
287 * @return mixed Variant if one found, null otherwise
289 protected function getHeaderVariant() {
292 if ( $this->mHeaderVariant
) {
293 return $this->mHeaderVariant
;
296 // see if some supported language variant is set in the
298 $languages = array_keys( $wgRequest->getAcceptLang() );
299 if ( empty( $languages ) ) {
303 $fallbackLanguages = [];
304 foreach ( $languages as $language ) {
305 $this->mHeaderVariant
= $this->validateVariant( $language );
306 if ( $this->mHeaderVariant
) {
310 // To see if there are fallbacks of current language.
311 // We record these fallback variants, and process
313 $fallbacks = $this->getVariantFallbacks( $language );
314 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
315 $fallbackLanguages[] = $fallbacks;
316 } elseif ( is_array( $fallbacks ) ) {
318 array_merge( $fallbackLanguages, $fallbacks );
322 if ( !$this->mHeaderVariant
) {
323 // process fallback languages now
324 $fallback_languages = array_unique( $fallbackLanguages );
325 foreach ( $fallback_languages as $language ) {
326 $this->mHeaderVariant
= $this->validateVariant( $language );
327 if ( $this->mHeaderVariant
) {
333 return $this->mHeaderVariant
;
337 * Dictionary-based conversion.
338 * This function would not parse the conversion rules.
339 * If you want to parse rules, try to use convert() or
342 * @param string $text The text to be converted
343 * @param bool|string $toVariant The target language code
344 * @return string The converted text
346 public function autoConvert( $text, $toVariant = false ) {
350 $toVariant = $this->getPreferredVariant();
356 if ( $this->guessVariant( $text, $toVariant ) ) {
359 /* we convert everything except:
360 1. HTML markups (anything between < and >)
362 3. placeholders created by the parser
363 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
364 Minimize use of backtracking where possible.
366 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
368 // this one is needed when the text is inside an HTML markup
369 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
371 // Optimize for the common case where these tags have
372 // few or no children. Thus try and possesively get as much as
373 // possible, and only engage in backtracking when we hit a '<'.
375 // disable convert to variants between <code> tags
376 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
377 // disable conversion of <script> tags
378 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
379 // disable conversion of <pre> tags
380 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
381 // The "|.*+)" at the end, is in case we missed some part of html syntax,
382 // we will fail securely (hopefully) by matching the rest of the string.
383 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
385 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
386 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
391 // Guard against delimiter nulls in the input
392 // (should never happen: see T159174)
393 $text = str_replace( "\000", '', $text );
394 $text = str_replace( "\004", '', $text );
396 $markupMatches = null;
397 $elementMatches = null;
399 // We add a marker (\004) at the end of text, to ensure we always match the
400 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
401 while ( $startPos < strlen( $text ) ) {
402 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
403 $elementPos = $markupMatches[0][1];
404 $element = $markupMatches[0][0];
405 if ( $element === "\004" ) {
407 $elementPos = strlen( $text );
409 } elseif ( substr( $element, -1 ) === "\004" ) {
410 // This can sometimes happen if we have
411 // unclosed html tags (For example
412 // when converting a title attribute
413 // during a recursive call that contains
414 // a < e.g. <div title="<">.
415 $element = substr( $element, 0, -1 );
418 // If we hit here, then Language Converter could be tricked
419 // into doing an XSS, so we refuse to translate.
420 // If non-crazy input manages to reach this code path,
421 // we should consider it a bug.
422 $log = LoggerFactory
::getInstance( 'languageconverter' );
423 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
424 . ". Disabling language conversion for this page.",
426 "method" => __METHOD__
,
427 "variant" => $toVariant,
428 "startOfText" => substr( $text, 0, 500 )
433 // Queue the part before the markup for translation in a batch
434 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
436 // Advance to the next position
437 $startPos = $elementPos +
strlen( $element );
439 // Translate any alt or title attributes inside the matched element
441 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
443 // FIXME, this decodes entities, so if you have something
444 // like <div title="foo<bar"> the bar won't get
445 // translated since after entity decoding it looks like
446 // unclosed html and we call this method recursively
448 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
449 // Ensure self-closing tags stay self-closing.
450 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
452 foreach ( [ 'title', 'alt' ] as $attrName ) {
453 if ( !isset( $attrs[$attrName] ) ) {
456 $attr = $attrs[$attrName];
457 // Don't convert URLs
458 if ( !strpos( $attr, '://' ) ) {
459 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
462 if ( $attr !== $attrs[$attrName] ) {
463 $attrs[$attrName] = $attr;
468 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
469 $close . $elementMatches[3];
472 $literalBlob .= $element . "\000";
475 // Do the main translation batch
476 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
478 // Put the output back together
479 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
480 $literalIter = StringUtils
::explode( "\000", $literalBlob );
482 while ( $translatedIter->valid() && $literalIter->valid() ) {
483 $output .= $translatedIter->current();
484 $output .= $literalIter->current();
485 $translatedIter->next();
486 $literalIter->next();
493 * Translate a string to a variant.
494 * Doesn't parse rules or do any of that other stuff, for that use
495 * convert() or convertTo().
497 * @param string $text Text to convert
498 * @param string $variant Variant language code
499 * @return string Translated text
501 public function translate( $text, $variant ) {
502 // If $text is empty or only includes spaces, do nothing
503 // Otherwise translate it
504 if ( trim( $text ) ) {
506 $text = $this->mTables
[$variant]->replace( $text );
512 * Call translate() to convert text to all valid variants.
514 * @param string $text The text to be converted
515 * @return array Variant => converted text
517 public function autoConvertToAllVariants( $text ) {
521 foreach ( $this->mVariants
as $variant ) {
522 $ret[$variant] = $this->translate( $text, $variant );
529 * Apply manual conversion rules.
531 * @param ConverterRule $convRule
533 protected function applyManualConv( $convRule ) {
534 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
536 // T26072: $mConvRuleTitle was overwritten by other manual
537 // rule(s) not for title, this breaks the title conversion.
538 $newConvRuleTitle = $convRule->getTitle();
539 if ( $newConvRuleTitle ) {
540 // So I add an empty check for getTitle()
541 $this->mConvRuleTitle
= $newConvRuleTitle;
544 // merge/remove manual conversion rules to/from global table
545 $convTable = $convRule->getConvTable();
546 $action = $convRule->getRulesAction();
547 foreach ( $convTable as $variant => $pair ) {
548 if ( !$this->validateVariant( $variant ) ) {
552 if ( $action == 'add' ) {
553 // More efficient than array_merge(), about 2.5 times.
554 foreach ( $pair as $from => $to ) {
555 $this->mTables
[$variant]->setPair( $from, $to );
557 } elseif ( $action == 'remove' ) {
558 $this->mTables
[$variant]->removeArray( $pair );
564 * Auto convert a Title object to a readable string in the
567 * @param Title $title A object of Title
568 * @return string Converted title text
570 public function convertTitle( $title ) {
571 $variant = $this->getPreferredVariant();
572 $index = $title->getNamespace();
573 if ( $index !== NS_MAIN
) {
574 $text = $this->convertNamespace( $index, $variant ) . ':';
578 $text .= $this->translate( $title->getText(), $variant );
583 * Get the namespace display name in the preferred variant.
585 * @param int $index Namespace id
586 * @param string|null $variant Variant code or null for preferred variant
587 * @return string Namespace name for display
589 public function convertNamespace( $index, $variant = null ) {
590 if ( $index === NS_MAIN
) {
594 if ( $variant === null ) {
595 $variant = $this->getPreferredVariant();
598 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
599 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
600 $nsVariantText = $cache->get( $key );
601 if ( $nsVariantText !== false ) {
602 return $nsVariantText;
605 // First check if a message gives a converted name in the target variant.
606 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
607 if ( $nsConvMsg->exists() ) {
608 $nsVariantText = $nsConvMsg->plain();
611 // Then check if a message gives a converted name in content language
612 // which needs extra translation to the target variant.
613 if ( $nsVariantText === false ) {
614 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
615 if ( $nsConvMsg->exists() ) {
616 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
620 if ( $nsVariantText === false ) {
621 // No message exists, retrieve it from the target variant's namespace names.
622 $langObj = $this->mLangObj
->factory( $variant );
623 $nsVariantText = $langObj->getFormattedNsText( $index );
626 $cache->set( $key, $nsVariantText, 60 );
628 return $nsVariantText;
632 * Convert text to different variants of a language. The automatic
633 * conversion is done in autoConvert(). Here we parse the text
634 * marked with -{}-, which specifies special conversions of the
635 * text that can not be accomplished in autoConvert().
637 * Syntax of the markup:
638 * -{code1:text1;code2:text2;...}- or
639 * -{flags|code1:text1;code2:text2;...}- or
640 * -{text}- in which case no conversion should take place for text
642 * @param string $text Text to be converted
643 * @return string Converted text
645 public function convert( $text ) {
646 $variant = $this->getPreferredVariant();
647 return $this->convertTo( $text, $variant );
651 * Same as convert() except a extra parameter to custom variant.
653 * @param string $text Text to be converted
654 * @param string $variant The target variant code
655 * @return string Converted text
657 public function convertTo( $text, $variant ) {
658 global $wgDisableLangConversion;
659 if ( $wgDisableLangConversion ) {
662 // Reset converter state for a new converter run.
663 $this->mConvRuleTitle
= false;
664 return $this->recursiveConvertTopLevel( $text, $variant );
668 * Recursively convert text on the outside. Allow to use nested
669 * markups to custom rules.
671 * @param string $text Text to be converted
672 * @param string $variant The target variant code
673 * @param int $depth Depth of recursion
674 * @return string Converted text
676 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
679 $length = strlen( $text );
680 $shouldConvert = !$this->guessVariant( $text, $variant );
683 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
684 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
685 // phpcs:ignore Generic.Files.LineLength
686 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
687 while ( $startPos < $length && $continue ) {
688 $continue = preg_match(
689 // Only match -{ outside of html.
690 "/$noScript|$noStyle|$noHtml|-\{/",
698 // No more markup, append final segment
699 $fragment = substr( $text, $startPos );
700 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
704 // Offset of the match of the regex pattern.
707 // Append initial segment
708 $fragment = substr( $text, $startPos, $pos - $startPos );
709 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
710 // -{ marker found, not in attribute
711 // Advance position up to -{ marker.
713 // Do recursive conversion
714 // Note: This passes $startPos by reference, and advances it.
715 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
721 * Recursively convert text on the inside.
723 * @param string $text Text to be converted
724 * @param string $variant The target variant code
725 * @param int &$startPos
726 * @param int $depth Depth of recursion
728 * @throws MWException
729 * @return string Converted text
731 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
732 // Quick sanity check (no function calls)
733 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
734 throw new MWException( __METHOD__
. ': invalid input string' );
739 $warningDone = false;
740 $length = strlen( $text );
742 while ( $startPos < $length ) {
744 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
754 // Append initial segment
755 $inner .= substr( $text, $startPos, $pos - $startPos );
763 if ( $depth >= $this->mMaxDepth
) {
765 if ( !$warningDone ) {
766 $inner .= '<span class="error">' .
767 wfMessage( 'language-converter-depth-warning' )
768 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
775 // Recursively parse another rule
776 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
781 $rule = new ConverterRule( $inner, $this );
782 $rule->parse( $variant );
783 $this->applyManualConv( $rule );
784 return $rule->getDisplay();
786 throw new MWException( __METHOD__
. ': invalid regex match' );
791 if ( $startPos < $length ) {
792 $inner .= substr( $text, $startPos );
795 return '-{' . $this->autoConvert( $inner, $variant );
799 * If a language supports multiple variants, it is possible that
800 * non-existing link in one variant actually exists in another variant.
801 * This function tries to find it. See e.g. LanguageZh.php
802 * The input parameters may be modified upon return
804 * @param string &$link The name of the link
805 * @param Title &$nt The title object of the link
806 * @param bool $ignoreOtherCond To disable other conditions when
807 * we need to transclude a template or update a category's link
809 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
810 # If the article has already existed, there is no need to
811 # check it again, otherwise it may cause a fault.
812 if ( is_object( $nt ) && $nt->exists() ) {
816 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
817 $isredir = $wgRequest->getText( 'redirect', 'yes' );
818 $action = $wgRequest->getText( 'action' );
819 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
822 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
823 $disableLinkConversion = $wgDisableLangConversion
824 ||
$wgDisableTitleConversion;
825 $linkBatch = new LinkBatch();
829 if ( $disableLinkConversion ||
830 ( !$ignoreOtherCond &&
833 ||
$action == 'submit'
834 ||
$linkconvert == 'no' ) ) ) {
838 if ( is_object( $nt ) ) {
839 $ns = $nt->getNamespace();
842 $variants = $this->autoConvertToAllVariants( $link );
843 if ( !$variants ) { // give up
849 foreach ( $variants as $v ) {
851 $varnt = Title
::newFromText( $v, $ns );
852 if ( !is_null( $varnt ) ) {
853 $linkBatch->addObj( $varnt );
859 // fetch all variants in single query
860 $linkBatch->execute();
862 foreach ( $titles as $varnt ) {
863 if ( $varnt->getArticleID() > 0 ) {
865 $link = $varnt->getText();
872 * Returns language specific hash options.
876 public function getExtraHashOptions() {
877 $variant = $this->getPreferredVariant();
879 return '!' . $variant;
883 * Guess if a text is written in a variant. This should be implemented in subclasses.
885 * @param string $text The text to be checked
886 * @param string $variant Language code of the variant to be checked for
887 * @return bool True if $text appears to be written in $variant, false if not
889 * @author Nikola Smolenski <smolensk@eunet.rs>
892 public function guessVariant( $text, $variant ) {
897 * Load default conversion tables.
898 * This method must be implemented in derived class.
901 * @throws MWException
903 function loadDefaultTables() {
904 $class = static::class;
905 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
909 * Load conversion tables either from the cache or the disk.
911 * @param bool $fromCache Load from memcached? Defaults to true.
913 function loadTables( $fromCache = true ) {
914 global $wgLanguageConverterCacheType;
916 if ( $this->mTablesLoaded
) {
920 $this->mTablesLoaded
= true;
921 $this->mTables
= false;
922 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
923 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
925 $this->mTables
= $cache->get( $cacheKey );
927 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
928 // not in cache, or we need a fresh reload.
929 // We will first load the default tables
930 // then update them using things in MediaWiki:Conversiontable/*
931 $this->loadDefaultTables();
932 foreach ( $this->mVariants
as $var ) {
933 $cached = $this->parseCachedTable( $var );
934 $this->mTables
[$var]->mergeArray( $cached );
937 $this->postLoadTables();
938 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
940 $cache->set( $cacheKey, $this->mTables
, 43200 );
945 * Hook for post processing after conversion tables are loaded.
947 function postLoadTables() {
951 * Reload the conversion tables.
953 * Also used by test suites which need to reset the converter state.
957 private function reloadTables() {
958 if ( $this->mTables
) {
959 unset( $this->mTables
);
962 $this->mTablesLoaded
= false;
963 $this->loadTables( false );
967 * Parse the conversion table stored in the cache.
969 * The tables should be in blocks of the following form:
976 * To make the tables more manageable, subpages are allowed
977 * and will be parsed recursively if $recursive == true.
979 * @param string $code Language code
980 * @param string $subpage Subpage name
981 * @param bool $recursive Parse subpages recursively? Defaults to true.
985 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
988 $key = 'Conversiontable/' . $code;
990 $key .= '/' . $subpage;
992 if ( array_key_exists( $key, $parsed ) ) {
996 $parsed[$key] = true;
998 if ( $subpage === '' ) {
999 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1002 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1003 if ( $title && $title->exists() ) {
1004 $revision = Revision
::newFromTitle( $title );
1006 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1007 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
1010 // @todo in the future, use a specialized content model, perhaps based on json!
1015 # Nothing to parse if there's no text
1016 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1020 // get all subpage links of the form
1021 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1022 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1024 $subs = StringUtils
::explode( '[[', $txt );
1026 foreach ( $subs as $sub ) {
1027 $link = explode( ']]', $sub, 2 );
1028 if ( count( $link ) != 2 ) {
1031 $b = explode( '|', $link[0], 2 );
1032 $b = explode( '/', trim( $b[0] ), 3 );
1033 if ( count( $b ) == 3 ) {
1039 if ( $b[0] == $linkhead && $b[1] == $code ) {
1040 $sublinks[] = $sublink;
1044 // parse the mappings in this page
1045 $blocks = StringUtils
::explode( '-{', $txt );
1048 foreach ( $blocks as $block ) {
1050 // Skip the part before the first -{
1054 $mappings = explode( '}-', $block, 2 )[0];
1055 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1056 $table = StringUtils
::explode( ';', $stripped );
1057 foreach ( $table as $t ) {
1058 $m = explode( '=>', $t, 3 );
1059 if ( count( $m ) != 2 ) {
1062 // trim any trailling comments starting with '//'
1063 $tt = explode( '//', $m[1], 2 );
1064 $ret[trim( $m[0] )] = trim( $tt[0] );
1068 // recursively parse the subpages
1070 foreach ( $sublinks as $link ) {
1071 $s = $this->parseCachedTable( $code, $link, $recursive );
1076 if ( $this->mUcfirst
) {
1077 foreach ( $ret as $k => $v ) {
1078 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1085 * Enclose a string with the "no conversion" tag. This is used by
1086 * various functions in the Parser.
1088 * @param string $text Text to be tagged for no conversion
1089 * @param bool $noParse Unused
1090 * @return string The tagged text
1092 public function markNoConversion( $text, $noParse = false ) {
1093 # don't mark if already marked
1094 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1098 $ret = "-{R|$text}-";
1103 * Convert the sorting key for category links. This should make different
1104 * keys that are variants of each other map to the same key.
1106 * @param string $key
1110 function convertCategoryKey( $key ) {
1115 * Refresh the cache of conversion tables when
1116 * MediaWiki:Conversiontable* is updated.
1118 * @param Title $titleobj The Title of the page being updated
1120 public function updateConversionTable( Title
$titleobj ) {
1121 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1122 $title = $titleobj->getDBkey();
1123 $t = explode( '/', $title, 3 );
1125 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1126 if ( $this->validateVariant( $t[1] ) ) {
1127 $this->reloadTables();
1134 * Get the cached separator pattern for ConverterRule::parseRules()
1137 function getVarSeparatorPattern() {
1138 if ( is_null( $this->mVarSeparatorPattern
) ) {
1139 // varsep_pattern for preg_split:
1140 // text should be splited by ";" only if a valid variant
1141 // name exist after the markup, for example:
1142 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1143 // <span style="font-size:120%;">yyy</span>;}-
1144 // we should split it as:
1146 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1147 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1151 foreach ( $this->mVariants
as $variant ) {
1152 // zh-hans:xxx;zh-hant:yyy
1153 $pat .= $variant . '\s*:|';
1154 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1155 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1158 $this->mVarSeparatorPattern
= $pat;
1160 return $this->mVarSeparatorPattern
;