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
;
24 * Base class for language conversion.
27 * @author Zhengzhu Feng <zhengzhu@gmail.com>
28 * @author fdcn <fdcn64@gmail.com>
29 * @author shinjiman <shinjiman@gmail.com>
30 * @author PhiLiP <philip.npc@gmail.com>
32 class LanguageConverter
{
34 * languages supporting variants
38 static public $languagesWithVariants = [
50 public $mMainLanguageCode;
56 public $mVariantFallbacks;
57 public $mVariantNames;
58 public $mTablesLoaded = false;
60 // 'bidirectional' 'unidirectional' 'disable' for each variant
64 * @var string Memcached key name
70 public $mDescCodeSep = ':', $mDescVarSep = ';';
71 public $mUcfirst = false;
72 public $mConvRuleTitle = false;
75 public $mHeaderVariant;
76 public $mMaxDepth = 10;
77 public $mVarSeparatorPattern;
79 const CACHE_VERSION_KEY
= 'VERSION 7';
82 * @param Language $langobj
83 * @param string $maincode The main language code of this language
84 * @param string[] $variants The supported variants of this language
85 * @param array $variantfallbacks The fallback language of each variant
86 * @param array $flags Defining the custom strings that maps to the flags
87 * @param array $manualLevel Limit for supported variants
89 public function __construct( $langobj, $maincode, $variants = [],
90 $variantfallbacks = [], $flags = [],
92 global $wgDisabledVariants;
93 $this->mLangObj
= $langobj;
94 $this->mMainLanguageCode
= $maincode;
95 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
96 $this->mVariantFallbacks
= $variantfallbacks;
97 $this->mVariantNames
= Language
::fetchLanguageNames();
98 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
100 // 'S' show converted text
101 // '+' add rules for alltext
102 // 'E' the gave flags is error
103 // these flags above are reserved for program
104 'A' => 'A', // add rule for convert code (all text convert)
105 'T' => 'T', // title convert
106 'R' => 'R', // raw content
107 'D' => 'D', // convert description (subclass implement)
108 '-' => '-', // remove convert (not implement)
109 'H' => 'H', // add rule for convert code (but no display in placed code)
110 'N' => 'N', // current variant name
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;
124 * Get all valid variants.
125 * Call this instead of using $this->mVariants directly.
127 * @return string[] Contains all valid variants
129 public function getVariants() {
130 return $this->mVariants
;
134 * In case some variant is not defined in the markup, we need
135 * to have some fallback. For example, in zh, normally people
136 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
137 * when zh-sg is preferred but not defined, we will pick zh-hans
138 * in this case. Right now this is only used by zh.
140 * @param string $variant The language code of the variant
141 * @return string|array The code of the fallback language or the
142 * main code if there is no fallback
144 public function getVariantFallbacks( $variant ) {
145 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
146 return $this->mVariantFallbacks
[$variant];
148 return $this->mMainLanguageCode
;
152 * Get the title produced by the conversion rule.
153 * @return string The converted title text
155 public function getConvRuleTitle() {
156 return $this->mConvRuleTitle
;
160 * Get preferred language variant.
161 * @return string The preferred language code
163 public function getPreferredVariant() {
164 global $wgDefaultLanguageVariant, $wgUser;
166 $req = $this->getURLVariant();
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 $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, false 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, false otherwise.
252 protected function getUserVariant() {
253 global $wgUser, $wgContLang;
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() ) {
269 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
270 $ret = $wgUser->getOption( 'variant' );
272 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
275 // figure out user lang without constructing wgLang to avoid
276 // infinite recursion
277 $ret = $wgUser->getOption( 'language' );
280 $this->mUserVariant
= $this->validateVariant( $ret );
281 return $this->mUserVariant
;
285 * Determine the language variant from the Accept-Language header.
287 * @return mixed Variant if one found, false otherwise.
289 protected function getHeaderVariant() {
292 if ( $this->mHeaderVariant
) {
293 return $this->mHeaderVariant
;
296 // see if some supported language variant is set in the
298 $languages = array_keys( $wgRequest->getAcceptLang() );
299 if ( empty( $languages ) ) {
303 $fallbackLanguages = [];
304 foreach ( $languages as $language ) {
305 $this->mHeaderVariant
= $this->validateVariant( $language );
306 if ( $this->mHeaderVariant
) {
310 // To see if there are fallbacks of current language.
311 // We record these fallback variants, and process
313 $fallbacks = $this->getVariantFallbacks( $language );
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
) {
323 // process fallback languages now
324 $fallback_languages = array_unique( $fallbackLanguages );
325 foreach ( $fallback_languages as $language ) {
326 $this->mHeaderVariant
= $this->validateVariant( $language );
327 if ( $this->mHeaderVariant
) {
333 return $this->mHeaderVariant
;
337 * Dictionary-based conversion.
338 * This function would not parse the conversion rules.
339 * If you want to parse rules, try to use convert() or
342 * @param string $text The text to be converted
343 * @param bool|string $toVariant The target language code
344 * @return string The converted text
346 public function autoConvert( $text, $toVariant = false ) {
351 $toVariant = $this->getPreferredVariant();
357 if ( $this->guessVariant( $text, $toVariant ) ) {
361 /* we convert everything except:
362 * 1. HTML markups (anything between < and >)
364 * 3. placeholders created by the parser
366 $marker = '|' . Parser
::MARKER_PREFIX
. '[\-a-zA-Z0-9]+';
368 // this one is needed when the text is inside an HTML markup
369 $htmlfix = '|<[^>]+$|^[^<>]*>';
371 // disable convert to variants between <code> tags
372 $codefix = '<code>.+?<\/code>|';
373 // disable conversion of <script> tags
374 $scriptfix = '<script.*?>.*?<\/script>|';
375 // disable conversion of <pre> tags
376 $prefix = '<pre.*?>.*?<\/pre>|';
378 $reg = '/' . $codefix . $scriptfix . $prefix .
379 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
384 // Guard against delimiter nulls in the input
385 // (should never happen: see T159174)
386 $text = str_replace( "\000", '', $text );
388 $markupMatches = null;
389 $elementMatches = null;
390 while ( $startPos < strlen( $text ) ) {
391 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
392 $elementPos = $markupMatches[0][1];
393 $element = $markupMatches[0][0];
395 $elementPos = strlen( $text );
399 // Queue the part before the markup for translation in a batch
400 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
402 // Advance to the next position
403 $startPos = $elementPos +
strlen( $element );
405 // Translate any alt or title attributes inside the matched element
407 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
409 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
411 foreach ( [ 'title', 'alt' ] as $attrName ) {
412 if ( !isset( $attrs[$attrName] ) ) {
415 $attr = $attrs[$attrName];
416 // Don't convert URLs
417 if ( !strpos( $attr, '://' ) ) {
418 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
421 if ( $attr !== $attrs[$attrName] ) {
422 $attrs[$attrName] = $attr;
427 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
431 $literalBlob .= $element . "\000";
434 // Do the main translation batch
435 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
437 // Put the output back together
438 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
439 $literalIter = StringUtils
::explode( "\000", $literalBlob );
441 while ( $translatedIter->valid() && $literalIter->valid() ) {
442 $output .= $translatedIter->current();
443 $output .= $literalIter->current();
444 $translatedIter->next();
445 $literalIter->next();
452 * Translate a string to a variant.
453 * Doesn't parse rules or do any of that other stuff, for that use
454 * convert() or convertTo().
456 * @param string $text Text to convert
457 * @param string $variant Variant language code
458 * @return string Translated text
460 public function translate( $text, $variant ) {
461 // If $text is empty or only includes spaces, do nothing
462 // Otherwise translate it
463 if ( trim( $text ) ) {
465 $text = $this->mTables
[$variant]->replace( $text );
471 * Call translate() to convert text to all valid variants.
473 * @param string $text The text to be converted
474 * @return array Variant => converted text
476 public function autoConvertToAllVariants( $text ) {
480 foreach ( $this->mVariants
as $variant ) {
481 $ret[$variant] = $this->translate( $text, $variant );
488 * Apply manual conversion rules.
490 * @param ConverterRule $convRule
492 protected function applyManualConv( $convRule ) {
493 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
495 // T26072: $mConvRuleTitle was overwritten by other manual
496 // rule(s) not for title, this breaks the title conversion.
497 $newConvRuleTitle = $convRule->getTitle();
498 if ( $newConvRuleTitle ) {
499 // So I add an empty check for getTitle()
500 $this->mConvRuleTitle
= $newConvRuleTitle;
503 // merge/remove manual conversion rules to/from global table
504 $convTable = $convRule->getConvTable();
505 $action = $convRule->getRulesAction();
506 foreach ( $convTable as $variant => $pair ) {
507 if ( !$this->validateVariant( $variant ) ) {
511 if ( $action == 'add' ) {
512 // More efficient than array_merge(), about 2.5 times.
513 foreach ( $pair as $from => $to ) {
514 $this->mTables
[$variant]->setPair( $from, $to );
516 } elseif ( $action == 'remove' ) {
517 $this->mTables
[$variant]->removeArray( $pair );
523 * Auto convert a Title object to a readable string in the
526 * @param Title $title A object of Title
527 * @return string Converted title text
529 public function convertTitle( $title ) {
530 $variant = $this->getPreferredVariant();
531 $index = $title->getNamespace();
532 if ( $index !== NS_MAIN
) {
533 $text = $this->convertNamespace( $index, $variant ) . ':';
537 $text .= $this->translate( $title->getText(), $variant );
542 * Get the namespace display name in the preferred variant.
544 * @param int $index Namespace id
545 * @param string|null $variant Variant code or null for preferred variant
546 * @return string Namespace name for display
548 public function convertNamespace( $index, $variant = null ) {
549 if ( $index === NS_MAIN
) {
553 if ( $variant === null ) {
554 $variant = $this->getPreferredVariant();
557 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
558 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
559 $nsVariantText = $cache->get( $key );
560 if ( $nsVariantText !== false ) {
561 return $nsVariantText;
564 // First check if a message gives a converted name in the target variant.
565 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
566 if ( $nsConvMsg->exists() ) {
567 $nsVariantText = $nsConvMsg->plain();
570 // Then check if a message gives a converted name in content language
571 // which needs extra translation to the target variant.
572 if ( $nsVariantText === false ) {
573 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
574 if ( $nsConvMsg->exists() ) {
575 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
579 if ( $nsVariantText === false ) {
580 // No message exists, retrieve it from the target variant's namespace names.
581 $langObj = $this->mLangObj
->factory( $variant );
582 $nsVariantText = $langObj->getFormattedNsText( $index );
585 $cache->set( $key, $nsVariantText, 60 );
587 return $nsVariantText;
591 * Convert text to different variants of a language. The automatic
592 * conversion is done in autoConvert(). Here we parse the text
593 * marked with -{}-, which specifies special conversions of the
594 * text that can not be accomplished in autoConvert().
596 * Syntax of the markup:
597 * -{code1:text1;code2:text2;...}- or
598 * -{flags|code1:text1;code2:text2;...}- or
599 * -{text}- in which case no conversion should take place for text
601 * @param string $text Text to be converted
602 * @return string Converted text
604 public function convert( $text ) {
605 $variant = $this->getPreferredVariant();
606 return $this->convertTo( $text, $variant );
610 * Same as convert() except a extra parameter to custom variant.
612 * @param string $text Text to be converted
613 * @param string $variant The target variant code
614 * @return string Converted text
616 public function convertTo( $text, $variant ) {
617 global $wgDisableLangConversion;
618 if ( $wgDisableLangConversion ) {
621 // Reset converter state for a new converter run.
622 $this->mConvRuleTitle
= false;
623 return $this->recursiveConvertTopLevel( $text, $variant );
627 * Recursively convert text on the outside. Allow to use nested
628 * markups to custom rules.
630 * @param string $text Text to be converted
631 * @param string $variant The target variant code
632 * @param int $depth Depth of recursion
633 * @return string Converted text
635 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
638 $length = strlen( $text );
639 $shouldConvert = !$this->guessVariant( $text, $variant );
641 while ( $startPos < $length ) {
642 $pos = strpos( $text, '-{', $startPos );
644 if ( $pos === false ) {
645 // No more markup, append final segment
646 $fragment = substr( $text, $startPos );
647 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
652 // Append initial segment
653 $fragment = substr( $text, $startPos, $pos - $startPos );
654 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
659 // Do recursive conversion
660 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
667 * Recursively convert text on the inside.
669 * @param string $text Text to be converted
670 * @param string $variant The target variant code
671 * @param int $startPos
672 * @param int $depth Depth of recursion
674 * @throws MWException
675 * @return string Converted text
677 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
678 // Quick sanity check (no function calls)
679 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
680 throw new MWException( __METHOD__
. ': invalid input string' );
685 $warningDone = false;
686 $length = strlen( $text );
688 while ( $startPos < $length ) {
690 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
700 // Append initial segment
701 $inner .= substr( $text, $startPos, $pos - $startPos );
709 if ( $depth >= $this->mMaxDepth
) {
711 if ( !$warningDone ) {
712 $inner .= '<span class="error">' .
713 wfMessage( 'language-converter-depth-warning' )
714 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
721 // Recursively parse another rule
722 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
727 $rule = new ConverterRule( $inner, $this );
728 $rule->parse( $variant );
729 $this->applyManualConv( $rule );
730 return $rule->getDisplay();
732 throw new MWException( __METHOD__
. ': invalid regex match' );
737 if ( $startPos < $length ) {
738 $inner .= substr( $text, $startPos );
741 return '-{' . $this->autoConvert( $inner, $variant );
745 * If a language supports multiple variants, it is possible that
746 * non-existing link in one variant actually exists in another variant.
747 * This function tries to find it. See e.g. LanguageZh.php
748 * The input parameters may be modified upon return
750 * @param string &$link The name of the link
751 * @param Title &$nt The title object of the link
752 * @param bool $ignoreOtherCond To disable other conditions when
753 * we need to transclude a template or update a category's link
755 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
756 # If the article has already existed, there is no need to
757 # check it again, otherwise it may cause a fault.
758 if ( is_object( $nt ) && $nt->exists() ) {
762 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
763 $isredir = $wgRequest->getText( 'redirect', 'yes' );
764 $action = $wgRequest->getText( 'action' );
765 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
768 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
769 $disableLinkConversion = $wgDisableLangConversion
770 ||
$wgDisableTitleConversion;
771 $linkBatch = new LinkBatch();
775 if ( $disableLinkConversion ||
776 ( !$ignoreOtherCond &&
779 ||
$action == 'submit'
780 ||
$linkconvert == 'no' ) ) ) {
784 if ( is_object( $nt ) ) {
785 $ns = $nt->getNamespace();
788 $variants = $this->autoConvertToAllVariants( $link );
789 if ( !$variants ) { // give up
795 foreach ( $variants as $v ) {
797 $varnt = Title
::newFromText( $v, $ns );
798 if ( !is_null( $varnt ) ) {
799 $linkBatch->addObj( $varnt );
805 // fetch all variants in single query
806 $linkBatch->execute();
808 foreach ( $titles as $varnt ) {
809 if ( $varnt->getArticleID() > 0 ) {
811 $link = $varnt->getText();
818 * Returns language specific hash options.
822 public function getExtraHashOptions() {
823 $variant = $this->getPreferredVariant();
825 return '!' . $variant;
829 * Guess if a text is written in a variant. This should be implemented in subclasses.
831 * @param string $text The text to be checked
832 * @param string $variant Language code of the variant to be checked for
833 * @return bool True if $text appears to be written in $variant, false if not
835 * @author Nikola Smolenski <smolensk@eunet.rs>
838 public function guessVariant( $text, $variant ) {
843 * Load default conversion tables.
844 * This method must be implemented in derived class.
847 * @throws MWException
849 function loadDefaultTables() {
850 $class = static::class;
851 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
855 * Load conversion tables either from the cache or the disk.
857 * @param bool $fromCache Load from memcached? Defaults to true.
859 function loadTables( $fromCache = true ) {
860 global $wgLanguageConverterCacheType;
862 if ( $this->mTablesLoaded
) {
866 $this->mTablesLoaded
= true;
867 $this->mTables
= false;
868 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
870 $this->mTables
= $cache->get( $this->mCacheKey
);
872 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
873 // not in cache, or we need a fresh reload.
874 // We will first load the default tables
875 // then update them using things in MediaWiki:Conversiontable/*
876 $this->loadDefaultTables();
877 foreach ( $this->mVariants
as $var ) {
878 $cached = $this->parseCachedTable( $var );
879 $this->mTables
[$var]->mergeArray( $cached );
882 $this->postLoadTables();
883 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
885 $cache->set( $this->mCacheKey
, $this->mTables
, 43200 );
890 * Hook for post processing after conversion tables are loaded.
892 function postLoadTables() {
896 * Reload the conversion tables.
900 function reloadTables() {
901 if ( $this->mTables
) {
902 unset( $this->mTables
);
905 $this->mTablesLoaded
= false;
906 $this->loadTables( false );
910 * Parse the conversion table stored in the cache.
912 * The tables should be in blocks of the following form:
919 * To make the tables more manageable, subpages are allowed
920 * and will be parsed recursively if $recursive == true.
922 * @param string $code Language code
923 * @param string $subpage Subpage name
924 * @param bool $recursive Parse subpages recursively? Defaults to true.
928 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
931 $key = 'Conversiontable/' . $code;
933 $key .= '/' . $subpage;
935 if ( array_key_exists( $key, $parsed ) ) {
939 $parsed[$key] = true;
941 if ( $subpage === '' ) {
942 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
945 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
946 if ( $title && $title->exists() ) {
947 $revision = Revision
::newFromTitle( $title );
949 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
950 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
953 // @todo in the future, use a specialized content model, perhaps based on json!
958 # Nothing to parse if there's no text
959 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
963 // get all subpage links of the form
964 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
965 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
967 $subs = StringUtils
::explode( '[[', $txt );
969 foreach ( $subs as $sub ) {
970 $link = explode( ']]', $sub, 2 );
971 if ( count( $link ) != 2 ) {
974 $b = explode( '|', $link[0], 2 );
975 $b = explode( '/', trim( $b[0] ), 3 );
976 if ( count( $b ) == 3 ) {
982 if ( $b[0] == $linkhead && $b[1] == $code ) {
983 $sublinks[] = $sublink;
987 // parse the mappings in this page
988 $blocks = StringUtils
::explode( '-{', $txt );
991 foreach ( $blocks as $block ) {
993 // Skip the part before the first -{
997 $mappings = explode( '}-', $block, 2 )[0];
998 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
999 $table = StringUtils
::explode( ';', $stripped );
1000 foreach ( $table as $t ) {
1001 $m = explode( '=>', $t, 3 );
1002 if ( count( $m ) != 2 ) {
1005 // trim any trailling comments starting with '//'
1006 $tt = explode( '//', $m[1], 2 );
1007 $ret[trim( $m[0] )] = trim( $tt[0] );
1011 // recursively parse the subpages
1013 foreach ( $sublinks as $link ) {
1014 $s = $this->parseCachedTable( $code, $link, $recursive );
1019 if ( $this->mUcfirst
) {
1020 foreach ( $ret as $k => $v ) {
1021 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1028 * Enclose a string with the "no conversion" tag. This is used by
1029 * various functions in the Parser.
1031 * @param string $text Text to be tagged for no conversion
1032 * @param bool $noParse Unused
1033 * @return string The tagged text
1035 public function markNoConversion( $text, $noParse = false ) {
1036 # don't mark if already marked
1037 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1041 $ret = "-{R|$text}-";
1046 * Convert the sorting key for category links. This should make different
1047 * keys that are variants of each other map to the same key.
1049 * @param string $key
1053 function convertCategoryKey( $key ) {
1058 * Refresh the cache of conversion tables when
1059 * MediaWiki:Conversiontable* is updated.
1061 * @param Title $titleobj The Title of the page being updated
1063 public function updateConversionTable( Title
$titleobj ) {
1064 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1065 $title = $titleobj->getDBkey();
1066 $t = explode( '/', $title, 3 );
1068 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1069 if ( $this->validateVariant( $t[1] ) ) {
1070 $this->reloadTables();
1077 * Get the cached separator pattern for ConverterRule::parseRules()
1080 function getVarSeparatorPattern() {
1081 if ( is_null( $this->mVarSeparatorPattern
) ) {
1082 // varsep_pattern for preg_split:
1083 // text should be splited by ";" only if a valid variant
1084 // name exist after the markup, for example:
1085 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1086 // <span style="font-size:120%;">yyy</span>;}-
1087 // we should split it as:
1089 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1090 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1094 foreach ( $this->mVariants
as $variant ) {
1095 // zh-hans:xxx;zh-hant:yyy
1096 $pat .= $variant . '\s*:|';
1097 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1098 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1101 $this->mVarSeparatorPattern
= $pat;
1103 return $this->mVarSeparatorPattern
;