95 $variantfallbacks = [], $flags = [],
102 $this->mVariantNames = Language::fetchLanguageNames();
116 $this->mFlags =
array_merge( $defaultflags, $flags );
117 foreach ( $this->mVariants as $v ) {
119 $this->mManualLevel[
$v] = $manualLevel[
$v];
121 $this->mManualLevel[
$v] =
'bidirectional';
123 $this->mFlags[
$v] =
$v;
134 return $this->mVariants;
149 return $this->mVariantFallbacks[$variant] ?? $this->mMainLanguageCode;
157 return $this->mConvRuleTitle;
169 Hooks::run(
'GetLangPreferredVariant', [ &
$req ] );
171 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !
$req ) {
190 return $this->mMainLanguageCode;
214 return $this->mMainLanguageCode;
227 if ( $variant ===
null ) {
232 $variant = LanguageCode::replaceDeprecatedCodes(
strtolower( $variant ) );
233 if (
in_array( $variant, $this->mVariants ) ) {
240 foreach ( $this->mVariants as $v ) {
242 if (
strtolower( LanguageCode::bcp47( $v ) ) === $variant ) {
257 if ( $this->mURLVariant ) {
258 return $this->mURLVariant;
269 return $this->mURLVariant;
290 if ( !$wgUser->isSafeToLoad() ) {
293 if ( $wgUser->isLoggedIn() ) {
295 $this->mMainLanguageCode ==
296 MediaWikiServices::getInstance()->getContentLanguage()->getCode()
298 $ret = $wgUser->getOption(
'variant' );
300 $ret = $wgUser->getOption(
'variant-' . $this->mMainLanguageCode );
305 $ret = $wgUser->getOption(
'language' );
309 return $this->mUserVariant;
320 if ( $this->mHeaderVariant ) {
321 return $this->mHeaderVariant;
331 $fallbackLanguages = [];
334 if ( $this->mHeaderVariant ) {
342 if (
is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
350 if ( !$this->mHeaderVariant ) {
352 $fallback_languages =
array_unique( $fallbackLanguages );
353 foreach ( $fallback_languages as $language ) {
355 if ( $this->mHeaderVariant ) {
361 return $this->mHeaderVariant;
394 $marker =
'|' . Parser::MARKER_PREFIX .
'[^\x7f]++\x7f';
397 $htmlfix =
'|<[^>\004]++(?=\004$)|^[^<>]*+>';
404 $codefix =
'<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
406 $scriptfix =
'<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
408 $prefix =
'<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
411 $htmlFullTag =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
413 $reg =
'/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
414 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix .
'|\004$/s';
424 $markupMatches =
null;
425 $elementMatches =
null;
429 while ( $startPos <
strlen( $text ) ) {
430 if (
preg_match( $reg, $text .
"\004", $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
431 $elementPos = $markupMatches[0][1];
432 $element = $markupMatches[0][0];
433 if ( $element ===
"\004" ) {
435 $elementPos =
strlen( $text );
443 $element =
substr( $element, 0, -1 );
450 $log = LoggerFactory::getInstance(
'languageconverter' );
451 $log->error(
"Hit pcre.backtrack_limit in " . __METHOD__
452 .
". Disabling language conversion for this page.",
454 "method" => __METHOD__,
455 "variant" => $toVariant,
456 "startOfText" =>
substr( $text, 0, 500 )
462 $sourceBlob .=
substr( $text, $startPos, $elementPos - $startPos ) .
"\000";
465 $startPos = $elementPos +
strlen( $element );
469 &&
preg_match(
'/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
476 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
478 $close =
substr( $elementMatches[2], -1 ) ===
'/' ?
' /' :
'';
480 foreach ( [
'title',
'alt' ] as $attrName ) {
481 if ( !
isset( $attrs[$attrName] ) ) {
486 if ( !
strpos( $attr,
'://' ) ) {
490 if ( $attr !== $attrs[$attrName] ) {
496 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
497 $close . $elementMatches[3];
500 $literalBlob .= $element .
"\000";
504 $translatedBlob = $this->
translate( $sourceBlob, $toVariant );
507 $translatedIter = StringUtils::explode(
"\000", $translatedBlob );
508 $literalIter = StringUtils::explode(
"\000", $literalBlob );
510 while ( $translatedIter->valid() && $literalIter->valid() ) {
511 $output .= $translatedIter->current();
512 $output .= $literalIter->current();
513 $translatedIter->next();
514 $literalIter->next();
532 if (
trim( $text ) ) {
534 $text = $this->mTables[$variant]->replace( $text );
549 foreach ( $this->mVariants as $variant ) {
566 $newConvRuleTitle = $convRule->getTitle();
567 if ( $newConvRuleTitle ) {
573 $convTable = $convRule->getConvTable();
574 $action = $convRule->getRulesAction();
575 foreach ( $convTable as $variant => $pair ) {
581 if ( $action ==
'add' ) {
583 foreach ( $pair as $from => $to ) {
584 $this->mTables[
$v]->setPair( $from, $to );
586 }
elseif ( $action ==
'remove' ) {
587 $this->mTables[
$v]->removeArray( $pair );
601 $index = $title->getNamespace();
607 $text .= $this->
translate( $title->getText(), $variant );
623 if ( $variant ===
null ) {
627 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
628 $key =
$cache->makeKey(
'languageconverter',
'namespace-text', $index, $variant );
629 $nsVariantText =
$cache->get( $key );
630 if ( $nsVariantText !==
false ) {
635 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inLanguage( $variant );
636 if ( $nsConvMsg->exists() ) {
637 $nsVariantText = $nsConvMsg->plain();
642 if ( $nsVariantText ===
false ) {
643 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inContentLanguage();
644 if ( $nsConvMsg->exists() ) {
645 $nsVariantText = $this->
translate( $nsConvMsg->plain(), $variant );
649 if ( $nsVariantText ===
false ) {
651 $langObj = $this->mLangObj->factory( $variant );
652 $nsVariantText = $langObj->getFormattedNsText( $index );
655 $cache->set( $key, $nsVariantText, 60 );
680 return $this->
convertTo( $text, $variant );
698 $this->mConvRuleTitle =
false;
714 $length =
strlen( $text );
715 $shouldConvert = !$this->
guessVariant( $text, $variant );
718 $noScript =
'<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
719 $noStyle =
'<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
721 $noHtml =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
722 while ( $startPos < $length && $continue ) {
725 "/$noScript|$noStyle|$noHtml|-\{/",
734 $fragment =
substr( $text, $startPos );
735 $out .= $shouldConvert ? $this->
autoConvert( $fragment, $variant ) : $fragment;
743 $fragment =
substr( $text, $startPos, $pos - $startPos );
744 $out .= $shouldConvert ? $this->
autoConvert( $fragment, $variant ) : $fragment;
768 if ( $text[$startPos] !==
'-' || $text[$startPos + 1] !==
'{' ) {
769 throw new MWException( __METHOD__ .
': invalid input string' );
774 $warningDone =
false;
775 $length =
strlen( $text );
777 while ( $startPos < $length ) {
779 preg_match(
'/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
790 $inner .=
substr( $text, $startPos, $pos - $startPos );
798 if ( $depth >= $this->mMaxDepth ) {
800 if ( !$warningDone ) {
801 $inner .=
'<span class="error">' .
802 wfMessage(
'language-converter-depth-warning' )
803 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
817 $rule->parse( $variant );
819 return $rule->getDisplay();
821 throw new MWException( __METHOD__ .
': invalid regex match' );
826 if ( $startPos < $length ) {
827 $inner .=
substr( $text, $startPos );
830 return '-{' . $this->
autoConvert( $inner, $variant );
845 # If the article has already existed, there is no need to
846 # check it again, otherwise it may cause a fault.
847 if (
is_object( $nt ) && $nt->exists() ) {
852 $isredir =
$wgRequest->getText(
'redirect',
'yes' );
854 if ( $action ==
'edit' &&
$wgRequest->getBool(
'redlink' ) ) {
857 $linkconvert =
$wgRequest->getText(
'linkconvert',
'yes' );
864 if ( $disableLinkConversion ||
865 ( !$ignoreOtherCond &&
868 || $action ==
'submit'
869 || $linkconvert ==
'no' ) ) ) {
874 $ns = $nt->getNamespace();
884 foreach ( $variants as $v ) {
886 $varnt = Title::newFromText( $v, $ns );
888 $linkBatch->addObj( $varnt );
895 $linkBatch->execute();
897 foreach (
$titles as $varnt ) {
898 if ( $varnt->getArticleID() > 0 ) {
900 $link = $varnt->getText();
914 return '!' . $variant;
939 $class = static::class;
940 throw new MWException(
"Must implement loadDefaultTables() method in class $class" );
951 if ( $this->mTablesLoaded ) {
955 $this->mTablesLoaded =
true;
956 $this->mTables =
false;
958 $cacheKey =
$cache->makeKey(
'conversiontables', $this->mMainLanguageCode );
960 $this->mTables =
$cache->get( $cacheKey );
962 if ( !$this->mTables || !
array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
967 foreach ( $this->mVariants as $var ) {
969 $this->mTables[
$var]->mergeArray( $cached );
973 $this->mTables[self::CACHE_VERSION_KEY] =
true;
975 $cache->set( $cacheKey, $this->mTables, 43200 );
993 if ( $this->mTables ) {
994 unset( $this->mTables );
997 $this->mTablesLoaded =
false;
1021 static $parsed = [];
1023 $key =
'Conversiontable/' .
$code;
1031 $parsed[$key] =
true;
1033 if ( $subpage ===
'' ) {
1034 $txt = MessageCache::singleton()->getMsgFromNamespace( $key,
$code );
1037 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
1038 if ( $title && $title->exists() ) {
1050 # Nothing to parse if there's no text
1051 if ( $txt ===
false || $txt ===
null || $txt ===
'' ) {
1057 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
1059 $subs = StringUtils::explode(
'[[', $txt );
1061 foreach ( $subs as $sub ) {
1062 $link = explode(
']]', $sub, 2 );
1063 if ( count(
$link ) != 2 ) {
1066 $b = explode(
'|',
$link[0], 2 );
1067 $b = explode(
'/',
trim( $b[0] ), 3 );
1068 if ( count( $b ) == 3 ) {
1074 if ( $b[0] == $linkhead && $b[1] ==
$code ) {
1080 $blocks = StringUtils::explode(
'-{', $txt );
1083 foreach ( $blocks as $block ) {
1089 $mappings = explode(
'}-', $block, 2 )[0];
1090 $stripped =
str_replace( [
"'",
'"',
'*',
'#' ],
'', $mappings );
1091 $table = StringUtils::explode(
';', $stripped );
1092 foreach ( $table as
$t ) {
1093 $m = explode(
'=>',
$t, 3 );
1094 if ( count( $m ) != 2 ) {
1098 $tt = explode(
'//', $m[1], 2 );
1105 foreach ( $sublinks as
$link ) {
1111 if ( $this->mUcfirst ) {
1112 foreach (
$ret as $k => $v ) {
1113 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1128 # don't mark if already marked
1129 if (
strpos( $text,
'-{' ) ||
strpos( $text,
'}-' ) ) {
1133 $ret =
"-{R|$text}-";
1156 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1157 $title = $titleobj->getDBkey();
1158 $t = explode(
'/', $title, 3 );
1160 if ( $c > 1 &&
$t[0] ==
'Conversiontable' ) {
1173 if (
is_null( $this->mVarSeparatorPattern ) ) {
1185 $expandedVariants = [];
1186 foreach ( $this->mVariants as $variant ) {
1187 $expandedVariants[ $variant ] = 1;
1189 $expandedVariants[ LanguageCode::bcp47( $variant ) ] = 1;
1192 foreach ( LanguageCode::getDeprecatedCodeMapping() as $old => $new ) {
1193 if (
isset( $expandedVariants[ $new ] ) ) {
1194 $expandedVariants[ $old ] = 1;
1199 foreach ( $expandedVariants as $variant => $ignore ) {
1201 $pat .= $variant .
'\s*:|';
1203 $pat .=
'[^;]*?=>\s*' . $variant .
'\s*:|';
1206 $this->mVarSeparatorPattern =
$pat;
1208 return $this->mVarSeparatorPattern;
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
$wgDefaultLanguageVariant
Default variant code, if false, the default will be the language code.
$wgDisableLangConversion
Whether to enable language variant conversion.
$wgDisabledVariants
Disabled variants array of language variant conversion.
$wgLanguageConverterCacheType
The cache type for storing language conversion tables, which are used when parsing certain text and i...
$wgDisableTitleConversion
Whether to enable language variant conversion for links.
if(! $wgDBerrorLogTZ) $wgRequest
Parser for rules of language conversion, parse rules in -{ }- tag.
Base class for language conversion.
getPreferredVariant()
Get preferred language variant.
convertTitle( $title)
Auto convert a Title object to a readable string in the preferred variant.
validateVariant( $variant=null)
Validate the variant and return an appropriate strict internal variant code if one exists.
getDefaultVariant()
Get default variant.
recursiveConvertTopLevel( $text, $variant, $depth=0)
Recursively convert text on the outside.
loadTables( $fromCache=true)
Load conversion tables either from the cache or the disk.
getHeaderVariant()
Determine the language variant from the Accept-Language header.
static array $languagesWithVariants
languages supporting variants
autoConvert( $text, $toVariant=false)
Dictionary-based conversion.
recursiveConvertRule( $text, $variant, &$startPos, $depth=0)
Recursively convert text on the inside.
__construct(Language $langobj, $maincode, $variants=[], $variantfallbacks=[], $flags=[], $manualLevel=[])
parseCachedTable( $code, $subpage='', $recursive=true)
Parse the conversion table stored in the cache.
getVarSeparatorPattern()
Get the cached separator pattern for ConverterRule::parseRules()
convertNamespace( $index, $variant=null)
Get the namespace display name in the preferred variant.
getExtraHashOptions()
Returns language specific hash options.
getVariantFallbacks( $variant)
In case some variant is not defined in the markup, we need to have some fallback.
updateConversionTable(Title $titleobj)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
markNoConversion( $text, $noParse=false)
Enclose a string with the "no conversion" tag.
applyManualConv( $convRule)
Apply manual conversion rules.
translate( $text, $variant)
Translate a string to a variant.
getVariants()
Get all valid variants.
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
convert( $text)
Convert text to different variants of a language.
postLoadTables()
Hook for post processing after conversion tables are loaded.
getURLVariant()
Get the variant specified in the URL.
ReplacementArray[] $mTables
@phan-var array<string,ReplacementArray>
loadDefaultTables()
Load default conversion tables.
autoConvertToAllVariants( $text)
Call translate() to convert text to all valid variants.
guessVariant( $text, $variant)
Guess if a text is written in a variant.
getUserVariant()
Determine if the user has a variant set.
convertTo( $text, $variant)
Same as convert() except a extra parameter to custom variant.
convertCategoryKey( $key)
Convert the sorting key for category links.
getConvRuleTitle()
Get the title produced by the conversion rule.
reloadTables()
Reload the conversion tables.
Internationalisation code.
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Wrapper around strtr() that holds replacements.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Represents a title within MediaWiki.
this hook is for auditing only $req
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
usually copyright or history_copyright This message must be in HTML not wikitext & $link
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
const CONTENT_MODEL_WIKITEXT
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
switch( $options['output']) $languages