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( Language
$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() {
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() ) {
270 $this->mMainLanguageCode
==
271 MediaWikiServices
::getInstance()->getContentLanguage()->getCode()
273 $ret = $wgUser->getOption( 'variant' );
275 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
278 // figure out user lang without constructing wgLang to avoid
279 // infinite recursion
280 $ret = $wgUser->getOption( 'language' );
283 $this->mUserVariant
= $this->validateVariant( $ret );
284 return $this->mUserVariant
;
288 * Determine the language variant from the Accept-Language header.
290 * @return mixed Variant if one found, null otherwise
292 protected function getHeaderVariant() {
295 if ( $this->mHeaderVariant
) {
296 return $this->mHeaderVariant
;
299 // see if some supported language variant is set in the
301 $languages = array_keys( $wgRequest->getAcceptLang() );
302 if ( empty( $languages ) ) {
306 $fallbackLanguages = [];
307 foreach ( $languages as $language ) {
308 $this->mHeaderVariant
= $this->validateVariant( $language );
309 if ( $this->mHeaderVariant
) {
313 // To see if there are fallbacks of current language.
314 // We record these fallback variants, and process
316 $fallbacks = $this->getVariantFallbacks( $language );
317 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
318 $fallbackLanguages[] = $fallbacks;
319 } elseif ( is_array( $fallbacks ) ) {
321 array_merge( $fallbackLanguages, $fallbacks );
325 if ( !$this->mHeaderVariant
) {
326 // process fallback languages now
327 $fallback_languages = array_unique( $fallbackLanguages );
328 foreach ( $fallback_languages as $language ) {
329 $this->mHeaderVariant
= $this->validateVariant( $language );
330 if ( $this->mHeaderVariant
) {
336 return $this->mHeaderVariant
;
340 * Dictionary-based conversion.
341 * This function would not parse the conversion rules.
342 * If you want to parse rules, try to use convert() or
345 * @param string $text The text to be converted
346 * @param bool|string $toVariant The target language code
347 * @return string The converted text
349 public function autoConvert( $text, $toVariant = false ) {
353 $toVariant = $this->getPreferredVariant();
359 if ( $this->guessVariant( $text, $toVariant ) ) {
362 /* we convert everything except:
363 1. HTML markups (anything between < and >)
365 3. placeholders created by the parser
366 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
367 Minimize use of backtracking where possible.
369 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
371 // this one is needed when the text is inside an HTML markup
372 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
374 // Optimize for the common case where these tags have
375 // few or no children. Thus try and possesively get as much as
376 // possible, and only engage in backtracking when we hit a '<'.
378 // disable convert to variants between <code> tags
379 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
380 // disable conversion of <script> tags
381 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
382 // disable conversion of <pre> tags
383 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
384 // The "|.*+)" at the end, is in case we missed some part of html syntax,
385 // we will fail securely (hopefully) by matching the rest of the string.
386 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
388 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
389 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
394 // Guard against delimiter nulls in the input
395 // (should never happen: see T159174)
396 $text = str_replace( "\000", '', $text );
397 $text = str_replace( "\004", '', $text );
399 $markupMatches = null;
400 $elementMatches = null;
402 // We add a marker (\004) at the end of text, to ensure we always match the
403 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
404 while ( $startPos < strlen( $text ) ) {
405 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
406 $elementPos = $markupMatches[0][1];
407 $element = $markupMatches[0][0];
408 if ( $element === "\004" ) {
410 $elementPos = strlen( $text );
412 } elseif ( substr( $element, -1 ) === "\004" ) {
413 // This can sometimes happen if we have
414 // unclosed html tags (For example
415 // when converting a title attribute
416 // during a recursive call that contains
417 // a < e.g. <div title="<">.
418 $element = substr( $element, 0, -1 );
421 // If we hit here, then Language Converter could be tricked
422 // into doing an XSS, so we refuse to translate.
423 // If non-crazy input manages to reach this code path,
424 // we should consider it a bug.
425 $log = LoggerFactory
::getInstance( 'languageconverter' );
426 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
427 . ". Disabling language conversion for this page.",
429 "method" => __METHOD__
,
430 "variant" => $toVariant,
431 "startOfText" => substr( $text, 0, 500 )
436 // Queue the part before the markup for translation in a batch
437 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
439 // Advance to the next position
440 $startPos = $elementPos +
strlen( $element );
442 // Translate any alt or title attributes inside the matched element
444 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
446 // FIXME, this decodes entities, so if you have something
447 // like <div title="foo<bar"> the bar won't get
448 // translated since after entity decoding it looks like
449 // unclosed html and we call this method recursively
451 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
452 // Ensure self-closing tags stay self-closing.
453 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
455 foreach ( [ 'title', 'alt' ] as $attrName ) {
456 if ( !isset( $attrs[$attrName] ) ) {
459 $attr = $attrs[$attrName];
460 // Don't convert URLs
461 if ( !strpos( $attr, '://' ) ) {
462 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
465 if ( $attr !== $attrs[$attrName] ) {
466 $attrs[$attrName] = $attr;
471 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
472 $close . $elementMatches[3];
475 $literalBlob .= $element . "\000";
478 // Do the main translation batch
479 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
481 // Put the output back together
482 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
483 $literalIter = StringUtils
::explode( "\000", $literalBlob );
485 while ( $translatedIter->valid() && $literalIter->valid() ) {
486 $output .= $translatedIter->current();
487 $output .= $literalIter->current();
488 $translatedIter->next();
489 $literalIter->next();
496 * Translate a string to a variant.
497 * Doesn't parse rules or do any of that other stuff, for that use
498 * convert() or convertTo().
500 * @param string $text Text to convert
501 * @param string $variant Variant language code
502 * @return string Translated text
504 public function translate( $text, $variant ) {
505 // If $text is empty or only includes spaces, do nothing
506 // Otherwise translate it
507 if ( trim( $text ) ) {
509 $text = $this->mTables
[$variant]->replace( $text );
515 * Call translate() to convert text to all valid variants.
517 * @param string $text The text to be converted
518 * @return array Variant => converted text
520 public function autoConvertToAllVariants( $text ) {
524 foreach ( $this->mVariants
as $variant ) {
525 $ret[$variant] = $this->translate( $text, $variant );
532 * Apply manual conversion rules.
534 * @param ConverterRule $convRule
536 protected function applyManualConv( $convRule ) {
537 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
539 // T26072: $mConvRuleTitle was overwritten by other manual
540 // rule(s) not for title, this breaks the title conversion.
541 $newConvRuleTitle = $convRule->getTitle();
542 if ( $newConvRuleTitle ) {
543 // So I add an empty check for getTitle()
544 $this->mConvRuleTitle
= $newConvRuleTitle;
547 // merge/remove manual conversion rules to/from global table
548 $convTable = $convRule->getConvTable();
549 $action = $convRule->getRulesAction();
550 foreach ( $convTable as $variant => $pair ) {
551 if ( !$this->validateVariant( $variant ) ) {
555 if ( $action == 'add' ) {
556 // More efficient than array_merge(), about 2.5 times.
557 foreach ( $pair as $from => $to ) {
558 $this->mTables
[$variant]->setPair( $from, $to );
560 } elseif ( $action == 'remove' ) {
561 $this->mTables
[$variant]->removeArray( $pair );
567 * Auto convert a Title object to a readable string in the
570 * @param Title $title A object of Title
571 * @return string Converted title text
573 public function convertTitle( $title ) {
574 $variant = $this->getPreferredVariant();
575 $index = $title->getNamespace();
576 if ( $index !== NS_MAIN
) {
577 $text = $this->convertNamespace( $index, $variant ) . ':';
581 $text .= $this->translate( $title->getText(), $variant );
586 * Get the namespace display name in the preferred variant.
588 * @param int $index Namespace id
589 * @param string|null $variant Variant code or null for preferred variant
590 * @return string Namespace name for display
592 public function convertNamespace( $index, $variant = null ) {
593 if ( $index === NS_MAIN
) {
597 if ( $variant === null ) {
598 $variant = $this->getPreferredVariant();
601 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
602 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
603 $nsVariantText = $cache->get( $key );
604 if ( $nsVariantText !== false ) {
605 return $nsVariantText;
608 // First check if a message gives a converted name in the target variant.
609 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
610 if ( $nsConvMsg->exists() ) {
611 $nsVariantText = $nsConvMsg->plain();
614 // Then check if a message gives a converted name in content language
615 // which needs extra translation to the target variant.
616 if ( $nsVariantText === false ) {
617 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
618 if ( $nsConvMsg->exists() ) {
619 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
623 if ( $nsVariantText === false ) {
624 // No message exists, retrieve it from the target variant's namespace names.
625 $langObj = $this->mLangObj
->factory( $variant );
626 $nsVariantText = $langObj->getFormattedNsText( $index );
629 $cache->set( $key, $nsVariantText, 60 );
631 return $nsVariantText;
635 * Convert text to different variants of a language. The automatic
636 * conversion is done in autoConvert(). Here we parse the text
637 * marked with -{}-, which specifies special conversions of the
638 * text that can not be accomplished in autoConvert().
640 * Syntax of the markup:
641 * -{code1:text1;code2:text2;...}- or
642 * -{flags|code1:text1;code2:text2;...}- or
643 * -{text}- in which case no conversion should take place for text
645 * @param string $text Text to be converted
646 * @return string Converted text
648 public function convert( $text ) {
649 $variant = $this->getPreferredVariant();
650 return $this->convertTo( $text, $variant );
654 * Same as convert() except a extra parameter to custom variant.
656 * @param string $text Text to be converted
657 * @param string $variant The target variant code
658 * @return string Converted text
660 public function convertTo( $text, $variant ) {
661 global $wgDisableLangConversion;
662 if ( $wgDisableLangConversion ) {
665 // Reset converter state for a new converter run.
666 $this->mConvRuleTitle
= false;
667 return $this->recursiveConvertTopLevel( $text, $variant );
671 * Recursively convert text on the outside. Allow to use nested
672 * markups to custom rules.
674 * @param string $text Text to be converted
675 * @param string $variant The target variant code
676 * @param int $depth Depth of recursion
677 * @return string Converted text
679 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
682 $length = strlen( $text );
683 $shouldConvert = !$this->guessVariant( $text, $variant );
686 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
687 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
688 // phpcs:ignore Generic.Files.LineLength
689 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
690 while ( $startPos < $length && $continue ) {
691 $continue = preg_match(
692 // Only match -{ outside of html.
693 "/$noScript|$noStyle|$noHtml|-\{/",
701 // No more markup, append final segment
702 $fragment = substr( $text, $startPos );
703 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
707 // Offset of the match of the regex pattern.
710 // Append initial segment
711 $fragment = substr( $text, $startPos, $pos - $startPos );
712 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
713 // -{ marker found, not in attribute
714 // Advance position up to -{ marker.
716 // Do recursive conversion
717 // Note: This passes $startPos by reference, and advances it.
718 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
724 * Recursively convert text on the inside.
726 * @param string $text Text to be converted
727 * @param string $variant The target variant code
728 * @param int &$startPos
729 * @param int $depth Depth of recursion
731 * @throws MWException
732 * @return string Converted text
734 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
735 // Quick sanity check (no function calls)
736 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
737 throw new MWException( __METHOD__
. ': invalid input string' );
742 $warningDone = false;
743 $length = strlen( $text );
745 while ( $startPos < $length ) {
747 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
757 // Append initial segment
758 $inner .= substr( $text, $startPos, $pos - $startPos );
766 if ( $depth >= $this->mMaxDepth
) {
768 if ( !$warningDone ) {
769 $inner .= '<span class="error">' .
770 wfMessage( 'language-converter-depth-warning' )
771 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
778 // Recursively parse another rule
779 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
784 $rule = new ConverterRule( $inner, $this );
785 $rule->parse( $variant );
786 $this->applyManualConv( $rule );
787 return $rule->getDisplay();
789 throw new MWException( __METHOD__
. ': invalid regex match' );
794 if ( $startPos < $length ) {
795 $inner .= substr( $text, $startPos );
798 return '-{' . $this->autoConvert( $inner, $variant );
802 * If a language supports multiple variants, it is possible that
803 * non-existing link in one variant actually exists in another variant.
804 * This function tries to find it. See e.g. LanguageZh.php
805 * The input parameters may be modified upon return
807 * @param string &$link The name of the link
808 * @param Title &$nt The title object of the link
809 * @param bool $ignoreOtherCond To disable other conditions when
810 * we need to transclude a template or update a category's link
812 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
813 # If the article has already existed, there is no need to
814 # check it again, otherwise it may cause a fault.
815 if ( is_object( $nt ) && $nt->exists() ) {
819 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
820 $isredir = $wgRequest->getText( 'redirect', 'yes' );
821 $action = $wgRequest->getText( 'action' );
822 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
825 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
826 $disableLinkConversion = $wgDisableLangConversion
827 ||
$wgDisableTitleConversion;
828 $linkBatch = new LinkBatch();
832 if ( $disableLinkConversion ||
833 ( !$ignoreOtherCond &&
836 ||
$action == 'submit'
837 ||
$linkconvert == 'no' ) ) ) {
841 if ( is_object( $nt ) ) {
842 $ns = $nt->getNamespace();
845 $variants = $this->autoConvertToAllVariants( $link );
846 if ( !$variants ) { // give up
852 foreach ( $variants as $v ) {
854 $varnt = Title
::newFromText( $v, $ns );
855 if ( !is_null( $varnt ) ) {
856 $linkBatch->addObj( $varnt );
862 // fetch all variants in single query
863 $linkBatch->execute();
865 foreach ( $titles as $varnt ) {
866 if ( $varnt->getArticleID() > 0 ) {
868 $link = $varnt->getText();
875 * Returns language specific hash options.
879 public function getExtraHashOptions() {
880 $variant = $this->getPreferredVariant();
882 return '!' . $variant;
886 * Guess if a text is written in a variant. This should be implemented in subclasses.
888 * @param string $text The text to be checked
889 * @param string $variant Language code of the variant to be checked for
890 * @return bool True if $text appears to be written in $variant, false if not
892 * @author Nikola Smolenski <smolensk@eunet.rs>
895 public function guessVariant( $text, $variant ) {
900 * Load default conversion tables.
901 * This method must be implemented in derived class.
904 * @throws MWException
906 function loadDefaultTables() {
907 $class = static::class;
908 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
912 * Load conversion tables either from the cache or the disk.
914 * @param bool $fromCache Load from memcached? Defaults to true.
916 function loadTables( $fromCache = true ) {
917 global $wgLanguageConverterCacheType;
919 if ( $this->mTablesLoaded
) {
923 $this->mTablesLoaded
= true;
924 $this->mTables
= false;
925 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
926 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
928 $this->mTables
= $cache->get( $cacheKey );
930 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
931 // not in cache, or we need a fresh reload.
932 // We will first load the default tables
933 // then update them using things in MediaWiki:Conversiontable/*
934 $this->loadDefaultTables();
935 foreach ( $this->mVariants
as $var ) {
936 $cached = $this->parseCachedTable( $var );
937 $this->mTables
[$var]->mergeArray( $cached );
940 $this->postLoadTables();
941 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
943 $cache->set( $cacheKey, $this->mTables
, 43200 );
948 * Hook for post processing after conversion tables are loaded.
950 function postLoadTables() {
954 * Reload the conversion tables.
956 * Also used by test suites which need to reset the converter state.
960 private function reloadTables() {
961 if ( $this->mTables
) {
962 unset( $this->mTables
);
965 $this->mTablesLoaded
= false;
966 $this->loadTables( false );
970 * Parse the conversion table stored in the cache.
972 * The tables should be in blocks of the following form:
979 * To make the tables more manageable, subpages are allowed
980 * and will be parsed recursively if $recursive == true.
982 * @param string $code Language code
983 * @param string $subpage Subpage name
984 * @param bool $recursive Parse subpages recursively? Defaults to true.
988 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
991 $key = 'Conversiontable/' . $code;
993 $key .= '/' . $subpage;
995 if ( array_key_exists( $key, $parsed ) ) {
999 $parsed[$key] = true;
1001 if ( $subpage === '' ) {
1002 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1005 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1006 if ( $title && $title->exists() ) {
1007 $revision = Revision
::newFromTitle( $title );
1009 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1010 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
1013 // @todo in the future, use a specialized content model, perhaps based on json!
1018 # Nothing to parse if there's no text
1019 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1023 // get all subpage links of the form
1024 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1025 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1027 $subs = StringUtils
::explode( '[[', $txt );
1029 foreach ( $subs as $sub ) {
1030 $link = explode( ']]', $sub, 2 );
1031 if ( count( $link ) != 2 ) {
1034 $b = explode( '|', $link[0], 2 );
1035 $b = explode( '/', trim( $b[0] ), 3 );
1036 if ( count( $b ) == 3 ) {
1042 if ( $b[0] == $linkhead && $b[1] == $code ) {
1043 $sublinks[] = $sublink;
1047 // parse the mappings in this page
1048 $blocks = StringUtils
::explode( '-{', $txt );
1051 foreach ( $blocks as $block ) {
1053 // Skip the part before the first -{
1057 $mappings = explode( '}-', $block, 2 )[0];
1058 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1059 $table = StringUtils
::explode( ';', $stripped );
1060 foreach ( $table as $t ) {
1061 $m = explode( '=>', $t, 3 );
1062 if ( count( $m ) != 2 ) {
1065 // trim any trailling comments starting with '//'
1066 $tt = explode( '//', $m[1], 2 );
1067 $ret[trim( $m[0] )] = trim( $tt[0] );
1071 // recursively parse the subpages
1073 foreach ( $sublinks as $link ) {
1074 $s = $this->parseCachedTable( $code, $link, $recursive );
1079 if ( $this->mUcfirst
) {
1080 foreach ( $ret as $k => $v ) {
1081 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1088 * Enclose a string with the "no conversion" tag. This is used by
1089 * various functions in the Parser.
1091 * @param string $text Text to be tagged for no conversion
1092 * @param bool $noParse Unused
1093 * @return string The tagged text
1095 public function markNoConversion( $text, $noParse = false ) {
1096 # don't mark if already marked
1097 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1101 $ret = "-{R|$text}-";
1106 * Convert the sorting key for category links. This should make different
1107 * keys that are variants of each other map to the same key.
1109 * @param string $key
1113 function convertCategoryKey( $key ) {
1118 * Refresh the cache of conversion tables when
1119 * MediaWiki:Conversiontable* is updated.
1121 * @param Title $titleobj The Title of the page being updated
1123 public function updateConversionTable( Title
$titleobj ) {
1124 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1125 $title = $titleobj->getDBkey();
1126 $t = explode( '/', $title, 3 );
1128 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1129 if ( $this->validateVariant( $t[1] ) ) {
1130 $this->reloadTables();
1137 * Get the cached separator pattern for ConverterRule::parseRules()
1140 function getVarSeparatorPattern() {
1141 if ( is_null( $this->mVarSeparatorPattern
) ) {
1142 // varsep_pattern for preg_split:
1143 // text should be splited by ";" only if a valid variant
1144 // name exist after the markup, for example:
1145 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1146 // <span style="font-size:120%;">yyy</span>;}-
1147 // we should split it as:
1149 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1150 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1154 foreach ( $this->mVariants
as $variant ) {
1155 // zh-hans:xxx;zh-hant:yyy
1156 $pat .= $variant . '\s*:|';
1157 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1158 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1161 $this->mVarSeparatorPattern
= $pat;
1163 return $this->mVarSeparatorPattern
;