34 class LanguageConverter {
40 static public $languagesWithVariants = [
54 public $mMainLanguageCode;
60 public $mVariantFallbacks;
61 public $mVariantNames;
62 public $mTablesLoaded =
false;
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';
88 public function __construct(
Language $langobj, $maincode, $variants = [],
89 $variantfallbacks = [], $flags = [],
92 $this->mLangObj = $langobj;
93 $this->mMainLanguageCode = $maincode;
95 $this->mVariantFallbacks = $variantfallbacks;
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;
127 public function getVariants() {
128 return $this->mVariants;
142 public function getVariantFallbacks( $variant ) {
143 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
144 return $this->mVariantFallbacks[$variant];
146 return $this->mMainLanguageCode;
153 public function getConvRuleTitle() {
154 return $this->mConvRuleTitle;
161 public function getPreferredVariant() {
164 $req = $this->getURLVariant();
168 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !
$req ) {
169 $req = $this->getUserVariant();
171 $req = $this->getHeaderVariant();
178 $req = $this->validateVariant(
$req );
187 return $this->mMainLanguageCode;
195 public function getDefaultVariant() {
198 $req = $this->getURLVariant();
201 $req = $this->getHeaderVariant();
211 return $this->mMainLanguageCode;
223 public function validateVariant( $variant =
null ) {
224 if ( $variant ===
null ) {
230 if ( in_array( $variant, $this->mVariants ) ) {
237 foreach ( $this->mVariants
as $v ) {
251 public function getURLVariant() {
254 if ( $this->mURLVariant ) {
255 return $this->mURLVariant;
265 $this->mURLVariant = $this->validateVariant(
$ret );
266 return $this->mURLVariant;
274 protected function getUserVariant() {
287 if ( !$wgUser->isSafeToLoad() ) {
290 if ( $wgUser->isLoggedIn() ) {
292 $this->mMainLanguageCode ==
293 MediaWikiServices::getInstance()->getContentLanguage()->getCode()
295 $ret = $wgUser->getOption(
'variant' );
297 $ret = $wgUser->getOption(
'variant-' . $this->mMainLanguageCode );
302 $ret = $wgUser->getOption(
'language' );
305 $this->mUserVariant = $this->validateVariant(
$ret );
306 return $this->mUserVariant;
314 protected function getHeaderVariant() {
317 if ( $this->mHeaderVariant ) {
318 return $this->mHeaderVariant;
328 $fallbackLanguages = [];
330 $this->mHeaderVariant = $this->validateVariant( $language );
331 if ( $this->mHeaderVariant ) {
338 $fallbacks = $this->getVariantFallbacks( $language );
339 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
340 $fallbackLanguages[] = $fallbacks;
341 } elseif ( is_array( $fallbacks ) ) {
343 array_merge( $fallbackLanguages, $fallbacks );
347 if ( !$this->mHeaderVariant ) {
349 $fallback_languages = array_unique( $fallbackLanguages );
350 foreach ( $fallback_languages
as $language ) {
351 $this->mHeaderVariant = $this->validateVariant( $language );
352 if ( $this->mHeaderVariant ) {
358 return $this->mHeaderVariant;
371 public function autoConvert( $text, $toVariant =
false ) {
375 $toVariant = $this->getPreferredVariant();
381 if ( $this->guessVariant( $text, $toVariant ) ) {
391 $marker =
'|' . Parser::MARKER_PREFIX .
'[^\x7f]++\x7f';
394 $htmlfix =
'|<[^>\004]++(?=\004$)|^[^<>]*+>';
401 $codefix =
'<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
403 $scriptfix =
'<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
405 $prefix =
'<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
408 $htmlFullTag =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
410 $reg =
'/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
411 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix .
'|\004$/s';
418 $text = str_replace(
"\000",
'', $text );
419 $text = str_replace(
"\004",
'', $text );
421 $markupMatches =
null;
422 $elementMatches =
null;
426 while ( $startPos < strlen( $text ) ) {
427 if ( preg_match( $reg, $text .
"\004", $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
428 $elementPos = $markupMatches[0][1];
429 $element = $markupMatches[0][0];
430 if ( $element ===
"\004" ) {
432 $elementPos = strlen( $text );
434 } elseif ( substr( $element, -1 ) ===
"\004" ) {
440 $element = substr( $element, 0, -1 );
447 $log = LoggerFactory::getInstance(
'languageconverter' );
448 $log->error(
"Hit pcre.backtrack_limit in " . __METHOD__
449 .
". Disabling language conversion for this page.",
451 "method" => __METHOD__,
452 "variant" => $toVariant,
453 "startOfText" => substr( $text, 0, 500 )
459 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) .
"\000";
462 $startPos = $elementPos + strlen( $element );
466 && preg_match(
'/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
473 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
475 $close = substr( $elementMatches[2], -1 ) ===
'/' ?
' /' :
'';
477 foreach ( [
'title',
'alt' ]
as $attrName ) {
478 if ( !isset( $attrs[$attrName] ) ) {
481 $attr = $attrs[$attrName];
483 if ( !strpos( $attr,
'://' ) ) {
484 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
487 if ( $attr !== $attrs[$attrName] ) {
488 $attrs[$attrName] = $attr;
494 $close . $elementMatches[3];
497 $literalBlob .= $element .
"\000";
501 $translatedBlob = $this->
translate( $sourceBlob, $toVariant );
507 while ( $translatedIter->valid() && $literalIter->valid() ) {
508 $output .= $translatedIter->current();
509 $output .= $literalIter->current();
510 $translatedIter->next();
511 $literalIter->next();
526 public function translate( $text, $variant ) {
529 if ( trim( $text ) ) {
531 $text = $this->mTables[$variant]->replace( $text );
542 public function autoConvertToAllVariants( $text ) {
546 foreach ( $this->mVariants
as $variant ) {
558 protected function applyManualConv( $convRule ) {
563 $newConvRuleTitle = $convRule->getTitle();
564 if ( $newConvRuleTitle ) {
566 $this->mConvRuleTitle = $newConvRuleTitle;
570 $convTable = $convRule->getConvTable();
571 $action = $convRule->getRulesAction();
572 foreach ( $convTable
as $variant => $pair ) {
573 $v = $this->validateVariant( $variant );
578 if ( $action ==
'add' ) {
580 foreach ( $pair
as $from => $to ) {
581 $this->mTables[$v]->setPair( $from, $to );
583 } elseif ( $action ==
'remove' ) {
584 $this->mTables[$v]->removeArray( $pair );
596 public function convertTitle(
$title ) {
597 $variant = $this->getPreferredVariant();
598 $index =
$title->getNamespace();
600 $text = $this->convertNamespace( $index, $variant ) .
':';
615 public function convertNamespace( $index, $variant =
null ) {
620 if ( $variant ===
null ) {
621 $variant = $this->getPreferredVariant();
624 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
625 $key =
$cache->makeKey(
'languageconverter',
'namespace-text', $index, $variant );
626 $nsVariantText =
$cache->get( $key );
627 if ( $nsVariantText !==
false ) {
628 return $nsVariantText;
632 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inLanguage( $variant );
633 if ( $nsConvMsg->exists() ) {
634 $nsVariantText = $nsConvMsg->plain();
639 if ( $nsVariantText ===
false ) {
640 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inContentLanguage();
641 if ( $nsConvMsg->exists() ) {
642 $nsVariantText = $this->
translate( $nsConvMsg->plain(), $variant );
646 if ( $nsVariantText ===
false ) {
648 $langObj = $this->mLangObj->factory( $variant );
649 $nsVariantText = $langObj->getFormattedNsText( $index );
652 $cache->set( $key, $nsVariantText, 60 );
654 return $nsVariantText;
675 public function convert( $text ) {
676 $variant = $this->getPreferredVariant();
677 return $this->convertTo( $text, $variant );
689 public function convertTo( $text, $variant ) {
695 $this->mConvRuleTitle =
false;
696 return $this->recursiveConvertTopLevel( $text, $variant );
708 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
711 $length = strlen( $text );
712 $shouldConvert = !$this->guessVariant( $text, $variant );
715 $noScript =
'<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
716 $noStyle =
'<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
718 $noHtml =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
719 while ( $startPos < $length && $continue ) {
720 $continue = preg_match(
722 "/$noScript|$noStyle|$noHtml|-\{/",
731 $fragment = substr( $text, $startPos );
732 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
740 $fragment = substr( $text, $startPos, $pos - $startPos );
741 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
747 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
763 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
765 if ( $text[$startPos] !==
'-' || $text[$startPos + 1] !==
'{' ) {
766 throw new MWException( __METHOD__ .
': invalid input string' );
771 $warningDone =
false;
772 $length = strlen( $text );
774 while ( $startPos < $length ) {
776 preg_match(
'/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
787 $inner .= substr( $text, $startPos, $pos - $startPos );
795 if ( $depth >= $this->mMaxDepth ) {
797 if ( !$warningDone ) {
798 $inner .=
'<span class="error">' .
799 wfMessage(
'language-converter-depth-warning' )
800 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
808 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
814 $rule->parse( $variant );
815 $this->applyManualConv( $rule );
816 return $rule->getDisplay();
818 throw new MWException( __METHOD__ .
': invalid regex match' );
823 if ( $startPos < $length ) {
824 $inner .= substr( $text, $startPos );
827 return '-{' . $this->autoConvert( $inner, $variant );
841 public function findVariantLink( &
$link, &$nt, $ignoreOtherCond =
false ) {
842 # If the article has already existed, there is no need to
843 # check it again, otherwise it may cause a fault.
844 if ( is_object( $nt ) && $nt->exists() ) {
849 $isredir =
$wgRequest->getText(
'redirect',
'yes' );
851 if ( $action ==
'edit' &&
$wgRequest->getBool(
'redlink' ) ) {
854 $linkconvert =
$wgRequest->getText(
'linkconvert',
'yes' );
861 if ( $disableLinkConversion ||
862 ( !$ignoreOtherCond &&
865 || $action ==
'submit'
866 || $linkconvert ==
'no' ) ) ) {
870 if ( is_object( $nt ) ) {
871 $ns = $nt->getNamespace();
874 $variants = $this->autoConvertToAllVariants(
$link );
881 foreach ( $variants
as $v ) {
884 if ( !is_null( $varnt ) ) {
885 $linkBatch->addObj( $varnt );
892 $linkBatch->execute();
895 if ( $varnt->getArticleID() > 0 ) {
897 $link = $varnt->getText();
908 public function getExtraHashOptions() {
909 $variant = $this->getPreferredVariant();
911 return '!' . $variant;
924 public function guessVariant( $text, $variant ) {
935 function loadDefaultTables() {
937 throw new MWException(
"Must implement loadDefaultTables() method in class $class" );
945 function loadTables( $fromCache =
true ) {
948 if ( $this->mTablesLoaded ) {
952 $this->mTablesLoaded =
true;
953 $this->mTables =
false;
955 $cacheKey =
$cache->makeKey(
'conversiontables', $this->mMainLanguageCode );
957 $this->mTables =
$cache->get( $cacheKey );
959 if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
963 $this->loadDefaultTables();
964 foreach ( $this->mVariants
as $var ) {
965 $cached = $this->parseCachedTable( $var );
966 $this->mTables[$var]->mergeArray( $cached );
969 $this->postLoadTables();
970 $this->mTables[self::CACHE_VERSION_KEY] =
true;
972 $cache->set( $cacheKey, $this->mTables, 43200 );
979 function postLoadTables() {
989 private function reloadTables() {
990 if ( $this->mTables ) {
991 unset( $this->mTables );
994 $this->mTablesLoaded =
false;
995 $this->loadTables(
false );
1017 function parseCachedTable(
$code, $subpage =
'', $recursive =
true ) {
1018 static $parsed = [];
1020 $key =
'Conversiontable/' .
$code;
1022 $key .=
'/' . $subpage;
1024 if ( array_key_exists( $key, $parsed ) ) {
1028 $parsed[$key] =
true;
1030 if ( $subpage ===
'' ) {
1039 $txt = $revision->getContent(
Revision::RAW )->getNativeData();
1047 # Nothing to parse if there's no text
1048 if ( $txt ===
false || $txt ===
null || $txt ===
'' ) {
1054 $linkhead = $this->mLangObj->getNsText(
NS_MEDIAWIKI ) .
1058 foreach ( $subs
as $sub ) {
1059 $link = explode(
']]', $sub, 2 );
1063 $b = explode(
'|',
$link[0], 2 );
1064 $b = explode(
'/', trim( $b[0] ), 3 );
1065 if (
count( $b ) == 3 ) {
1071 if ( $b[0] == $linkhead && $b[1] ==
$code ) {
1072 $sublinks[] = $sublink;
1080 foreach ( $blocks
as $block ) {
1086 $mappings = explode(
'}-', $block, 2 )[0];
1087 $stripped = str_replace( [
"'",
'"',
'*',
'#' ],
'', $mappings );
1089 foreach ( $table
as $t ) {
1090 $m = explode(
'=>',
$t, 3 );
1091 if (
count( $m ) != 2 ) {
1095 $tt = explode(
'//', $m[1], 2 );
1096 $ret[trim( $m[0] )] = trim( $tt[0] );
1102 foreach ( $sublinks
as $link ) {
1103 $s = $this->parseCachedTable(
$code,
$link, $recursive );
1108 if ( $this->mUcfirst ) {
1109 foreach (
$ret as $k => $v ) {
1110 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1124 public function markNoConversion( $text, $noParse =
false ) {
1125 # don't mark if already marked
1126 if ( strpos( $text,
'-{' ) || strpos( $text,
'}-' ) ) {
1130 $ret =
"-{R|$text}-";
1142 function convertCategoryKey( $key ) {
1152 public function updateConversionTable(
Title $titleobj ) {
1157 if ( $c > 1 &&
$t[0] ==
'Conversiontable' ) {
1158 if ( $this->validateVariant(
$t[1] ) ) {
1159 $this->reloadTables();
1169 function getVarSeparatorPattern() {
1170 if ( is_null( $this->mVarSeparatorPattern ) ) {
1183 foreach ( $this->mVariants
as $variant ) {
1185 $pat .= $variant .
'\s*:|';
1187 $pat .=
'[^;]*?=>\s*' . $variant .
'\s*:|';
1190 $this->mVarSeparatorPattern = $pat;
1192 return $this->mVarSeparatorPattern;