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 = [
53 public $mMainLanguageCode;
59 public $mVariantFallbacks;
60 public $mVariantNames;
61 public $mTablesLoaded = false;
63 // 'bidirectional' 'unidirectional' 'disable' for each variant
68 public $mDescCodeSep = ':', $mDescVarSep = ';';
69 public $mUcfirst = false;
70 public $mConvRuleTitle = false;
73 public $mHeaderVariant;
74 public $mMaxDepth = 10;
75 public $mVarSeparatorPattern;
77 const CACHE_VERSION_KEY
= 'VERSION 7';
80 * @param Language $langobj
81 * @param string $maincode The main language code of this language
82 * @param string[] $variants The supported variants of this language
83 * @param array $variantfallbacks The fallback language of each variant
84 * @param array $flags Defining the custom strings that maps to the flags
85 * @param array $manualLevel Limit for supported variants
87 public function __construct( $langobj, $maincode, $variants = [],
88 $variantfallbacks = [], $flags = [],
90 global $wgDisabledVariants;
91 $this->mLangObj
= $langobj;
92 $this->mMainLanguageCode
= $maincode;
93 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
94 $this->mVariantFallbacks
= $variantfallbacks;
95 $this->mVariantNames
= Language
::fetchLanguageNames();
97 // 'S' show converted text
98 // '+' add rules for alltext
99 // 'E' the gave flags is error
100 // these flags above are reserved for program
101 'A' => 'A', // add rule for convert code (all text convert)
102 'T' => 'T', // title convert
103 'R' => 'R', // raw content
104 'D' => 'D', // convert description (subclass implement)
105 '-' => '-', // remove convert (not implement)
106 'H' => 'H', // add rule for convert code (but no display in placed code)
107 'N' => 'N', // current variant name
109 $this->mFlags
= array_merge( $defaultflags, $flags );
110 foreach ( $this->mVariants
as $v ) {
111 if ( array_key_exists( $v, $manualLevel ) ) {
112 $this->mManualLevel
[$v] = $manualLevel[$v];
114 $this->mManualLevel
[$v] = 'bidirectional';
116 $this->mFlags
[$v] = $v;
121 * Get all valid variants.
122 * Call this instead of using $this->mVariants directly.
124 * @return string[] Contains all valid variants
126 public function getVariants() {
127 return $this->mVariants
;
131 * In case some variant is not defined in the markup, we need
132 * to have some fallback. For example, in zh, normally people
133 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
134 * when zh-sg is preferred but not defined, we will pick zh-hans
135 * in this case. Right now this is only used by zh.
137 * @param string $variant The language code of the variant
138 * @return string|array The code of the fallback language or the
139 * main code if there is no fallback
141 public function getVariantFallbacks( $variant ) {
142 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
143 return $this->mVariantFallbacks
[$variant];
145 return $this->mMainLanguageCode
;
149 * Get the title produced by the conversion rule.
150 * @return string The converted title text
152 public function getConvRuleTitle() {
153 return $this->mConvRuleTitle
;
157 * Get preferred language variant.
158 * @return string The preferred language code
160 public function getPreferredVariant() {
161 global $wgDefaultLanguageVariant, $wgUser;
163 $req = $this->getURLVariant();
165 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
166 $req = $this->getUserVariant();
168 $req = $this->getHeaderVariant();
171 if ( $wgDefaultLanguageVariant && !$req ) {
172 $req = $this->validateVariant( $wgDefaultLanguageVariant );
175 // This function, unlike the other get*Variant functions, is
176 // not memoized (i.e. there return value is not cached) since
177 // new information might appear during processing after this
179 if ( $this->validateVariant( $req ) ) {
182 return $this->mMainLanguageCode
;
186 * Get default variant.
187 * This function would not be affected by user's settings
188 * @return string The default variant code
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
193 $req = $this->getURLVariant();
196 $req = $this->getHeaderVariant();
199 if ( $wgDefaultLanguageVariant && !$req ) {
200 $req = $this->validateVariant( $wgDefaultLanguageVariant );
206 return $this->mMainLanguageCode
;
210 * Validate the variant
211 * @param string $variant The variant to validate
212 * @return mixed Returns the variant if it is valid, null otherwise
214 public function validateVariant( $variant = null ) {
215 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
222 * Get the variant specified in the URL
224 * @return mixed Variant if one found, false otherwise.
226 public function getURLVariant() {
229 if ( $this->mURLVariant
) {
230 return $this->mURLVariant
;
233 // see if the preference is set in the request
234 $ret = $wgRequest->getText( 'variant' );
237 $ret = $wgRequest->getVal( 'uselang' );
240 $this->mURLVariant
= $this->validateVariant( $ret );
241 return $this->mURLVariant
;
245 * Determine if the user has a variant set.
247 * @return mixed Variant if one found, false otherwise.
249 protected function getUserVariant() {
250 global $wgUser, $wgContLang;
252 // memoizing this function wreaks havoc on parserTest.php
254 if ( $this->mUserVariant ) {
255 return $this->mUserVariant;
259 // Get language variant preference from logged in users
260 // Don't call this on stub objects because that causes infinite
261 // recursion during initialisation
262 if ( !$wgUser->isSafeToLoad() ) {
265 if ( $wgUser->isLoggedIn() ) {
266 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
267 $ret = $wgUser->getOption( 'variant' );
269 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
272 // figure out user lang without constructing wgLang to avoid
273 // infinite recursion
274 $ret = $wgUser->getOption( 'language' );
277 $this->mUserVariant
= $this->validateVariant( $ret );
278 return $this->mUserVariant
;
282 * Determine the language variant from the Accept-Language header.
284 * @return mixed Variant if one found, false otherwise.
286 protected function getHeaderVariant() {
289 if ( $this->mHeaderVariant
) {
290 return $this->mHeaderVariant
;
293 // see if some supported language variant is set in the
295 $languages = array_keys( $wgRequest->getAcceptLang() );
296 if ( empty( $languages ) ) {
300 $fallbackLanguages = [];
301 foreach ( $languages as $language ) {
302 $this->mHeaderVariant
= $this->validateVariant( $language );
303 if ( $this->mHeaderVariant
) {
307 // To see if there are fallbacks of current language.
308 // We record these fallback variants, and process
310 $fallbacks = $this->getVariantFallbacks( $language );
311 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
312 $fallbackLanguages[] = $fallbacks;
313 } elseif ( is_array( $fallbacks ) ) {
315 array_merge( $fallbackLanguages, $fallbacks );
319 if ( !$this->mHeaderVariant
) {
320 // process fallback languages now
321 $fallback_languages = array_unique( $fallbackLanguages );
322 foreach ( $fallback_languages as $language ) {
323 $this->mHeaderVariant
= $this->validateVariant( $language );
324 if ( $this->mHeaderVariant
) {
330 return $this->mHeaderVariant
;
334 * Dictionary-based conversion.
335 * This function would not parse the conversion rules.
336 * If you want to parse rules, try to use convert() or
339 * @param string $text The text to be converted
340 * @param bool|string $toVariant The target language code
341 * @return string The converted text
343 public function autoConvert( $text, $toVariant = false ) {
347 $toVariant = $this->getPreferredVariant();
353 if ( $this->guessVariant( $text, $toVariant ) ) {
356 /* we convert everything except:
357 1. HTML markups (anything between < and >)
359 3. placeholders created by the parser
360 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
361 Minimize use of backtracking where possible.
363 $marker = '|' . Parser
::MARKER_PREFIX
. '[^\x7f]++\x7f';
365 // this one is needed when the text is inside an HTML markup
366 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
368 // Optimize for the common case where these tags have
369 // few or no children. Thus try and possesively get as much as
370 // possible, and only engage in backtracking when we hit a '<'.
372 // disable convert to variants between <code> tags
373 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
374 // disable conversion of <script> tags
375 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
376 // disable conversion of <pre> tags
377 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
378 // The "|.*+)" at the end, is in case we missed some part of html syntax,
379 // we will fail securely (hopefully) by matching the rest of the string.
380 $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
382 $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
383 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
388 // Guard against delimiter nulls in the input
389 // (should never happen: see T159174)
390 $text = str_replace( "\000", '', $text );
391 $text = str_replace( "\004", '', $text );
393 $markupMatches = null;
394 $elementMatches = null;
396 // We add a marker (\004) at the end of text, to ensure we always match the
397 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
398 while ( $startPos < strlen( $text ) ) {
399 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
400 $elementPos = $markupMatches[0][1];
401 $element = $markupMatches[0][0];
402 if ( $element === "\004" ) {
404 $elementPos = strlen( $text );
406 } elseif ( substr( $element, -1 ) === "\004" ) {
407 // This can sometimes happen if we have
408 // unclosed html tags (For example
409 // when converting a title attribute
410 // during a recursive call that contains
411 // a < e.g. <div title="<">.
412 $element = substr( $element, 0, -1 );
415 // If we hit here, then Language Converter could be tricked
416 // into doing an XSS, so we refuse to translate.
417 // If non-crazy input manages to reach this code path,
418 // we should consider it a bug.
419 $log = LoggerFactory
::getInstance( 'languageconverter' );
420 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
421 . ". Disabling language conversion for this page.",
423 "method" => __METHOD__
,
424 "variant" => $toVariant,
425 "startOfText" => substr( $text, 0, 500 )
430 // Queue the part before the markup for translation in a batch
431 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
433 // Advance to the next position
434 $startPos = $elementPos +
strlen( $element );
436 // Translate any alt or title attributes inside the matched element
438 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
440 // FIXME, this decodes entities, so if you have something
441 // like <div title="foo<bar"> the bar won't get
442 // translated since after entity decoding it looks like
443 // unclosed html and we call this method recursively
445 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
446 // Ensure self-closing tags stay self-closing.
447 $close = substr( $elementMatches[2], -1 ) === '/' ?
' /' : '';
449 foreach ( [ 'title', 'alt' ] as $attrName ) {
450 if ( !isset( $attrs[$attrName] ) ) {
453 $attr = $attrs[$attrName];
454 // Don't convert URLs
455 if ( !strpos( $attr, '://' ) ) {
456 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
459 if ( $attr !== $attrs[$attrName] ) {
460 $attrs[$attrName] = $attr;
465 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
466 $close . $elementMatches[3];
469 $literalBlob .= $element . "\000";
472 // Do the main translation batch
473 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
475 // Put the output back together
476 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
477 $literalIter = StringUtils
::explode( "\000", $literalBlob );
479 while ( $translatedIter->valid() && $literalIter->valid() ) {
480 $output .= $translatedIter->current();
481 $output .= $literalIter->current();
482 $translatedIter->next();
483 $literalIter->next();
490 * Translate a string to a variant.
491 * Doesn't parse rules or do any of that other stuff, for that use
492 * convert() or convertTo().
494 * @param string $text Text to convert
495 * @param string $variant Variant language code
496 * @return string Translated text
498 public function translate( $text, $variant ) {
499 // If $text is empty or only includes spaces, do nothing
500 // Otherwise translate it
501 if ( trim( $text ) ) {
503 $text = $this->mTables
[$variant]->replace( $text );
509 * Call translate() to convert text to all valid variants.
511 * @param string $text The text to be converted
512 * @return array Variant => converted text
514 public function autoConvertToAllVariants( $text ) {
518 foreach ( $this->mVariants
as $variant ) {
519 $ret[$variant] = $this->translate( $text, $variant );
526 * Apply manual conversion rules.
528 * @param ConverterRule $convRule
530 protected function applyManualConv( $convRule ) {
531 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
533 // T26072: $mConvRuleTitle was overwritten by other manual
534 // rule(s) not for title, this breaks the title conversion.
535 $newConvRuleTitle = $convRule->getTitle();
536 if ( $newConvRuleTitle ) {
537 // So I add an empty check for getTitle()
538 $this->mConvRuleTitle
= $newConvRuleTitle;
541 // merge/remove manual conversion rules to/from global table
542 $convTable = $convRule->getConvTable();
543 $action = $convRule->getRulesAction();
544 foreach ( $convTable as $variant => $pair ) {
545 if ( !$this->validateVariant( $variant ) ) {
549 if ( $action == 'add' ) {
550 // More efficient than array_merge(), about 2.5 times.
551 foreach ( $pair as $from => $to ) {
552 $this->mTables
[$variant]->setPair( $from, $to );
554 } elseif ( $action == 'remove' ) {
555 $this->mTables
[$variant]->removeArray( $pair );
561 * Auto convert a Title object to a readable string in the
564 * @param Title $title A object of Title
565 * @return string Converted title text
567 public function convertTitle( $title ) {
568 $variant = $this->getPreferredVariant();
569 $index = $title->getNamespace();
570 if ( $index !== NS_MAIN
) {
571 $text = $this->convertNamespace( $index, $variant ) . ':';
575 $text .= $this->translate( $title->getText(), $variant );
580 * Get the namespace display name in the preferred variant.
582 * @param int $index Namespace id
583 * @param string|null $variant Variant code or null for preferred variant
584 * @return string Namespace name for display
586 public function convertNamespace( $index, $variant = null ) {
587 if ( $index === NS_MAIN
) {
591 if ( $variant === null ) {
592 $variant = $this->getPreferredVariant();
595 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
596 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
597 $nsVariantText = $cache->get( $key );
598 if ( $nsVariantText !== false ) {
599 return $nsVariantText;
602 // First check if a message gives a converted name in the target variant.
603 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
604 if ( $nsConvMsg->exists() ) {
605 $nsVariantText = $nsConvMsg->plain();
608 // Then check if a message gives a converted name in content language
609 // which needs extra translation to the target variant.
610 if ( $nsVariantText === false ) {
611 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
612 if ( $nsConvMsg->exists() ) {
613 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
617 if ( $nsVariantText === false ) {
618 // No message exists, retrieve it from the target variant's namespace names.
619 $langObj = $this->mLangObj
->factory( $variant );
620 $nsVariantText = $langObj->getFormattedNsText( $index );
623 $cache->set( $key, $nsVariantText, 60 );
625 return $nsVariantText;
629 * Convert text to different variants of a language. The automatic
630 * conversion is done in autoConvert(). Here we parse the text
631 * marked with -{}-, which specifies special conversions of the
632 * text that can not be accomplished in autoConvert().
634 * Syntax of the markup:
635 * -{code1:text1;code2:text2;...}- or
636 * -{flags|code1:text1;code2:text2;...}- or
637 * -{text}- in which case no conversion should take place for text
639 * @param string $text Text to be converted
640 * @return string Converted text
642 public function convert( $text ) {
643 $variant = $this->getPreferredVariant();
644 return $this->convertTo( $text, $variant );
648 * Same as convert() except a extra parameter to custom variant.
650 * @param string $text Text to be converted
651 * @param string $variant The target variant code
652 * @return string Converted text
654 public function convertTo( $text, $variant ) {
655 global $wgDisableLangConversion;
656 if ( $wgDisableLangConversion ) {
659 // Reset converter state for a new converter run.
660 $this->mConvRuleTitle
= false;
661 return $this->recursiveConvertTopLevel( $text, $variant );
665 * Recursively convert text on the outside. Allow to use nested
666 * markups to custom rules.
668 * @param string $text Text to be converted
669 * @param string $variant The target variant code
670 * @param int $depth Depth of recursion
671 * @return string Converted text
673 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
676 $length = strlen( $text );
677 $shouldConvert = !$this->guessVariant( $text, $variant );
680 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
681 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
682 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
683 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
684 // @codingStandardsIgnoreEnd
685 while ( $startPos < $length && $continue ) {
686 $continue = preg_match(
687 // Only match -{ outside of html.
688 "/$noScript|$noStyle|$noHtml|-\{/",
696 // No more markup, append final segment
697 $fragment = substr( $text, $startPos );
698 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
702 // Offset of the match of the regex pattern.
705 // Append initial segment
706 $fragment = substr( $text, $startPos, $pos - $startPos );
707 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
708 // -{ marker found, not in attribute
709 // Advance position up to -{ marker.
711 // Do recursive conversion
712 // Note: This passes $startPos by reference, and advances it.
713 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
719 * Recursively convert text on the inside.
721 * @param string $text Text to be converted
722 * @param string $variant The target variant code
723 * @param int &$startPos
724 * @param int $depth Depth of recursion
726 * @throws MWException
727 * @return string Converted text
729 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
730 // Quick sanity check (no function calls)
731 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
732 throw new MWException( __METHOD__
. ': invalid input string' );
737 $warningDone = false;
738 $length = strlen( $text );
740 while ( $startPos < $length ) {
742 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
752 // Append initial segment
753 $inner .= substr( $text, $startPos, $pos - $startPos );
761 if ( $depth >= $this->mMaxDepth
) {
763 if ( !$warningDone ) {
764 $inner .= '<span class="error">' .
765 wfMessage( 'language-converter-depth-warning' )
766 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
773 // Recursively parse another rule
774 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
779 $rule = new ConverterRule( $inner, $this );
780 $rule->parse( $variant );
781 $this->applyManualConv( $rule );
782 return $rule->getDisplay();
784 throw new MWException( __METHOD__
. ': invalid regex match' );
789 if ( $startPos < $length ) {
790 $inner .= substr( $text, $startPos );
793 return '-{' . $this->autoConvert( $inner, $variant );
797 * If a language supports multiple variants, it is possible that
798 * non-existing link in one variant actually exists in another variant.
799 * This function tries to find it. See e.g. LanguageZh.php
800 * The input parameters may be modified upon return
802 * @param string &$link The name of the link
803 * @param Title &$nt The title object of the link
804 * @param bool $ignoreOtherCond To disable other conditions when
805 * we need to transclude a template or update a category's link
807 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
808 # If the article has already existed, there is no need to
809 # check it again, otherwise it may cause a fault.
810 if ( is_object( $nt ) && $nt->exists() ) {
814 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
815 $isredir = $wgRequest->getText( 'redirect', 'yes' );
816 $action = $wgRequest->getText( 'action' );
817 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
820 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
821 $disableLinkConversion = $wgDisableLangConversion
822 ||
$wgDisableTitleConversion;
823 $linkBatch = new LinkBatch();
827 if ( $disableLinkConversion ||
828 ( !$ignoreOtherCond &&
831 ||
$action == 'submit'
832 ||
$linkconvert == 'no' ) ) ) {
836 if ( is_object( $nt ) ) {
837 $ns = $nt->getNamespace();
840 $variants = $this->autoConvertToAllVariants( $link );
841 if ( !$variants ) { // give up
847 foreach ( $variants as $v ) {
849 $varnt = Title
::newFromText( $v, $ns );
850 if ( !is_null( $varnt ) ) {
851 $linkBatch->addObj( $varnt );
857 // fetch all variants in single query
858 $linkBatch->execute();
860 foreach ( $titles as $varnt ) {
861 if ( $varnt->getArticleID() > 0 ) {
863 $link = $varnt->getText();
870 * Returns language specific hash options.
874 public function getExtraHashOptions() {
875 $variant = $this->getPreferredVariant();
877 return '!' . $variant;
881 * Guess if a text is written in a variant. This should be implemented in subclasses.
883 * @param string $text The text to be checked
884 * @param string $variant Language code of the variant to be checked for
885 * @return bool True if $text appears to be written in $variant, false if not
887 * @author Nikola Smolenski <smolensk@eunet.rs>
890 public function guessVariant( $text, $variant ) {
895 * Load default conversion tables.
896 * This method must be implemented in derived class.
899 * @throws MWException
901 function loadDefaultTables() {
902 $class = static::class;
903 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
907 * Load conversion tables either from the cache or the disk.
909 * @param bool $fromCache Load from memcached? Defaults to true.
911 function loadTables( $fromCache = true ) {
912 global $wgLanguageConverterCacheType;
914 if ( $this->mTablesLoaded
) {
918 $this->mTablesLoaded
= true;
919 $this->mTables
= false;
920 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
921 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
923 $this->mTables
= $cache->get( $cacheKey );
925 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
926 // not in cache, or we need a fresh reload.
927 // We will first load the default tables
928 // then update them using things in MediaWiki:Conversiontable/*
929 $this->loadDefaultTables();
930 foreach ( $this->mVariants
as $var ) {
931 $cached = $this->parseCachedTable( $var );
932 $this->mTables
[$var]->mergeArray( $cached );
935 $this->postLoadTables();
936 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
938 $cache->set( $cacheKey, $this->mTables
, 43200 );
943 * Hook for post processing after conversion tables are loaded.
945 function postLoadTables() {
949 * Reload the conversion tables.
951 * Also used by test suites which need to reset the converter state.
955 private function reloadTables() {
956 if ( $this->mTables
) {
957 unset( $this->mTables
);
960 $this->mTablesLoaded
= false;
961 $this->loadTables( false );
965 * Parse the conversion table stored in the cache.
967 * The tables should be in blocks of the following form:
974 * To make the tables more manageable, subpages are allowed
975 * and will be parsed recursively if $recursive == true.
977 * @param string $code Language code
978 * @param string $subpage Subpage name
979 * @param bool $recursive Parse subpages recursively? Defaults to true.
983 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
986 $key = 'Conversiontable/' . $code;
988 $key .= '/' . $subpage;
990 if ( array_key_exists( $key, $parsed ) ) {
994 $parsed[$key] = true;
996 if ( $subpage === '' ) {
997 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1000 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1001 if ( $title && $title->exists() ) {
1002 $revision = Revision
::newFromTitle( $title );
1004 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1005 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
1008 // @todo in the future, use a specialized content model, perhaps based on json!
1013 # Nothing to parse if there's no text
1014 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1018 // get all subpage links of the form
1019 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1020 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1022 $subs = StringUtils
::explode( '[[', $txt );
1024 foreach ( $subs as $sub ) {
1025 $link = explode( ']]', $sub, 2 );
1026 if ( count( $link ) != 2 ) {
1029 $b = explode( '|', $link[0], 2 );
1030 $b = explode( '/', trim( $b[0] ), 3 );
1031 if ( count( $b ) == 3 ) {
1037 if ( $b[0] == $linkhead && $b[1] == $code ) {
1038 $sublinks[] = $sublink;
1042 // parse the mappings in this page
1043 $blocks = StringUtils
::explode( '-{', $txt );
1046 foreach ( $blocks as $block ) {
1048 // Skip the part before the first -{
1052 $mappings = explode( '}-', $block, 2 )[0];
1053 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1054 $table = StringUtils
::explode( ';', $stripped );
1055 foreach ( $table as $t ) {
1056 $m = explode( '=>', $t, 3 );
1057 if ( count( $m ) != 2 ) {
1060 // trim any trailling comments starting with '//'
1061 $tt = explode( '//', $m[1], 2 );
1062 $ret[trim( $m[0] )] = trim( $tt[0] );
1066 // recursively parse the subpages
1068 foreach ( $sublinks as $link ) {
1069 $s = $this->parseCachedTable( $code, $link, $recursive );
1074 if ( $this->mUcfirst
) {
1075 foreach ( $ret as $k => $v ) {
1076 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1083 * Enclose a string with the "no conversion" tag. This is used by
1084 * various functions in the Parser.
1086 * @param string $text Text to be tagged for no conversion
1087 * @param bool $noParse Unused
1088 * @return string The tagged text
1090 public function markNoConversion( $text, $noParse = false ) {
1091 # don't mark if already marked
1092 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1096 $ret = "-{R|$text}-";
1101 * Convert the sorting key for category links. This should make different
1102 * keys that are variants of each other map to the same key.
1104 * @param string $key
1108 function convertCategoryKey( $key ) {
1113 * Refresh the cache of conversion tables when
1114 * MediaWiki:Conversiontable* is updated.
1116 * @param Title $titleobj The Title of the page being updated
1118 public function updateConversionTable( Title
$titleobj ) {
1119 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1120 $title = $titleobj->getDBkey();
1121 $t = explode( '/', $title, 3 );
1123 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1124 if ( $this->validateVariant( $t[1] ) ) {
1125 $this->reloadTables();
1132 * Get the cached separator pattern for ConverterRule::parseRules()
1135 function getVarSeparatorPattern() {
1136 if ( is_null( $this->mVarSeparatorPattern
) ) {
1137 // varsep_pattern for preg_split:
1138 // text should be splited by ";" only if a valid variant
1139 // name exist after the markup, for example:
1140 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1141 // <span style="font-size:120%;">yyy</span>;}-
1142 // we should split it as:
1144 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1145 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1149 foreach ( $this->mVariants
as $variant ) {
1150 // zh-hans:xxx;zh-hant:yyy
1151 $pat .= $variant . '\s*:|';
1152 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1153 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1156 $this->mVarSeparatorPattern
= $pat;
1158 return $this->mVarSeparatorPattern
;