89 public function __construct( $langobj, $maincode, $variants = [],
90 $variantfallbacks = [],
$flags = [],
93 $this->mLangObj = $langobj;
94 $this->mMainLanguageCode = $maincode;
95 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
96 $this->mVariantFallbacks = $variantfallbacks;
98 $this->mCacheKey =
wfMemcKey(
'conversiontables', $maincode );
112 $this->mFlags = array_merge( $defaultflags,
$flags );
113 foreach ( $this->mVariants
as $v ) {
114 if ( array_key_exists( $v, $manualLevel ) ) {
115 $this->mManualLevel[$v] = $manualLevel[$v];
117 $this->mManualLevel[$v] =
'bidirectional';
119 $this->mFlags[$v] = $v;
145 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
146 return $this->mVariantFallbacks[$variant];
168 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !
$req ) {
174 if ( $wgDefaultLanguageVariant && !
$req ) {
202 if ( $wgDefaultLanguageVariant && !
$req ) {
218 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
232 if ( $this->mURLVariant ) {
237 $ret = $wgRequest->getText(
'variant' );
240 $ret = $wgRequest->getVal(
'uselang' );
265 if ( !$wgUser->isSafeToLoad() ) {
268 if ( $wgUser->isLoggedIn() ) {
269 if ( $this->mMainLanguageCode == $wgContLang->getCode() ) {
270 $ret = $wgUser->getOption(
'variant' );
272 $ret = $wgUser->getOption(
'variant-' . $this->mMainLanguageCode );
277 $ret = $wgUser->getOption(
'language' );
292 if ( $this->mHeaderVariant ) {
298 $languages = array_keys( $wgRequest->getAcceptLang() );
303 $fallbackLanguages = [];
306 if ( $this->mHeaderVariant ) {
314 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
315 $fallbackLanguages[] = $fallbacks;
316 } elseif ( is_array( $fallbacks ) ) {
318 array_merge( $fallbackLanguages, $fallbacks );
322 if ( !$this->mHeaderVariant ) {
324 $fallback_languages = array_unique( $fallbackLanguages );
325 foreach ( $fallback_languages
as $language ) {
327 if ( $this->mHeaderVariant ) {
369 $htmlfix =
'|<[^>\004]++(?=\004$)|^[^<>]*+>';
376 $codefix =
'<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
378 $scriptfix =
'<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
380 $prefix =
'<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
383 $htmlFullTag =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
385 $reg =
'/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
386 '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix .
'|\004$/s';
392 $text = str_replace(
"\000",
'', $text );
394 $markupMatches = null;
395 $elementMatches = null;
399 while ( $startPos < strlen( $text ) ) {
400 if ( preg_match( $reg, $text .
"\004", $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
401 $elementPos = $markupMatches[0][1];
402 $element = $markupMatches[0][0];
403 if ( $element ===
"\004" ) {
405 $elementPos = strlen( $text );
413 $log = LoggerFactory::getInstance(
'languageconverter' );
414 $log->error(
"Hit pcre.backtrack_limit in " . __METHOD__
415 .
". Disabling language conversion for this page.",
417 "method" => __METHOD__,
418 "variant" => $toVariant,
419 "startOfText" => substr( $text, 0, 500 )
425 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) .
"\000";
428 $startPos = $elementPos + strlen( $element );
432 && preg_match(
'/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
436 foreach ( [
'title',
'alt' ]
as $attrName ) {
437 if ( !isset( $attrs[$attrName] ) ) {
440 $attr = $attrs[$attrName];
442 if ( !strpos( $attr,
'://' ) ) {
447 $attr = preg_replace(
'/<[^>]+>/',
'', $attr );
448 if ( $attr !== $attrs[$attrName] ) {
449 $attrs[$attrName] = $attr;
458 $literalBlob .= $element .
"\000";
462 $translatedBlob = $this->
translate( $sourceBlob, $toVariant );
468 while ( $translatedIter->valid() && $literalIter->valid() ) {
469 $output .= $translatedIter->current();
470 $output .= $literalIter->current();
471 $translatedIter->next();
472 $literalIter->next();
490 if ( trim( $text ) ) {
492 $text = $this->mTables[$variant]->replace( $text );
507 foreach ( $this->mVariants
as $variant ) {
524 $newConvRuleTitle = $convRule->getTitle();
525 if ( $newConvRuleTitle ) {
527 $this->mConvRuleTitle = $newConvRuleTitle;
531 $convTable = $convRule->getConvTable();
532 $action = $convRule->getRulesAction();
533 foreach ( $convTable
as $variant => $pair ) {
538 if ( $action ==
'add' ) {
540 foreach ( $pair
as $from => $to ) {
541 $this->mTables[$variant]->setPair(
$from, $to );
543 } elseif ( $action ==
'remove' ) {
544 $this->mTables[$variant]->removeArray( $pair );
558 $index =
$title->getNamespace();
580 if ( $variant === null ) {
584 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
585 $key =
$cache->makeKey(
'languageconverter',
'namespace-text', $index, $variant );
586 $nsVariantText =
$cache->get( $key );
587 if ( $nsVariantText !==
false ) {
588 return $nsVariantText;
592 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inLanguage( $variant );
593 if ( $nsConvMsg->exists() ) {
594 $nsVariantText = $nsConvMsg->plain();
599 if ( $nsVariantText ===
false ) {
600 $nsConvMsg =
wfMessage(
'conversion-ns' . $index )->inContentLanguage();
601 if ( $nsConvMsg->exists() ) {
602 $nsVariantText = $this->
translate( $nsConvMsg->plain(), $variant );
606 if ( $nsVariantText ===
false ) {
608 $langObj = $this->mLangObj->factory( $variant );
609 $nsVariantText = $langObj->getFormattedNsText( $index );
612 $cache->set( $key, $nsVariantText, 60 );
614 return $nsVariantText;
633 return $this->
convertTo( $text, $variant );
645 if ( $wgDisableLangConversion ) {
649 $this->mConvRuleTitle =
false;
665 $length = strlen( $text );
666 $shouldConvert = !$this->
guessVariant( $text, $variant );
669 $noScript =
'<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
670 $noStyle =
'<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
671 $noHtml =
'<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
672 while ( $startPos < $length && $continue ) {
673 $continue = preg_match(
675 "/$noScript|$noStyle|$noHtml|-\{/",
684 $fragment = substr( $text, $startPos );
685 $out .= $shouldConvert ? $this->
autoConvert( $fragment, $variant ) : $fragment;
693 $fragment = substr( $text, $startPos, $pos - $startPos );
694 $out .= $shouldConvert ? $this->
autoConvert( $fragment, $variant ) : $fragment;
718 if ( $text[$startPos] !==
'-' || $text[$startPos + 1] !==
'{' ) {
719 throw new MWException( __METHOD__ .
': invalid input string' );
724 $warningDone =
false;
725 $length = strlen( $text );
727 while ( $startPos < $length ) {
729 preg_match(
'/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
740 $inner .= substr( $text, $startPos, $pos - $startPos );
748 if ( $depth >= $this->mMaxDepth ) {
750 if ( !$warningDone ) {
751 $inner .=
'<span class="error">' .
752 wfMessage(
'language-converter-depth-warning' )
753 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
767 $rule->parse( $variant );
769 return $rule->getDisplay();
771 throw new MWException( __METHOD__ .
': invalid regex match' );
776 if ( $startPos < $length ) {
777 $inner .= substr( $text, $startPos );
780 return '-{' . $this->
autoConvert( $inner, $variant );
795 # If the article has already existed, there is no need to
796 # check it again, otherwise it may cause a fault.
797 if ( is_object( $nt ) && $nt->exists() ) {
802 $isredir = $wgRequest->getText(
'redirect',
'yes' );
803 $action = $wgRequest->getText(
'action' );
804 if ( $action ==
'edit' && $wgRequest->getBool(
'redlink' ) ) {
807 $linkconvert = $wgRequest->getText(
'linkconvert',
'yes' );
808 $disableLinkConversion = $wgDisableLangConversion
814 if ( $disableLinkConversion ||
815 ( !$ignoreOtherCond &&
818 || $action ==
'submit'
819 || $linkconvert ==
'no' ) ) ) {
823 if ( is_object( $nt ) ) {
824 $ns = $nt->getNamespace();
834 foreach ( $variants
as $v ) {
837 if ( !is_null( $varnt ) ) {
838 $linkBatch->addObj( $varnt );
845 $linkBatch->execute();
848 if ( $varnt->getArticleID() > 0 ) {
850 $link = $varnt->getText();
864 return '!' . $variant;
889 $name = get_class( $this );
891 throw new MWException(
"Must implement loadDefaultTables() method in class $name" );
902 if ( $this->mTablesLoaded ) {
906 $this->mTablesLoaded =
true;
907 $this->mTables =
false;
911 $this->mTables =
$cache->get( $this->mCacheKey );
914 if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
920 foreach ( $this->mVariants
as $var ) {
922 $this->mTables[$var]->mergeArray( $cached );
926 $this->mTables[self::CACHE_VERSION_KEY] =
true;
928 $cache->set( $this->mCacheKey, $this->mTables, 43200 );
945 if ( $this->mTables ) {
946 unset( $this->mTables );
949 $this->mTablesLoaded =
false;
975 $key =
'Conversiontable/' .
$code;
977 $key .=
'/' . $subpage;
979 if ( array_key_exists( $key, $parsed ) ) {
983 $parsed[$key] =
true;
985 if ( $subpage ===
'' ) {
994 $txt = $revision->getContent(
Revision::RAW )->getNativeData();
1002 # Nothing to parse if there's no text
1003 if ( $txt ===
false || $txt === null || $txt ===
'' ) {
1009 $linkhead = $this->mLangObj->getNsText(
NS_MEDIAWIKI ) .
1013 foreach ( $subs
as $sub ) {
1014 $link = explode(
']]', $sub, 2 );
1015 if ( count(
$link ) != 2 ) {
1018 $b = explode(
'|',
$link[0], 2 );
1019 $b = explode(
'/', trim( $b[0] ), 3 );
1020 if ( count( $b ) == 3 ) {
1026 if ( $b[0] == $linkhead && $b[1] ==
$code ) {
1027 $sublinks[] = $sublink;
1035 foreach ( $blocks
as $block ) {
1041 $mappings = explode(
'}-', $block, 2 )[0];
1042 $stripped = str_replace( [
"'",
'"',
'*',
'#' ],
'', $mappings );
1044 foreach ( $table
as $t ) {
1045 $m = explode(
'=>', $t, 3 );
1046 if ( count( $m ) != 2 ) {
1050 $tt = explode(
'//', $m[1], 2 );
1051 $ret[trim( $m[0] )] = trim( $tt[0] );
1057 foreach ( $sublinks
as $link ) {
1063 if ( $this->mUcfirst ) {
1064 foreach (
$ret as $k => $v ) {
1065 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1080 # don't mark if already marked
1081 if ( strpos( $text,
'-{' ) || strpos( $text,
'}-' ) ) {
1085 $ret =
"-{R|$text}-";
1112 if ( $c > 1 &&
$t[0] ==
'Conversiontable' ) {
1125 if ( is_null( $this->mVarSeparatorPattern ) ) {
1138 foreach ( $this->mVariants
as $variant ) {
1140 $pat .= $variant .
'\s*:|';
1142 $pat .=
'[^;]*?=>\s*' . $variant .
'\s*:|';
1145 $this->mVarSeparatorPattern = $pat;
convertCategoryKey($key)
Convert the sorting key for category links.
updateConversionTable(Title $titleobj)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
static decodeTagAttributes($text)
Return an associative array of attribute names and values from a partial tag string.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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
the array() calling protocol came about after MediaWiki 1.4rc1.
const CONTENT_MODEL_WIKITEXT
__construct($langobj, $maincode, $variants=[], $variantfallbacks=[], $flags=[], $manualLevel=[])
Constructor.
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
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
convertTo($text, $variant)
Same as convert() except a extra parameter to custom variant.
if(!$wgDBerrorLogTZ) $wgRequest
getVarSeparatorPattern()
Get the cached separator pattern for ConverterRule::parseRules()
static getInstance($id)
Get a cached instance of the specified type of cache object.
wfProfileIn($functionname)
Begin profiling of a function.
recursiveConvertTopLevel($text, $variant, $depth=0)
Recursively convert text on the outside.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Base class for language conversion.
getExtraHashOptions()
Returns language specific hash options.
markNoConversion($text, $noParse=false)
Enclose a string with the "no conversion" tag.
parseCachedTable($code, $subpage= '', $recursive=true)
Parse the conversion table stored in the cache.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
loadTables($fromCache=true)
Load conversion tables either from the cache or the disk.
when a variable name is used in a it is silently declared as a new local masking the global
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
static fetchLanguageNames($inLanguage=null, $include= 'mw')
Get an array of language names, indexed by code.
postLoadTables()
Hook for post processing after conversion tables are loaded.
wfProfileOut($functionname= 'missing')
Stop profiling of a function.
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Class representing a list of titles The execute() method checks them all for existence and adds them ...
getVariantFallbacks($variant)
In case some variant is not defined in the markup, we need to have some fallback. ...
getDBkey()
Get the main part with underscores.
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 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 unsetoffset-wrap String Wrap the message in html(usually something like"<
switch($options['output']) $languages
getURLVariant()
Get the variant specified in the URL.
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
recursiveConvertRule($text, $variant, &$startPos, $depth=0)
Recursively convert text on the inside.
reloadTables()
Reload the conversion tables.
Parser for rules of language conversion , parse rules in -{ }- tag.
getUserVariant()
Determine if the user has a variant set.
translate($text, $variant)
Translate a string to a variant.
$wgLanguageConverterCacheType
The cache type for storing language conversion tables, which are used when parsing certain text and i...
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
$wgDisableTitleConversion
Whether to enable language variant conversion for links.
namespace and then decline to actually register it file or subcat img or subcat $title
$wgDisabledVariants
Disabled variants array of language variant conversion.
getVariants()
Get all valid variants.
getNamespace()
Get the namespace index, i.e.
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
$wgDisableLangConversion
Whether to enable language variant conversion.
$wgDefaultLanguageVariant
Default variant code, if false, the default will be the language code.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
this hook is for auditing only $req
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
getHeaderVariant()
Determine the language variant from the Accept-Language header.
guessVariant($text, $variant)
Guess if a text is written in a variant.
string $mCacheKey
Memcached key name.
getDefaultVariant()
Get default variant.
applyManualConv($convRule)
Apply manual conversion rules.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
autoConvert($text, $toVariant=false)
Dictionary-based conversion.
getConvRuleTitle()
Get the title produced by the conversion rule.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
convert($text)
Convert text to different variants of a language.
wfMemcKey()
Make a cache key for the local wiki.
static explode($separator, $subject)
Workalike for explode() with limited memory usage.
validateVariant($variant=null)
Validate the variant.
convertNamespace($index, $variant=null)
Get the namespace display name in the preferred variant.
static array $languagesWithVariants
languages supporting variants
getPreferredVariant()
Get preferred language variant.
autoConvertToAllVariants($text)
Call translate() to convert text to all valid variants.
loadDefaultTables()
Load default conversion tables.
static singleton()
Get the signleton instance of this class.
convertTitle($title)
Auto convert a Title object to a readable string in the preferred variant.
Allows to change the fields on the form that will be generated $name