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 * @warning Glossary state is maintained between calls. Never feed this
646 * method input that hasn't properly been escaped as it may result in
647 * an XSS in subsequent calls, even if those subsequent calls properly
649 * @param string $text Text to be converted, already html escaped.
650 * @return string Converted text (html)
652 public function convert( $text ) {
653 $variant = $this->getPreferredVariant();
654 return $this->convertTo( $text, $variant );
658 * Same as convert() except a extra parameter to custom variant.
660 * @param string $text Text to be converted, already html escaped
661 * @param-taint $text exec_html
662 * @param string $variant The target variant code
663 * @return string Converted text
664 * @return-taint escaped
666 public function convertTo( $text, $variant ) {
667 global $wgDisableLangConversion;
668 if ( $wgDisableLangConversion ) {
671 // Reset converter state for a new converter run.
672 $this->mConvRuleTitle
= false;
673 return $this->recursiveConvertTopLevel( $text, $variant );
677 * Recursively convert text on the outside. Allow to use nested
678 * markups to custom rules.
680 * @param string $text Text to be converted
681 * @param string $variant The target variant code
682 * @param int $depth Depth of recursion
683 * @return string Converted text
685 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
688 $length = strlen( $text );
689 $shouldConvert = !$this->guessVariant( $text, $variant );
692 $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
693 $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
694 // phpcs:ignore Generic.Files.LineLength
695 $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
696 while ( $startPos < $length && $continue ) {
697 $continue = preg_match(
698 // Only match -{ outside of html.
699 "/$noScript|$noStyle|$noHtml|-\{/",
707 // No more markup, append final segment
708 $fragment = substr( $text, $startPos );
709 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
713 // Offset of the match of the regex pattern.
716 // Append initial segment
717 $fragment = substr( $text, $startPos, $pos - $startPos );
718 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
719 // -{ marker found, not in attribute
720 // Advance position up to -{ marker.
722 // Do recursive conversion
723 // Note: This passes $startPos by reference, and advances it.
724 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
730 * Recursively convert text on the inside.
732 * @param string $text Text to be converted
733 * @param string $variant The target variant code
734 * @param int &$startPos
735 * @param int $depth Depth of recursion
737 * @throws MWException
738 * @return string Converted text
740 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
741 // Quick sanity check (no function calls)
742 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
743 throw new MWException( __METHOD__
. ': invalid input string' );
748 $warningDone = false;
749 $length = strlen( $text );
751 while ( $startPos < $length ) {
753 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
763 // Append initial segment
764 $inner .= substr( $text, $startPos, $pos - $startPos );
772 if ( $depth >= $this->mMaxDepth
) {
774 if ( !$warningDone ) {
775 $inner .= '<span class="error">' .
776 wfMessage( 'language-converter-depth-warning' )
777 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
784 // Recursively parse another rule
785 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
790 $rule = new ConverterRule( $inner, $this );
791 $rule->parse( $variant );
792 $this->applyManualConv( $rule );
793 return $rule->getDisplay();
795 throw new MWException( __METHOD__
. ': invalid regex match' );
800 if ( $startPos < $length ) {
801 $inner .= substr( $text, $startPos );
804 return '-{' . $this->autoConvert( $inner, $variant );
808 * If a language supports multiple variants, it is possible that
809 * non-existing link in one variant actually exists in another variant.
810 * This function tries to find it. See e.g. LanguageZh.php
811 * The input parameters may be modified upon return
813 * @param string &$link The name of the link
814 * @param Title &$nt The title object of the link
815 * @param bool $ignoreOtherCond To disable other conditions when
816 * we need to transclude a template or update a category's link
818 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
819 # If the article has already existed, there is no need to
820 # check it again, otherwise it may cause a fault.
821 if ( is_object( $nt ) && $nt->exists() ) {
825 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
826 $isredir = $wgRequest->getText( 'redirect', 'yes' );
827 $action = $wgRequest->getText( 'action' );
828 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
831 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
832 $disableLinkConversion = $wgDisableLangConversion
833 ||
$wgDisableTitleConversion;
834 $linkBatch = new LinkBatch();
838 if ( $disableLinkConversion ||
839 ( !$ignoreOtherCond &&
842 ||
$action == 'submit'
843 ||
$linkconvert == 'no' ) ) ) {
847 if ( is_object( $nt ) ) {
848 $ns = $nt->getNamespace();
851 $variants = $this->autoConvertToAllVariants( $link );
852 if ( !$variants ) { // give up
858 foreach ( $variants as $v ) {
860 $varnt = Title
::newFromText( $v, $ns );
861 if ( !is_null( $varnt ) ) {
862 $linkBatch->addObj( $varnt );
868 // fetch all variants in single query
869 $linkBatch->execute();
871 foreach ( $titles as $varnt ) {
872 if ( $varnt->getArticleID() > 0 ) {
874 $link = $varnt->getText();
881 * Returns language specific hash options.
885 public function getExtraHashOptions() {
886 $variant = $this->getPreferredVariant();
888 return '!' . $variant;
892 * Guess if a text is written in a variant. This should be implemented in subclasses.
894 * @param string $text The text to be checked
895 * @param string $variant Language code of the variant to be checked for
896 * @return bool True if $text appears to be written in $variant, false if not
898 * @author Nikola Smolenski <smolensk@eunet.rs>
901 public function guessVariant( $text, $variant ) {
906 * Load default conversion tables.
907 * This method must be implemented in derived class.
910 * @throws MWException
912 function loadDefaultTables() {
913 $class = static::class;
914 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
918 * Load conversion tables either from the cache or the disk.
920 * @param bool $fromCache Load from memcached? Defaults to true.
922 function loadTables( $fromCache = true ) {
923 global $wgLanguageConverterCacheType;
925 if ( $this->mTablesLoaded
) {
929 $this->mTablesLoaded
= true;
930 $this->mTables
= false;
931 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
932 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
934 $this->mTables
= $cache->get( $cacheKey );
936 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
937 // not in cache, or we need a fresh reload.
938 // We will first load the default tables
939 // then update them using things in MediaWiki:Conversiontable/*
940 $this->loadDefaultTables();
941 foreach ( $this->mVariants
as $var ) {
942 $cached = $this->parseCachedTable( $var );
943 $this->mTables
[$var]->mergeArray( $cached );
946 $this->postLoadTables();
947 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
949 $cache->set( $cacheKey, $this->mTables
, 43200 );
954 * Hook for post processing after conversion tables are loaded.
956 function postLoadTables() {
960 * Reload the conversion tables.
962 * Also used by test suites which need to reset the converter state.
966 private function reloadTables() {
967 if ( $this->mTables
) {
968 unset( $this->mTables
);
971 $this->mTablesLoaded
= false;
972 $this->loadTables( false );
976 * Parse the conversion table stored in the cache.
978 * The tables should be in blocks of the following form:
985 * To make the tables more manageable, subpages are allowed
986 * and will be parsed recursively if $recursive == true.
988 * @param string $code Language code
989 * @param string $subpage Subpage name
990 * @param bool $recursive Parse subpages recursively? Defaults to true.
994 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
997 $key = 'Conversiontable/' . $code;
999 $key .= '/' . $subpage;
1001 if ( array_key_exists( $key, $parsed ) ) {
1005 $parsed[$key] = true;
1007 if ( $subpage === '' ) {
1008 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
1011 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
1012 if ( $title && $title->exists() ) {
1013 $revision = Revision
::newFromTitle( $title );
1015 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
1016 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
1019 // @todo in the future, use a specialized content model, perhaps based on json!
1024 # Nothing to parse if there's no text
1025 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
1029 // get all subpage links of the form
1030 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1031 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
1033 $subs = StringUtils
::explode( '[[', $txt );
1035 foreach ( $subs as $sub ) {
1036 $link = explode( ']]', $sub, 2 );
1037 if ( count( $link ) != 2 ) {
1040 $b = explode( '|', $link[0], 2 );
1041 $b = explode( '/', trim( $b[0] ), 3 );
1042 if ( count( $b ) == 3 ) {
1048 if ( $b[0] == $linkhead && $b[1] == $code ) {
1049 $sublinks[] = $sublink;
1053 // parse the mappings in this page
1054 $blocks = StringUtils
::explode( '-{', $txt );
1057 foreach ( $blocks as $block ) {
1059 // Skip the part before the first -{
1063 $mappings = explode( '}-', $block, 2 )[0];
1064 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1065 $table = StringUtils
::explode( ';', $stripped );
1066 foreach ( $table as $t ) {
1067 $m = explode( '=>', $t, 3 );
1068 if ( count( $m ) != 2 ) {
1071 // trim any trailling comments starting with '//'
1072 $tt = explode( '//', $m[1], 2 );
1073 $ret[trim( $m[0] )] = trim( $tt[0] );
1077 // recursively parse the subpages
1079 foreach ( $sublinks as $link ) {
1080 $s = $this->parseCachedTable( $code, $link, $recursive );
1085 if ( $this->mUcfirst
) {
1086 foreach ( $ret as $k => $v ) {
1087 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1094 * Enclose a string with the "no conversion" tag. This is used by
1095 * various functions in the Parser.
1097 * @param string $text Text to be tagged for no conversion
1098 * @param bool $noParse Unused
1099 * @return string The tagged text
1101 public function markNoConversion( $text, $noParse = false ) {
1102 # don't mark if already marked
1103 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1107 $ret = "-{R|$text}-";
1112 * Convert the sorting key for category links. This should make different
1113 * keys that are variants of each other map to the same key.
1115 * @param string $key
1119 function convertCategoryKey( $key ) {
1124 * Refresh the cache of conversion tables when
1125 * MediaWiki:Conversiontable* is updated.
1127 * @param Title $titleobj The Title of the page being updated
1129 public function updateConversionTable( Title
$titleobj ) {
1130 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1131 $title = $titleobj->getDBkey();
1132 $t = explode( '/', $title, 3 );
1134 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1135 if ( $this->validateVariant( $t[1] ) ) {
1136 $this->reloadTables();
1143 * Get the cached separator pattern for ConverterRule::parseRules()
1146 function getVarSeparatorPattern() {
1147 if ( is_null( $this->mVarSeparatorPattern
) ) {
1148 // varsep_pattern for preg_split:
1149 // text should be splited by ";" only if a valid variant
1150 // name exist after the markup, for example:
1151 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1152 // <span style="font-size:120%;">yyy</span>;}-
1153 // we should split it as:
1155 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1156 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1160 foreach ( $this->mVariants
as $variant ) {
1161 // zh-hans:xxx;zh-hant:yyy
1162 $pat .= $variant . '\s*:|';
1163 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1164 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1167 $this->mVarSeparatorPattern
= $pat;
1169 return $this->mVarSeparatorPattern
;